/*
 * File is ment to load dynamic content to statically builded pages TaDa!
 * */


$(function(){
    //alert("here we are");
    //collecting elemtns to dLoad
   var ajax_params = {};
   ajax_params["rand"] = Math.random();
   $.each($('.dload'), function(index, element){
       ajax_params[element.id] = 1;
    });
    
   //requesting for collected elements contents
   init_request();
   $.ajax({url:'/ajax-dloader',
       data: ajax_params,
       dataType:'json',
       success: function(data, textStatus, jqXHR){
            for(var i = 0; i < data.length ; i++){
                resp_part = data[i];
                $(resp_part['element']).html(resp_part['html'])
            }
            request_is_done();
        },
        error: trigger_error
    });
  //now the filters
  //in case we have any 
  //setting values, which are currently turned ON ahould be used only in casse of 
  if ($(".form_filter").length > 0){
      //init_request_filter();
      var params = {}
      params['slug'] = $("#curent-category-slug").val();
      var sp_b = $(".speical_brand");
      if( sp_b.length > 0 ){
        params["brand"] = $(".speical_brand").attr("id");
      }
      /*$.ajax({url:'/ajax-get-filter-state',
        dataType:'json',
        data: params,
        success: function(data, textStatus, jqXHR){
            if (data['products']){
                $('.col_main').html(data['products']);
                reinit_custom_selects();
                init_add_to_cart_markers();
                init_pages_and_ordering();
            }
            //request_is_done_filter();
            //disabling all, and turning ON All links
            $("input.check_area").attr("checked",function(index, val){
                var id_ar = $(this).attr('id').split(':');
                if(id_ar.length > 1 && id_ar[1] == 'all'){
                    return true;
                }
                return false;
            });
            //setting up turnings on with respect to returned data for filters
            for(var i =0; i < data['product_filter'].length ; i++){
                var f_arr = data['product_filter'][i];
                for(var t =0; t < f_arr[1].length; t ++){
                    //console.debug($("input[id=" + f_arr[0] + ":" + f_arr[1][t] + "]"));
                    $("input[id=" + f_arr[0] + ":" + f_arr[1][t] + "]").attr("checked", true);
                    $("input[id=" + f_arr[0] + ":all]").attr("checked", false);
                    $("input[id=" + f_arr[0] + ":all]").attr("disabled", false);
                }
            }
            //setting up turnings on with respect to returned data for price filters
        },
        error: trigger_error
        });*/
        
        //now we are setting
        $("input.check_area").click(function(){
            //alert('Under Construction now.');
            //ie fires change only after focus leave.... wich is sucks.
            
            //first taking care over nice way of handling all/custom state
            
            var id_ar = $(this).attr('id').split(':');
            if(id_ar.length > 1 ){
                if( id_ar[1] == 'all'){
                    //in case it's all chbox, 
                    if($(this).attr('checked')){
                        // need to disable all others
                        $.each($("input.check_area"), function(index,element ){
                            var c_id_ar = element.id.split(':');
                            if(c_id_ar.length > 1 && c_id_ar[1] != 'all' && c_id_ar[0] == id_ar[0] ){
                                $(element).attr('checked', false);
                            }
                        });
                        
                    }else{
                        //not allowed user can not disble this option by just clicking on it
                        $(this).attr('checked', true);
                    }
                }else{
                    //any custom non - all chbox
                    if($(this).attr('checked')){
                        // checking off all chbox
                        $("input[id=" + id_ar[0] + ":all]").attr('checked', false);
                    }else{
                        // enabling all link, in case there is no similar chboxes turned on
                        // so basically we are looking for at least one non checked non all checkbox in save property group 
                        var any_more_selected = false;
                        $.each($("input.check_area"), function(index,element ){
                            var c_id_ar = element.id.split(':');
                            if(c_id_ar.length > 1 && c_id_ar[0] == id_ar[0] && c_id_ar[1] != 'all' && $(element).attr('checked')){
                                any_more_selected = true;
                                
                            }
                        });
                        if (!any_more_selected)
                            $("input[id=" + id_ar[0] + ":all]").attr('checked', true);
                    }
                }
            }
            //no need on collecting, once we rebuilding to the regular submit
            //instead we are just submiting form
            //reseting start from value, since new filter will be applied
            $('#serv-start').val('0');
            $(".form_filter form").submit();
        });//checkbox onclick handler ends
        /*
         * reinit_custom_selects();
                init_add_to_cart_markers();
                init_pages_and_ordering();
                request_is_done();
         * */
  }
   //on the customer page, to repeat order
   $(".form-order-repeat").each(function(){
       var options = { target: null, // target element(s) to be updated with server response
            form_el:$(this),
            dataType:'json', 
            complete:function(xHr, statusText){
              window.location = '/cart';
            }/*,
            success: function(data){
                alert('success');
                window.location = '/cart';
            }*/
        }
       $(this).ajaxForm(options);
    });
    
    
});

$(function(){
    //+ one more future ajax ordering
    init_pages_and_ordering();
    //TODO:: add code to display full text and hide it on clicks 
    //ids:#part-text .all-link
    $("#part-text .all-link").click(function(e){
        $("#part-text").css("display",'none');
        $("#full-text").css("display",'block');
    });
    $("#full-text .all-link-hide").click(function(e){
        $("#full-text").css("display",'none');
        $("#part-text").css("display",'block');
    });
    //ids:#full-text .all-link-hide
    
    });
    
/*function refresh_product_ordered_paged(){
    console.debug($(".form_nav").formSerialize());
} */   
function remove_order_and_page_on_def_vals(){
    page_val = $("#serv-start").val();
    if (page_val == 0){
        $("#serv-start").remove();
    }
    order_value = $("#serv-sorting").val();
    if(order_value == 'price'){
        $("#serv-sorting").remove();
    }
}
function init_pages_and_ordering(){
    //basically page links init only 
    $("ul.num_page li a").click(function(e){
        e.preventDefault();
        params = {};
        var href = $(this).attr('href');
        if(href){
            var cparams = href.split("?");
            if (cparams.length > 1){
                cparams_arr = cparams[1].split('=');
                params[cparams_arr[0]] = cparams_arr[1];
                if($("#serv-start").length > 0){
                    $("#serv-start").val(cparams_arr[1]);
                }else{
                    $('.form_filter form').append('<input id="serv-start" type="hidden" name="' + cparams_arr[0] + '" value="'+cparams_arr[1] +'"/>');
                }
                remove_order_and_page_on_def_vals();
                $('.form_filter form').submit();
                
                
                
            }
        }else{
            return false;
        }
        

    });
}

window.ajax_request_running_num = 0;
window.ajax_request_running_filter_num = 0;

//blur content for filters update
function init_request_filter(){
    window.ajax_request_running_filter_num ++;
    set_blur_filter();
}
function request_is_done_filter(){
    if(window.ajax_request_running_filter_num > 0)
        window.ajax_request_running_filter_num --;
    set_blur_filter();
}

function blur_content_filters(){
    var $bc ;
    if($("#blur-content").length > 0){
        $bc = $($("#blur-content")[0]);
    }else{
        $bc = $('<div id="blur-content"></div><div id="blur-content-message"><div class="info_message"><img alt="" src="/media/catapulta/images/iconcat_info.png"><span><b>\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u044e.</b><br/>\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430 \u043f\u043e\u0434\u043e\u0436\u0434\u0438\u0442\u0435.</span></div></div>').appendTo('body');
        
    }
    var $content = $("#content");
    cont_of = $content.offset();
    $bc.css('top', cont_of.top + "px");
    $bc.css('left', cont_of.left + "px");
    $bc.css('width', $content.outerWidth() + "px");
    $bc.css('height', $content.outerHeight() + "px");
    $bc.css('display', 'block');
    $("#blur-content-message").css('display', 'block');
    
}

function unblur_content_filters(){
    //$("#blur-content").css('display', 'none');
    $("#blur-content").css('top', '-100000px');
    $("#blur-content").css('left', '-100000px');
    $("#blur-content-message").css('display', 'none');
}
function set_blur_filter(){
    
    if (window.ajax_request_running_filter_num > 0){
         blur_content_filters();
    }else{
        unblur_content_filters();
    }
    
}
    
//regular blur currently non - active
function init_request(){
    return false;
    window.ajax_request_running_filter_n ++;
    set_blur();
}
function request_is_done(){
    return false;
    if(window.ajax_request_running_num > 0)
        window.ajax_request_running_num --;
    set_blur();
}


function set_blur(){
    return false;
    if (window.ajax_request_running_num > 0){
        blur_content();
    }else{
        unblur_content();
    }
}

function unblur_content(){
    return false;
    //$("#blur-content").css('display', 'none');
    $("#blur-content").css('top', '-100000px');
    $("#blur-content").css('left', '-100000px');
    $("#blur-content-message").css('display', 'none');
}


function blur_content(){
    // client dislike this option ... and later whanted it for the filters switching, restoring it  on blur_content_filters
    return false;
    var $bc ;
    if($("#blur-content").length > 0){
        $bc = $($("#blur-content")[0]);
    }else{
        $bc = $('<div id="blur-content"></div><div id="blur-content-message"><div class="info_message"><img alt="" src="/media/catapulta/images/iconcat_info.png"><span><b>\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u044e.</b><br/>\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430 \u043f\u043e\u0434\u043e\u0436\u0434\u0438\u0442\u0435.</span></div></div>').appendTo('body');
        
    }
    var $content = $("#content");
    cont_of = $content.offset();
    $bc.css('top', cont_of.top + "px");
    $bc.css('left', cont_of.left + "px");
    $bc.css('width', $content.outerWidth() + "px");
    $bc.css('height', $content.outerHeight() + "px");
    $bc.css('display', 'block');
    $("#blur-content-message").css('display', 'block');
    //#content
}
function trigger_info(info){
    // client dislike this option ...
    return false;
    //console.debug('info:');
    var $cont = get_message_cont();
    var $element = $('<div class="info_message"><img alt="" src="/media/catapulta/images/iconcat_info.png"><span><b>\u0412\u043d\u0438\u043c\u0430\u043d\u0438\u0435!</b><br/>' + info +  '</span></div>');
    $element = $element.prependTo($cont);
    setTimeout(function() {
      $element.animate({
        opacity: 0.25,
        height: 'toggle',
        width: 'toggle'
      }, 5000, function() {
        // Animation complete.
        //console.debug($element);
        //console.debug($(this));
        $(this).remove();
        toggle_message_compleate();
      });
    }, 3000);
    
}
function toggle_message_compleate(){
    
}
function trigger_error(jqXHR, textStatus, errorThrown){
    request_is_done();
    /*console.debug(errorThrown);
    console.debug(textStatus);
    console.debug(jqXHR);*/
    var error_title = '\u041f\u0440\u043e\u0438\u0437\u043e\u0448\u043b\u0430 \u043e\u0448\u0438\u0431\u043a\u0430.';
    if(errorThrown){
            error_title = '\u041d\u0435\u0432\u0435\u0440\u043d\u044b\u0439 \u043e\u0442\u0432\u0435\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043e\u0448\u0438\u0431\u043a\u0430 ' + textStatus +'(' +  errorThrown + ').';
    }
    var $cont = get_message_cont();
    var $element = $('<div class="error_message"><img alt="" src="/media/catapulta/images/iconcat_error.png"><span><b>' + error_title + '</b><br/>' + jqXHR + '</span></div>');
    $element = $element.prependTo($cont);
    setTimeout(function() {
      $element.animate({
        opacity: 0.25,
        height: 'toggle',
        width: 'toggle'
      }, 5000, function() {
        $(this).remove();
        toggle_message_compleate();
      });
    }, 3000);
            
}
function get_message_cont(){
    var result ;
    if($("#messages-cont").length == 0){
        result = $('<div id="messages-cont"></div>').appendTo('body');
    }else{
        result = $($("#messages-cont")[0]);
    }
    result.css("display",'block');
    return result;
}



