$(function (){
    $.fn.extend({
        imageEntryPreview : function (){
            return this.each(function(){
                img_path = $(this).attr("data-img-ref");
                link = $(this).attr("href");
                id = $(this).attr("id");
                select_winner = $(this).parent('div').attr('data-role');
                is_winner = $(this).parent('div').attr('data-winner-role');
                // Add title "SELECT WINNER" and "WINNER"
                title = '';
                if(select_winner !== undefined) {
                    title = select_winner;
                } else if (is_winner !== undefined) {
                    title = is_winner;
                }
                if($('#entry_obj_enlarged' + $(this).attr("id")).length === 0) {
                    $(this).wTooltip({
                        content : function(){
                            content  = "<a id=\"entry_obj_enlarged" + id + "\" href=\"" + link + "\">";
                            content += "<span class=\"enlarged_title\">" + title + "</span>";
                            content += "<img src=\"" + img_path + "\" />";
                            content += "</a>";
                            return content;
                        }
                    });
                }
            })
        },
        swfEntryPreview : function(){
            return this.each(function(){
                img_path = $(this).attr("data-img-ref");
                link = $(this).attr("href");
                id = $(this).attr("data-entry-id");
                enlarged_width = $(this).attr("data-width");
                real_width = $(this).attr("data-real-width");
                real_height = $(this).attr("data-real-height");
                css_height = Math.round((enlarged_width / real_width) * real_height);

                select_winner = $(this).parent('div').attr('data-role');
                is_winner = $(this).parent('div').attr('data-winner-role');

                // Add title "SELECT WINNER" and "WINNER"
                title = '';
                if(select_winner !== undefined) {
                    title = select_winner;
                } else if (is_winner !== undefined) {
                    title = is_winner;
                }
                if($('#entryobj_enlarged' + $(this).attr("id")).length === 0) {
                    $(this).wTooltip({
                        content: function(){
                            content  = "<a href=\"" + link + "\"";
                            content += "style=\"z-index: 1; position: absolute; width: " + enlarged_width +"px; height: " + css_height + "px; background-color: #FFFFFF; opacity:0;filter:alpha(opacity=1)\"></a>";
                            content += "<span class=\"enlarged_title\">" + title + "</span>";
                            content += "<div id=\"entryobj_enlarged" + id + "\" style=\"width: " + enlarged_width + "px; height: " + css_height + "px;\"></div>";
                            return content;
                        }
                    },function(){
                        flashembed("entryobj_enlarged" + id,
                        {
                            src: img_path,
                            wmode: 'opaque'
                        });
                    });
                }
            });
        },
        avatarifyPrice : function(options){
            return this.each(function(){
                o = {
                    avatarPath : '/assets/general/images/price-avatar/',
                    priceMin : 50,
                    priceAdv : 300,
                    priceExcelentRate : 35,
                    vat : 19,
                    fee : 15,
                    noVat : false,
                    icons : {
                        sad : 'icon-below-min.png',
                        soso : 'icon-average.png',
                        good : 'icon-good.png',
                        master : 'icon-excellent.png'
                    },
                    text : {
                        sad : 'to little',
                        soso : 'moderate',
                        good : 'good',
                        master : 'excellent'
                    },
                    avatarBox : 'price-icon-box',
                    textBox : 'price-icon-text',
                    projectFeeBox : 'project-fee'
                }
                $.extend(o, options);

                c = {
                    projectPrice : 0,
                    projectFee : 0,
                    priceX : 0
                }

                // Calculate excelent price limit
                c.priceX = o.priceAdv + Math.round((o.priceAdv * o.priceExcelentRate)/100);

                $(this).keyup(function(){
                    c.projectPrice = $(this).val();
                    if(c.projectPrice > 0){
                        c.projectPrice = parseInt(c.projectPrice);
                    } else {
                        c.projectPrice = 0;
                    }

                    // Do some math - calculate project fee
                    c.projectFee = ((c.projectPrice * o.fee)/100).toFixed(2);
                    $('#'+o.projectFeeBox).val(c.projectFee);
                    $('#roe_table').processCurrencyTable();

                    if(c.projectPrice < o.priceMin){
                        imagePath = o.avatarPath+o.icons.sad;
                        text = o.text.sad;
                    } else if(c.projectPrice >= o.priceMin && c.projectPrice < o.priceAdv) {
                        imagePath = o.avatarPath+o.icons.soso;
                        text = o.text.soso;
                    } else if(c.projectPrice >= o.priceAdv && c.projectPrice < c.priceX) {
                        imagePath = o.avatarPath+o.icons.good;
                        text = o.text.good;
                    } else if (c.projectPrice >= c.priceX) {
                        imagePath = o.avatarPath+o.icons.master;
                        text = o.text.master;
                    }
                    $('#'+o.avatarBox).css('background','url('+imagePath+')');
                    $('#'+o.textBox).html(text);
                });

                $(this).blur(function(){
                    $(this).trigger('keyup');
                    if(c.projectPrice < o.priceMin){
                        alert(o.minPriceError);
                        $(this).val(o.priceMin);
                        $(this).trigger('keyup');
                    }
                })

                $(this).trigger('keyup');


            });
        },
        processCurrencyTable : function(){
            if ($(this).children('thead').length > 0 && $(this).children('tbody').length > 0){
                var thead = $(this).children('thead');
                var tbody = $(this).children('tbody');
                roeOrder = new Array();
                thead.children('tr').children('th').each(function(k, obj){
                    // get order list of currencies based on data-value in th
                    if(k > 0) {
                        roeOrder[k] = $(obj).attr('data-value').toString();
                        if(roeOrder[k] !== 'local') {
                            $(obj).html(roeList[roeOrder[k]].curr_shortname);
                        }
                    }
                });
                
                tbody.children('tr').each(function(k, row){
                    // get data-row (used for id scraping)
                    var id_selector = $(row).attr('data-row');
                    // get data-cb (if val use .val() if html use .html()
                    // ex. $(#[data-row]).[data-cb]();
                    var cb_method = $(row).attr('data-cb');
                    var native_value = $('#' + id_selector)[cb_method]();
                    
                    $(roeOrder).each(function(k, roeItem){
                        // based on k access same element in current row
                        // write recalculated price in td cell
                        if(roeItem !== undefined && roeList[roeItem] !== undefined) {
                            currency = roeList[roeItem];
                            converted_value = convertCurrency(native_value, currency.curr_roe);
                            $(row).children('td:eq(' + k + ')').html(currency.curr_symbol + ' ' + converted_value);
                        }
                    });
                });

                $('select', this).children('option').attr('selected', false);
                $('select', this).children('option[value="' + roeList.local.curr_shortname + '"]').attr('selected', true);
            }
        },
        applyFilter : function(){
            if($(this).attr('data-filter').length > 0){
                // Explode segment
                $filter  = $(this).attr('data-filter').split('=');
                if($filter.length === 2){
                    fs = $filter[0];
                    fv = $filter[1];
                    if(uriOptions[fs] === null || uriOptions[fs].length > 0){
                        uriOptions[fs] = fv;
                        u = uriOptions;
                        urlPath = '/cat/'+u.cat+'/award/'+u.award+'/left/'+u.left+'/lang/'+u.lang+'/order/'+u.order+'/page/'+u.page;
                        window.location = u.base_url+urlPath;
                    }
                }
            }
        },
        applyOrder : function() {
            if($(this).attr('data-col').length > 0 && $(this).attr('data-dir').length > 0){
                orderCol = $(this).attr('data-col');
                orderDir = $(this).attr('data-dir');
                
                orderString = orderCol+':'+orderDir;
                uriOptions.order = orderString;
                u = uriOptions;
                urlPath = '/cat/'+u.cat+'/award/'+u.award+'/left/'+u.left+'/lang/'+u.lang+'/order/'+u.order+'/page/'+u.page;
                window.location = u.base_url+urlPath;
            }
        },
        applyLang : function() {
            if($(this).attr('data-lang') && $(this).attr('data-lang').length > 0){
                
                selected = $(this).attr('data-lang');
                $(this).toggleClass('selected');
                
                $('input[type="checkbox"][class="language"]').each(function(k, obj){
                    if ($(obj).val() == selected) {
                        if ($(obj).is(':checked') == true) {
                            $(obj).attr('checked',false);
                        } else {
                            $(obj).attr('checked',true);
                        }
                    }
                });
            }
            
            if ($(this).val() && $(this).val().length > 0) {
                selected = $(this).val();
                if ($(this).is(':checked') == true) {
                    $(this).attr('checked',true);
                } else {
                    $(this).attr('checked',false);
                }
                $(this).parent('label').toggleClass('selected');
            }
            
            langs = [];
            $('input[type="checkbox"][class="language"]').each(function(k, obj){
                if ($(obj).attr('checked') && $(obj).attr('checked').length > 0 && $(obj).attr('checked') == 'checked') {
                    langs.push($(obj).val());
                }
            });
            if (langs.length > 0) {
                uriOptions.lang = langs.join(':');
            }            
            u = uriOptions;
            urlPath = '/cat/'+u.cat+'/award/'+u.award+'/left/'+u.left+'/lang/'+u.lang+'/order/'+u.order+'/page/'+u.page;
            window.location = u.base_url+urlPath;
        },
        preselectLang : function() {
            langs = uriOptions.lang.split(':');
            $('input[type="checkbox"][class="language"]').each(function(k, obj){
                if ($.inArray($(obj).val(), langs) > -1) {
                    $(obj).attr('checked', true);
                    $(obj).parent('label').toggleClass('selected');
                }
            });
        },
        preselectFilter : function(caller, content, filter){
            u = uriOptions;
            text = $(content).find('a[data-filter="'+filter+'='+u[filter]+'"]').html();
            if(text !== null && text.length > 0){
                $(caller).html(text);
            }
        },
        entryFilters : function(){
            $(this).children('select').bind('change', function(){
                filterUrl = '/order/'+$('#order').val()+'/rate/'+$('#rate').val()+'/feedback/'+$('#feedback').val();
                window.location = projectUrl+filterUrl;
            });
        },
        reinitEditForm: function() {
          $(".more_info").click(function (){
                $(this).parent().parent().next(".info").slideToggle();
            });
            
            $('.datepicker').datepicker({
                minDate: '+2D',
                maxDate: project_end_date,
                dateFormat: 'yy-mm-dd',
                numberOfMonths: 2
            });
            
            $('.file_holder').each(function(index, val) {
               if($(this).attr('data-flink') !== undefined) {
                   $(this).html('<span class="fdownload" id=fdownload_"' + (index + 1) + '"><a href="' + $(this).attr('data-flink') + '">' + download_text + '</a>'
                                 + '<em><a class="fdelete" data-id="'+ (index + 1) +'">[x]</a></em>');
               } else {
                   $(this).html('<input size="" name="project_file_' + (index + 1) + '" type="file" id="project_file_' + (index + 1) + '" class="fileUploadField">');
               }
            });
            
            $('.fdelete').click(function(event){
                event.preventDefault();
                conf = confirm(fdelete_conf_msg);
                if(conf !== true) {
                    return false;
                }
                var index = $(this).attr('data-id');
                console.log($('.file_holder[data-id="'+index+'"]'));
                $('.file_holder[data-id="'+index+'"]').html('<input size="" name="project_file_' + index + '" type="file" id="project_file_' + index + '" class="fileUploadField">');
                
            });
            
            $('.lang_switch').click(function(event){
               event.preventDefault();
               if(is_changed === true) {
                   conf = confirm(conf_msg);
                   if(conf !== true) {
                       return false;
                   }
               }
               var lang_id = $(this).attr('data-value');
               var url = base_url + 'project/edit/' + project_id + '/' + lang_id + '/ajax';
               $.ajax({
                  type: 'post',
                  url: url,
                  success: function(response) {
                      $('#page-group').html(response);
                      $('#page-group').reinitEditForm();
                  }
               });
            });  
        }
    })

    loader = {
        home : function(){
            $('#wscroller_scroller').vScroll({
                speed: 500,
                height: 170,
                upID: "#recent-projects-up",
                downID: "#recent-projects-down",
                cycle: false
            });
            $('#wordrotate').vScroll({
                speed: 500,
                height: 170,
                upID: "#wordrotate-up",
                downID: "#wordrotate-down",
                cycle: true
            });
            $('#testimonials').vScroll({
                speed: 500,
                height: 170,
                upID: "#testimonials-up",
                downID: "#testimonials-down",
                cycle: true
            });
            $('#home-boxes .blue-box:last-child').addClass('last');
        },
        new_project_step_1 : function(){
            $(".read_more").toggle(
                function (){
                    $(this).text($(this).attr('data-less')),
                    $(this).prev("ul").toggleClass("openedList")
                },
                function (){
                    $(this).text($(this).attr('data-more')),
                    $(this).prev("ul").toggleClass("openedList")
                });
            return false;
        },
        new_project_step_2 : function(){
            $(".more_info").click(function (){
                $(this).parent().parent().next(".info").slideToggle();
            });
            $("input[type=radio][name=project_type]").click(function(){
                if($(this).val() === '3'){
                    $('#project-access-type').show();
                } else {
                    $('#project-access-type').hide();
                }
            });
            $('#project_award').avatarifyPrice(avataropt);
            $('#roe_table').css('display', 'none');
            $('#roe_table').processCurrencyTable();

            $('#roe_table th').children('select').change(function(event){
                var local_curr = $(this).val();
                $.ajax({
                    url: base_url + 'project/ajax_get_currency/' + local_curr,
                    dataType: 'json',
                    type: 'post',
                    success: function(response) {
                        roeList.local = response;
                        $('#roe_table').processCurrencyTable();
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#roe_table').processCurrencyTable();
                    }
                });
            });
            $('.datepicker').datepicker({
                minDate: '+7D',
                maxDate: "+1M",
                dateFormat: 'yy-mm-dd',
                numberOfMonths: 2
            });
        },
        new_project_step_3 : function(){
            
            $(".more_info").click(
                function (){
                    $(this).parent().parent().next(".info").slideToggle();
                });
           
            $('#roe_table').processCurrencyTable();

            $('#roe_table th').children('select').change(function(event){
                var local_curr = $(this).val();
                
                $.ajax({
                    url: base_url + 'project/ajax_get_currency/' + local_curr,
                    dataType: 'json',
                    type: 'post',
                    success: function(response) {
                        roeList.local = response;
                        $('#roe_table').processCurrencyTable();
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#roe_table').processCurrencyTable();
                    }
                });
            });
           
            $('#check_discount').click(
                function(){
                    //var discount_code = $('#discount_code').val();
                    var msg = $(this).attr('data-msg');
                    var project_id = $('#project_id').val();
                    var discount_code = prompt(msg);
                    
                    if(discount_code !== null && project_id > 0) {
                        var action_url = base_url + 'project/ajax_validate_discount';
                        var post_data = "discount_code=" + discount_code 
                        + '&' + "project_id=" + project_id;
                        var holder_element = $('.right_form_column');
                        
                        $.ajax({
                            url: action_url,
                            type: 'post',
                            data: post_data,
                            dataType: 'json',
                            beforeSend: function(object, settings) {
                                // *** blocks ul#discount
                                holder_element.block({
                                    message: '<span class="discount_loader"></span>',
                                    css: {
                                        border: '0',
                                        background: 'none',
                                        'margin-left': '8px'
                                    },
                                    overlayCSS: {
                                        width: '260px'
                                    }
                                });
                            },
                            success: function(response) {
                                holder_element.unblock();
                                var foreign_status = $('#show_foreign').attr('data-state');
                                if(response.status === 'valid') {
                                    discountCosts = {
                                        admin_cost: response.data.admin.cost,
                                        admin_cost_vat: response.data.admin.vat,
                                        admin_cost_total: response.data.admin.total,
                                        project_cost: nativeCosts.project_cost,
                                        project_cost_fee: response.data.success.cost,
                                        project_cost_vat: response.data.success.vat,
                                        project_cost_total: response.data.success.total
                                    }
                                    $('#discount_list .discount_item strong').html(discount_code);
                                    $('#discount_list').css('display', 'block');
                                } else {
                                    discountCosts = null;
                                    $('#discount_list').css('display', 'none');
                                }
                                if(foreign_status === 'shown'){
                                    recalculateCostList(roeList.local.curr_shortname);
                                } else {
                                    foreign_curr = roeList.local.curr_shortname;
                                    recalculateCostList('EUR');
                                    roeList.local.curr_shortname = foreign_curr;
                                }
                                $('#discount_code').val(discount_code);
                                alert(response.message);
                            },
                            error: function(object, text, err_type) {
                                alert('Server error!');
                            }
                        });
                    }
                    
                    return false;
                });
                
            $('#show_foreign').click(function(){
                var state = $(this).attr('data-state');
                switch(state) {
                    case 'hidden':
                        $('[data-group="foreign"]').each(function(k, elem) {
                            $(elem).css('display', 'block');
                        });
                        recalculateCostList(roeList.local.curr_shortname);
                        $(this).html($(this).attr('data-hide-label'));
                        $(this).attr('data-state', 'shown');
                        break;
                    case 'shown':
                        $('[data-group="foreign"]').each(function(k, elem) {
                            $(elem).css('display', 'none');
                        });
                        foreign_curr = roeList.local.curr_shortname;
                        recalculateCostList('EUR');
                        roeList.local.curr_shortname = foreign_curr;
                        $(this).html($(this).attr('data-show-label'));
                        $(this).attr('data-state', 'hidden');
                        break;
                }
                return false;
            });
            $('#discount_reset').click(function(event) {
                $('#discount_code').val();
                discountCosts = null;
                var foreign_status = $('#show_foreign').attr('data-state');
                if(foreign_status === 'shown'){
                    recalculateCostList(roeList.local.curr_shortname);
                } else {
                    foreign_curr = roeList.local.curr_shortname;
                    recalculateCostList('EUR');
                    roeList.local.curr_shortname = foreign_curr;
                }
                $('#discount_list').css('display', 'none');
            });
            $('#discount_list').css('display', 'none');
        },
        project_list : function(){
            // BUTTONS
            $('.fg-button').hover(
                function(){
                    $(this).removeClass('ui-state-default').addClass('ui-state-focus');
                },
                function(){
                    $(this).removeClass('ui-state-focus').addClass('ui-state-default');
                }
                );
            // *** filter dropdowns
            $('#cat_filter_btn').menu({
                content: $('#cat_filter').html(),
                onclick : function(item){
                    $(item).applyFilter();
                },
                onload : function(caller, content){
                    $(this).preselectFilter(caller, content, 'cat');
                },
                backLink: false,
                flyOut: true,
                followLink : false,
                width : 320
            });
            
            $('.order').click(function(){
                $(this).applyOrder();
                return false;
            })
            
            $(document).preselectLang();
            $('.lang-mark').click(function(){
                $(this).applyLang();
                return false;
            })
            $('input.language').click(function(){
                $(this).applyLang();
                return false;
            })
            
            $('#award_filter_btn').menu({
                content: $('#award_filter').html(),
                onclick : function(item){
                    $(item).applyFilter();
                },
                onload : function(caller, content){
                    $(this).preselectFilter(caller, content, 'award');
                },
                backLink: false,
                flyOut: true,
                followLink : false
            });

            $('#left_filter_btn').menu({
                content: $('#left_filter').html(),
                onclick : function(item){
                    $(item).applyFilter();
                },
                onload : function(caller, content){
                    $(this).preselectFilter(caller, content, 'left');
                },
                backLink: false,
                flyOut: true,
                followLink : false
            });
            $('.change_lang').click(function(e) {
                lang_id = $(this).attr('data-lang');
                project_id = $(this).attr('data-project');
                action_url = base_url + 'project/ajax_get_lang/' + project_id + '/' + lang_id + '/?redirect=1';
                $.ajax({
                    url: action_url,
                    type: 'get',
                    success: function(response) {
                        response = $.parseJSON(response);
                        if(response.status === false) {
                            return false;
                        }
                        
                        $.cookies.set('bs_lang_cookie' + project_id, lang_id, {
                            expiresAt: new Date('2592000000'), 
                            secure: false
                        });

                        window.location = response.redirect;
                        return true;
                    }
                });
            });
        },
        project : function(){
            $(".entry_preview").imageEntryPreview();
            $('.entry_swf_preview').swfEntryPreview();
            $('.star').rating();
            $('#selectfilters').entryFilters();
            //*** Report system - dialog settings
            $('#report_dialog').dialog({
                width: 600,
                height: 400,
                autoOpen: false,
                modal: true,
                resizable: false,
                zIndex: 3,
                draggable: false,
                buttons: [{
                    text: $('#report_dialog').attr('data-label-cancel'),
                    click: function() {
                        $('#report_dialog').dialog('close');
                    }
                },
                {
                    text: $('#report_dialog').attr('data-label-ok'),
                    click: function() {
                        var data = 'report_user_id='+$('#report_user_id').val()
                        + '&report_ref_link='+$('#report_ref_link').val()
                        + '&report_subject='+$('#report_subject').val()
                        + '&report_text='+$('#report_text').val()
                        + '&report_contact='+$('#report_contact').val()
                        + '&report_entry_id='+$('#report_entry_id').val()
                        + '&report_copyright_link='+$('#report_copyright_link').val()
                        + '&report_copyright_img='+$('#report_copyright_img').val()
                        + '&report_user_name='+$('#report_user_name').val()
                        + '&report_check='+$('#bot_quest').val();
                        $.ajax({
                            url: base_url + 'report/process_new_report',
                            type: 'post',
                            data: data,
                            success: function(data) {
                                alert(data);
                                if(data !== 'Please answer correct to antispam question!') {
                                    $('#report_subject,#report_text').val('');
                                    $('#report_dialog').dialog('close');
                                }
                            }
                        });
                    }
                }]
            });
            
            $('#home_carousel').jcarousel({
                step: 1
            });
            
            $('.change_lang').click(function(e) {
                lang_id = $(this).attr('data-lang');
                project_id = $(this).attr('data-project');
                action_url = base_url + 'project/ajax_get_lang/' + project_id + '/' + lang_id;
                $.ajax({
                    url: action_url,
                    type: 'get',
                    success: function(response) {
                        response = $.parseJSON(response);
                        if(response.status === false) {
                            return false;
                        }
                        
                        $('#project_company_description p').html(response.project_company_description);
                        $('#project_requirements p').html(response.project_requirements);
                        $('#project_audience p').html(response.project_audience);
                        $('#project_details p').html(response.project_details);
                        $('h1.page_title').html('<span class="dot yellow"></span>' + response.project_title);
                        
                        $('.project_files').html('');
                        
                        $.each(response.files, function(index, file){
                            $('.project_files').append("<li><a href=\""+file.path+"\">"+file.name+"</a></li>");
                        })
                        $.cookies.set('bs_lang_cookie' + project_id, lang_id, {
                            expiresAt: new Date('2592000000'), 
                            secure: false
                        });
                        return true;
                    }
                });
            });
            
            $('a[data-role="pendingEdit"]').click(function(event){
                conf_text = $(this).attr('data-value');
                res = confirm(conf_text);
                if(res !== true) {
                    return false;
                }
                
                return true;
            });
        },
        select_winner: function() {
            
            // *** PAYMENT DIALOG BEGIN
            $('#payment_dialog').dialog({
                autoOpen: false,
                width: 550,
                resizable: false,
                draggable: false,
                modal: true,
                buttons: 
                [{
                    text: $('#payment_dialog').attr('data-ok-trans'),
                    click: function() {
                        modal_offset = $('#payment_dialog').parent().offset();
                        modal_width = $('#payment_dialog').parent().width() + 5;
                        modal_height = $('#payment_dialog').parent().height() + 5;

                        $('#dialog_mask').css('top', modal_offset.top);
                        $('#dialog_mask').css('left', modal_offset.left);
                        $('#dialog_mask').css('width', modal_width  + 'px');
                        $('#dialog_mask').css('height', modal_height + 'px');
                        $('#dialog_mask_text').css('line-height', modal_height + 'px');
                        $('#dialog_mask').css('z-index', '9999');
                        $('#dialog_mask').css('display', 'block');
                        $('#dialog_mask').css('background-color', '#FFF');

                        form_data = $('#select_winner_form').serialize();
                        payment_data = $('#pay_form').serialize();
                        action_url = $('#select_winner_form').attr('action');

                        $.ajax({
                            url: action_url,
                            type: 'post',
                            data: form_data + '&' + payment_data,
                            success: function(data) {
                                $('#error_container').css('display', 'none');
                                data = $.parseJSON(data);
                                if(data.error !== undefined ) {
                                    $('#dialog_mask').css('display', 'none');
                                    $('#error_container span').html(data.error);
                                    $('#error_container').css('display', 'block');
                                    return false;
                                } else if(data.success !== undefined) {
                                    window.location = data.success;
                                }
                            }
                        })
                    }
                },
                {
                    text: $('#payment_dialog').attr('data-cancel-trans'),
                    click: function() {
                        $('#payment_dialog').dialog('close');
                        $('#error_container').css('display', 'none');
                    }
                }],
                close: function(event, ui) {
                    $('#dialog_mask').css('display', 'none');
                    $('#error_container').css('display', 'none');
                }
            });
            // *** PAYMENT DIALOG END
            
            $('#show_foreign').click(function(){
                var state = $(this).attr('data-state');
                switch(state) {
                    case 'hidden':
                        $('[data-group="foreign"]').each(function(k, elem) {
                            $(elem).css('display', 'block');
                        });
                        recalculateCostList(roeList.local.curr_shortname);
                        $(this).html($(this).attr('data-hide-label'));
                        $(this).attr('data-state', 'shown');
                        break;
                    case 'shown':
                        $('[data-group="foreign"]').each(function(k, elem) {
                            $(elem).css('display', 'none');
                        });
                        foreign_curr = roeList.local.curr_shortname;
                        recalculateCostList('EUR');
                        roeList.local.curr_shortname = foreign_curr;
                        $(this).html($(this).attr('data-show-label'));
                        $(this).attr('data-state', 'hidden');
                        break;
                }
                return false;
            });
            
            //*** bind opening on selection
            $('a.selectioner').bind('click', function(e){
                e.preventDefault();
                $('#payment_dialog').dialog('open');
                return false;
            });
        
            $("select").click(function(){
                recalculatePrice();
            });
            $('#cc').click(function(){
                recalculatePrice();
            });
            $('#paypal').click(function(){
                recalculatePrice();
            });
        
        },
        faq : function(){
            $('.tabs').tabs();
        },
        common : function(){
            $('#search').keydown(function(e) {
                if(e.keyCode === 13 && $(this).val().length > 2) {
                    search_string = $(this).val();
                    window.location = base_url + 'search/' + search_string;
                    return false;
                }
            });
            $('.search-form').bind('submit', function(){
                search_string = $('#search').val();
                window.location = base_url + 'search/' + search_string;
                return false;
            });
            $('#login').click(function() {
                $('#login-sub').toggle();
                return false;
            });
            $('#login-sub').find('input').each(function(k, object){
                if ($(object).attr('data-default')) {
                    $(object).bind('focus', function(){
                        if ($(object).attr('data-default') === $(object).val()) {
                            $(object).val('');
                        }
                    });
                    $(object).bind('blur', function(){
                        if ($(object).val() === '') {
                            $(object).val($(object).attr('data-default'));
                        }
                    });
                }
            });
            $('#languages a').click(function() {
                $('#languages-sub').toggle();
                return false;
            });
        },
        shop_item: function() {
            $(document).ready(function(){
                calculatePrice();
            })
        },
        shop_list: function() {
            
            $('#search_string').keypress(function(event){
                if(event.keyCode === 13 && $(this).val().length > 0) {
                    $('#search_submit').submit();
                }
            });
            
            $('#search_form').submit(function(event) {
                event.preventDefault();
                if($('#search_string').val().length > 0) {
                    action_url = $(this).attr('action') + '/' +  encodeURI($('#search_string').val());
                    window.location = action_url;
                }
            });
        },
        project_edit_local: function() {
            $('#page-group').reinitEditForm();
        },
        login: function() {
            $('#login_form input').keyup(function(obj){
                if(obj.keyCode === 13) {
                    $('#login_form').submit();
                }
            });
        },
        register: function() {
            $('#user_registration input').keyup(function(obj){
                if(obj.keyCode === 13) {
                    $('#user_registration').submit();
                }
            });
        }
    }
    $.extend($, loader.common());
    if($('#page-group').length > 0){
        method = $('#page-group').attr('data-page');
        $.extend($, loader[method]());
    }
    
    $('#languages-sub li a').click(function(event){
        event.preventDefault();
        domain = $(this).prop('href');
        token = $.cookies.get('guest');
        redirect = domain + '/auth/get_redirection/' + token
        window.location = redirect;
        return false;
    });
});

function rate_request(entry_id,mark){
    $.ajax({
        type: "GET",
        url: base_url+"project/ajax_rate_entry_request/"+entry_id+"/"+mark,
        success: function(){
            setTimeout("load_rate('"+entry_id+"')",500)
        }
    });
}

function load_rate(entry_id){
    $.ajax({
        url: base_url+"project/ajax_load_rating/"+entry_id,
        success: function(html){
            $("#rateBox"+entry_id).html(html);
            $('input.star'+entry_id).rating({
                callback:function(value,link){
                    rate_request(entry_id,value);
                }
            });
        }
    });
}

function reportLink(id) {
    $('#report_entry_id').val(id);
    $('#report_dialog').dialog('open');
    return false;
}

function switch_user_reg_type(value) {
    switch(value) {
        case 'designer':
            $('.designer_only').css('display', 'block');
            $('.company_only').css('display', 'none');
            break;
        case 'company':
            $('.designer_only').css('display', 'none');
            $('.company_only').css('display', 'block');
            break;
    }
}
function ptoggle(id){
    $("#"+id).toggle("fast");
    return false;
}

function roundNumber(num,delimiter){
    if(!delimiter){
        delimiter = ".";

    }
    num = Math.round(num*100)/100;
    num = num.toString();
    if(num.indexOf('.') === false){
        split_simbol = ',';
    } else {
        split_simbol = '.';
    }
    var split = num.split(split_simbol);
    if(!split[1]){
        split[1] = '00';
    } else {
        if(split[1].length  < 2){
            split[1] = split[1]*10;
        }
    }
    num = split[0]+delimiter+split[1];
    return num;
}

function calculatePrice(){    
    if($('#exc_purchase').attr('checked') == 'checked'){
        total_price = std_price + exc_price;
    } else {
        total_price = std_price;
    }

    $('#totalPrice').html(roundNumber(total_price));
}

function switch_tab($id) {
    switch($id) {
        case 'participated':
            $('#participated').css('display', 'block');
            $('#won').css('display', 'none');
            break;
        case 'won':
            $('#participated').css('display', 'none');
            $('#won').css('display', 'block');
            break;
    }
}

function removeEntry(entry_id, confirm_msg)
{
    if(confirm(confirm_msg)){
        window.location = base_url+"project/process_remove_entry/"+entry_id;
    }    
}

function convertCurrency(value, roe) {

    result = value * roe;
    result = roundNumber(result);
    return result;
}

function recalculateCostList(curr_shortname) {
    var local_curr = curr_shortname;
    var costs = nativeCosts;
    if(roeList[local_curr] === undefined) {
        $.ajax({
            url: base_url + 'project/ajax_get_currency/' + local_curr,
            dataType: 'json',
            type: 'post',
            async: false,
            success: function(response) {
                roeList.local = response;
            },
            error: function(object, event, code) {
                $('#local_curr option').attr('selected', false);
                $('#local_curr option[value="' + roeList.local.curr_shortname + '"]').attr('selected', true);
            }
        });
    }
    
    if(typeof discountCosts !== 'undefined' && discountCosts !== null) {
        costs = discountCosts;
    }
    
    fcurr = roeList.local;
    // *** change currency symbol to new one
    $('span.currency_symbol').html(fcurr.curr_symbol);
    
    // *** recalculate all fields to converted values
    $('#admin_cost').html(convertCurrency(costs.admin_cost, fcurr.curr_roe));
    $('#admin_cost_vat').html(convertCurrency(costs.admin_cost_vat, fcurr.curr_roe));
    $('#admin_cost_total').html(convertCurrency(costs.admin_cost_total, fcurr.curr_roe));
    $('#project_cost').html(convertCurrency(costs.project_cost, fcurr.curr_roe));
    $('#project_cost_fee').html(convertCurrency(costs.project_cost_fee, fcurr.curr_roe));
    $('#project_cost_vat').html(convertCurrency(costs.project_cost_vat, fcurr.curr_roe));
    $('#project_cost_total').html(convertCurrency(costs.project_cost_total, fcurr.curr_roe));
    
    // *** checkc if we have cc_fee field
    if($('#cc_fee').length > 0 && typeof costs.cc_fee !== "undefined") {
        $('#cc_fee').html(convertCurrency(costs.cc_fee, fcurr.curr_roe))
    }
    
    // *** set select currency to local one
    $('#local_curr option').attr('selected', false);
    $('#local_curr option[value="' + fcurr.curr_shortname + '"]').attr('selected', true);
    
    return true;
}
