var from_function = false;
var from_back_click = false;
var view_width = 1024;
var view_height = 768;

jQuery(document).ready(function(){
    jQuery(window).bind( 'hashchange', function(e) {
        hash_handler();
    });

    init_dock_menu();

    hash_handler();

    init_viewport();

    init_lincos_settings();

    init_product_details();

    init_cart();

    init_search();

    if (jQuery('div[name="product_list"]')[0]) {
        imagePreview();
    }
    
    jQuery('html body').append('<input type="hidden" value="" id="tmp_akt_cat_id" /> <input type="hidden" value="" id="tmp_akt_p_id" />');
    jQuery('#statusBox').remove();
});

function init_viewport(){
    view_height = jQuery(window).height();
    view_width = jQuery(window).width();
    var containers = jQuery('#lincos_cat_containers div[name^="category_list_"]');
    var topsl_height = jQuery("#ja-topsl").height();
    var dockmenu = 50;
    var mainnav_height = jQuery("#ja-mainnav").height();
    var calc_height = view_height - mainnav_height - topsl_height - dockmenu - 15;

    if (containers[0]) {
        containers.each(function () {
            jQuery(this).height(calc_height);
        });

        jQuery('#lincos_cat_containers div[name="product_list"]').height(calc_height);
    }else{
        jQuery("#ja-current-content").height(calc_height).css("overflow", "auto");
    }
}

function init_search(){
    jQuery("#keyword").animate({
        width:"95%"
    }, 400).focus();

    jQuery("#keyword").autocomplete(jQuery("#action_url").val(), {
        width: view_width/2,
        max: 50,
        highlight: false,
        scroll: true,
        scrollHeight: (view_height - jQuery("#ja-mainnav").height() - jQuery("#ja-topsl").height()),
        formatItem: function(data, i, n, value) {
            if (value.indexOf("%_%") >= 0) {
                var akt_data = value.split("%_%");
                var image_path = "http://" + baseURL + "/components/com_virtuemart/themes/default/images/noimage.gif";
                if (akt_data[0]) {
                    image_path = "http://" + baseURL + "/components/com_virtuemart/shop_image/product/" + akt_data[0];
                }
                var html = "<table><tr><td rowspan=\"2\"><img width=\"100\" onclick=\"window.location = '"+ akt_data[4] +"'\" border=\"0\" src=\""+image_path+"\"></td><td class=\"result_content\"> <div class=\"p_sku\">" + akt_data[1] + "</div> <div onclick=\"window.location = '"+ akt_data[4] +"'\" name=\"p_name\">" + akt_data[2] + "</div> <p onclick=\"window.location = '"+ akt_data[4] +"'\">" + akt_data[5] + "</p> <p>" + akt_data[6] + "</p> <p>" + akt_data[7] + "</p> </td></tr> <tr><td colspan=\"2\" class=\"result_content\" ><p onclick=\"window.location = '"+ akt_data[4] +"'\" name=\"desc\">" + akt_data[3] + "</p></td></tr></table>";
                return html;
            } else {
                return value;
            }
        }
    });
	
}

function hash_handler() {
    var hash = '-';
    var data;

    if (from_function) {
        from_function = false;
        return;
    } else {
        from_back_click = true;
        hash = window.location.hash.substr(1);
        
        data = hash.split('-');
        if(data[0]=='category'){
            show_category(data[1], data[2]);
        }else{
            if(data[0]=='product_list'){
                load_product_list(data[1], data[2], data[3], data[4]);
            }else{
                if(data[0]=='product_details'){
                    load_product_details(data[1]);
                }else{
                    if(data[0]=='close'){
                        close_container(data[1]);
                    }
                }
            }
        }
    }
    from_back_click = false;
}

function show_category (cat_id, parent_name) {
    jQuery('#pdetails_dialog').dialog('close');

    var akt_cat_div = jQuery("#lincos_cat_containers #category_"+cat_id);
    var sublist = jQuery('div[name="category_sublist"]', akt_cat_div).clone();

    var parent = jQuery('#lincos_cat_containers div[name^="'+parent_name+'"]');
    jQuery('div[class="visited-category"]', parent).attr('class', 'default_border');
    akt_cat_div.attr('class', 'visited-category');
    
    if (sublist.html() != null) {
        insert_sub(parent, sublist.html());
        // navigation
        window.location.hash = "category-"+cat_id+'-'+parent_name;
        if (!from_back_click){
            from_function = true;
        }
    // navigation
    } else {
        load_product_list(parent_name, cat_id, "rank", "desc");
    }

    jQuery('#tmp_akt_cat_id').val(cat_id);
    jQuery('#tmp_akt_p_id').val('');
    set_rank(cat_id, false);
}

function insert_sub(akt_container_div, html){
    var next_number = akt_container_div.attr("name").substr(14);
    next_number *= 1;
    next_number++;
    var new_container_div = jQuery('<div style="float: left; height: '+jQuery('#lincos_cat_containers > div[name="category_list_1"]').height()+'px;" name="category_list_'+next_number+'"></div>').html(
        '<div style="text-align:right; float:left; width:100%; height:5%;"><img style="cursor: pointer;" src="http://'+baseURL+'/media/system/images/container_close.png" onclick="javascript:close_container(\'category_list_'+next_number+'\')" /></div>'+
        '<div name="cat_real_content" style="overflow-y:scroll; height:95%; width:100%; float:left;">'+html+'</div>');

    insert_div(akt_container_div, new_container_div);
}

function insert_pl(parent, html){
    var new_container_div = jQuery('<div name="product_list" style="float: left; position: relative; height: '+jQuery('#lincos_cat_containers > div[name="category_list_1"]').height()+'px;" ></div>').html(html);
    
    insert_div(parent, new_container_div);
}

function insert_pd(parent, html){
    var new_container_div = jQuery('<div name="product_details" style=" overflow-y: scroll; float: left; position: relative; height: '+jQuery('#lincos_cat_containers > div[name="category_list_1"]').height()+'px;" ></div>').html(
        '<img style="cursor: pointer; position: absolute; top: 0px; right: 0px;" src="http://'+baseURL+'/media/system/images/container_close.png" onclick="javascript:close_container(\'product_details\')" >'+
        html);

    insert_div(parent, new_container_div);
}

function insert_div (akt_container_div, new_container_div) {
    del_right_containers (akt_container_div, false);

    //Uj tartalom beszurasa
    jQuery("#lincos_cat_containers").append(new_container_div.css('display', 'none'));

    //Container szelessegek ujraszamolasa
    calc_size();
    
    //Kijelolt elemek scrollozasa
    scroll_divs();

    //Villantas
    new_container_div.fadeIn("slow");
}

function del_right_containers (akt_container_div, self_deleting) {
    var akt_name = akt_container_div.attr('name');
    var flag = false;

    jQuery("#lincos_cat_containers").children().each(function(index) {
        if(!flag && jQuery(this).attr("name") == akt_name){
            flag = true;
            if (!self_deleting) {
                return;
            }
        }
        if (flag) {
            jQuery(this).remove();
        }
    });

    calc_size();

    if (self_deleting) {
        scroll_divs();
    }
}

function calc_size () {
    //Szelessegek ujraszamolasa
    var sublist_count = jQuery('#lincos_cat_containers div[name^="category_list_"]').length;
    var pl_count = jQuery('#lincos_cat_containers div[name="product_list"]').length;

    if (pl_count == 1) {
        sublist_width = 70/sublist_count;
        pl_width = 30;
    }else{
        sublist_width = 100/sublist_count;
        pl_width = 0;
    }

    jQuery('#lincos_cat_containers div[name^="category_list_"]').css("width", sublist_width+"%");
    jQuery('#lincos_cat_containers div[name="product_list"]').css('width', pl_width+'%');
}

function scroll_divs(){
    jQuery('#lincos_cat_containers div[name="cat_real_content"]').each(function() {
        var akt_name = jQuery(this).parent().attr('name');
        jQuery(this).scrollTo( jQuery('#lincos_cat_containers div[name="'+akt_name+'"] div.visited-category'), {
            duration:300
        } );
    });
}

function close_container(name){
    // navigation
    window.location.hash = "close-"+name;
    if (!from_back_click){
        from_function = true;
    }

    if (name == 'category_list_1') {
        del_right_containers(jQuery('#lincos_cat_containers div[name^="'+name+'"]'), false);
    } else {
        del_right_containers(jQuery('#lincos_cat_containers div[name^="'+name+'"]'), true);
    }
}

function load_product_list (parent_name, cat_id, s_name, s_type) {
    var parent = jQuery('#lincos_cat_containers div[name^="'+parent_name+'"]');
    jQuery('#pdetails_dialog').dialog('close');

    // navigation
    window.location.hash = "product_list-"+parent_name+'-'+cat_id+'-'+s_name+'-'+s_type;
    if (!from_back_click){
        from_function = true;
    }
    // navigation

    jQuery.post('http://'+baseURL, {
        "cat_id": cat_id,
        "s_name": s_name,
        "s_type": s_type
    },
    function(data){
        insert_pl(parent, jQuery(data).html());
        imagePreview();
    });
}

function load_product_details (p_id) {
    // navigation
    window.location.hash = "product_details-"+p_id;
    if (!from_back_click){
        from_function = true;
    }
    // navigation

    var akt_p_div = jQuery('#product_'+p_id);
    var default_class = akt_p_div.attr('class');
    var parent = jQuery('div[name="product_list"]');

    jQuery('div[class^="visited-product"]', parent).attr('class', default_class);
    akt_p_div.attr('class', 'visited-product');

    if (jQuery('#lincos_cat_containers')[0]) {
        jQuery('#lincos_cat_containers div[name="product_list"] div[name="pl_real_content"]').scrollTo( akt_p_div, {
            duration:300
        } );
    } else {
        jQuery('#ja-current-content').scrollTo( akt_p_div, {
            duration:300
        } );
    }

    jQuery.post('http://'+baseURL, {
        "p_id": p_id
    },
    function(data){
        var title = jQuery('#dialog_title', data).html();
        jQuery('#pdetails_dialog').html(jQuery(data).html());
        imagePreview();
		jQuery('#dialog_title').css('display', 'none');
        
        jQuery("#pdetails_dialog ul li").css("background-repeat", "no-repeat");
        jQuery('#pdetails_dialog').dialog('option', "title", title);
        jQuery('#pdetails_dialog').dialog('open');

        jQuery('#tmp_akt_p_id').val(p_id);

        load_ask(jQuery('#p_list_cat_id').val(), p_id);
    });

    set_rank(false, p_id);
}

function update_cart_value(source, type) {
	var act_val = jQuery('#'+source).val();
	act_val*=1;
	
	if (type=='inc') {
		jQuery('#'+source).val(act_val+1);
	}else{
		if (act_val>1) {
			jQuery('#'+source).val(act_val-1);
		}
	}
}

function add_to_cart (source, p_id, type) {
    jQuery.post('http://'+baseURL+'/index.php?option=com_content&id=26&tmpl=component', {
        "add_to_cart": 'true',
        "p_id": p_id,
        "cat_id": jQuery('#'+'cat_'+source).val(),
        "p_quantity": jQuery('#'+source).val()
    },
    function(data){
        var cart_full_information = jQuery('#cart_full_information', '<div>'+data+'</div>');
        var cart_short_information = jQuery('#cart_short_information', '<div>'+data+'</div>');

        jQuery('#cart_short_information').fadeOut("fast", function() {
            jQuery(this).html(cart_short_information.html());
            jQuery(this).fadeIn("fast");
        });
        jQuery('#cart_full_information').html(cart_full_information.html());

        // Show info
		var pos_left = jQuery('#'+source).position().left;
        var pos_top = jQuery('#'+source).position().top;
		if (type == 'search') {
			pos_left += 40;
			pos_top -= 30;
		} else {
			pos_left -= 50;
			pos_top -= 50;
		}
        
        jQuery('#'+source).parent().append('<div name="info_'+source+'" style="position: absolute; left: '+pos_left+'px; top: '+pos_top+'px; z-index: 9999999; background-color: #444444; color: white; border-radius: 4px; padding: 3px 5px 3px 5px;">'+update_cart_message+'</div>').fadeIn('slow');
        setTimeout( function() {
            jQuery('div[name="info_'+source+'"]').remove();
	}, 3000 );
    });
}

function sort_p_list (s_name) {
    var parent_name = jQuery('#lincos_cat_containers div[name="product_list"]').prev().attr('name');
    var s_type_img = jQuery('#p_list_sort_'+s_name+' img');
    if (s_type_img[0]) {
        if (s_type_img.attr('name')=='asc') {
            s_type = "desc";
        } else {
            s_type = "asc";
        }
    } else {
        s_type = "asc";
    }
    load_product_list(parent_name, jQuery('#p_list_cat_id').val(), s_name, s_type);
}

function imagePreview () {
    var top = 20;
    var left = 20;
    var tip_height = 535;
    var tip_width = 530;

    jQuery("a.preview").hover(function(e){
        if (e.pageY + tip_height > view_height) {
            top = e.pageY - ((e.pageY + tip_height) - view_height);
        } else {
            top = e.pageY;
        }
        if (e.pageX < tip_width + 10) {
            left = e.pageX + 20;
        } else {
            left = e.pageX - (tip_width + 10);
        }

        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        jQuery("body").append("<div style=\"border-radius: 10px; z-index:99999; position:absolute; border:1px solid #444444; width: 505px; height: 505px; background:url('"+ this.name +"') top left no-repeat; background-color: white; padding:7px; display:none; color:#444444;\" id='preview'><p style=\"width: 100%; text-align: center; font-weight:bold;position:absolute;bottom:3px;left:3px;\">"+ c +"</p></div>");
        jQuery("#preview")
        .css("top",(top) + "px")
        .css("left",(left) + "px")
        .fadeIn("fast");
    },
    function(){
        this.title = this.t;
        jQuery("#preview").remove();
    });
    jQuery("a.preview").mousemove(function(e){
        if (e.pageY + tip_height > view_height) {
            top = e.pageY - ((e.pageY + tip_height) - view_height);
        } else {
            top = e.pageY;
        }
        if (e.pageX < tip_width + 10) {
            left = e.pageX + 20;
        } else {
            left = e.pageX - (tip_width + 10);
        }
        
        jQuery("#preview")
        .css("top",(top) + "px")
        .css("left",(left) + "px");
    });
}

function init_cart(){
    var full_info = jQuery("#cart_full_information");
    jQuery("#cart_full_information").remove();
    jQuery("html body").append(full_info);
}

function init_product_details(){
    var title_tmp = jQuery("#pdetails_dialog_tmp #dialog_title").html();
	jQuery("#pdetails_dialog_tmp #dialog_title").css('display', 'none');
    var html_tmp = jQuery("#pdetails_dialog_tmp").html();
    var autoopen = false;
    if (html_tmp) {
        var tmp_p_id = jQuery('input[id^="pd_value_"]', html_tmp).attr('id').substr(9);
        jQuery('#product_'+tmp_p_id).attr('class', 'visited-product');
        jQuery('#lincos_cat_containers div[name="product_list"] div[name="pl_real_content"]').scrollTo( jQuery('#product_'+tmp_p_id), {
            duration:300
        } );
        autoopen = true;
    }
    jQuery("#pdetails_dialog_tmp").remove();
    jQuery("html body").append('<div id="pdetails_dialog" title="" style="display: none; overflow-y: scroll;">'+html_tmp+'</div>');

    jQuery('#pdetails_dialog').dialog({
        title: title_tmp,
        autoOpen: autoopen,
        bgiframe: true,
        modal: false,
        width:  Math.round(view_width*0.5),
        height: Math.round(view_height*0.9)
    });
    
    jQuery("#pdetails_dialog ul li").css("background-repeat", "no-repeat");
    if (jQuery('#tmp_cat_id')[0]) {
        load_ask(jQuery('#tmp_cat_id').val(), tmp_p_id);
    }
}

function show_cart(){
    jQuery("#cart_full_information").css('top', jQuery("#show_info_img").offset().top + 55);
    jQuery("#cart_full_information").css('left', jQuery("#show_info_img").offset().left - jQuery("#cart_full_information").width() + 30);
    
    if (jQuery("#cart_full_information").is(":hidden") ) {
        jQuery('#cart_full_information').fadeIn('fast');
    } else {
        jQuery('#cart_full_information').fadeOut('fast');
    }
}

function del_cart_item(p_id){
    jQuery.post('http://'+baseURL+'/index.php?option=com_content&view=article&id=26&tmpl=mymodule&moduleposition=cart', {
        "del_from_cart": 'true',
        "p_id": p_id
    },
    function(data){
        var cart_full_information = jQuery('#cart_full_information', '<div>'+data+'</div>');
        var cart_short_information = jQuery('#cart_short_information', '<div>'+data+'</div>');

        jQuery('#cart_short_information').fadeOut("fast", function() {
            jQuery(this).html(cart_short_information.html());
            jQuery(this).fadeIn("fast");
        });
        
        if (cart_full_information.html() == '') {
            jQuery('#cart_full_information').fadeOut("fast");
        }
        jQuery('#cart_full_information').html(cart_full_information.html());
    });
}

function update_cart_item(elem, e){
    if (e.keyCode == 13) {
        if (elem.value >= 1) {
            jQuery.post('http://'+baseURL+'/index.php?option=com_content&view=article&id=26&tmpl=mymodule&moduleposition=cart', {
                "update_from_cart": 'true',
                "p_quantity": elem.value,
                "p_id": elem.name
            },
            function(data){
                var cart_full_information = jQuery('#cart_full_information', '<div>'+data+'</div>');
                var cart_short_information = jQuery('#cart_short_information', '<div>'+data+'</div>');
                
                jQuery('#cart_short_information').fadeOut("fast", function() {
                    jQuery(this).html(cart_short_information.html());
                    jQuery(this).fadeIn("fast");
                });

                if (cart_full_information.html() == '') {
                    jQuery('#cart_full_information').fadeOut("fast");
                }
                jQuery('#cart_full_information').html(cart_full_information.html());
            });
        } else {
            alert("Nem megfelelo darabszam!");
        }
    }
}

function prevnext_product (type) {
    var akt_prod = jQuery('#lincos_cat_containers div[name="product_list"] div.visited-product');
    var next_prod = null;
    var p_id = 0;

    if (akt_prod[0]) {
        if (type == 'prev') {
            next_prod = akt_prod.prev();
        } else {
            next_prod = akt_prod.next();
        }
    } else {
        akt_prod = jQuery('div[name="product_list"] div.visited-product');
        var akt_td = akt_prod.parent();
        var next_td = null;
        if (type == 'prev') {
            next_td = akt_td.prev();
            if (next_td.html() == null) {
                next_td = akt_td.parent().prev().children(':last');
            }
        } else {
            next_td = akt_td.next();
            if (next_td.html() == null) {
                next_td = akt_td.parent().next().children(':first');
            }
        }
        next_prod = jQuery(next_td).children(':first');
    }

    if (next_prod.attr('id')) {
        p_id = next_prod.attr('id').substr(8);
        load_product_details(p_id);
    }
}

function save_settings() {
    var data = window.location.hash.substr(1).split('-');
    var sef_info = '';
    if(data[0]=='category' || data[0]=='product_list'){
        sef_info = 'cat_id='+data[1];
    }else{
        if(data[0]=='product_details'){
            sef_info = 'p_id='+data[1];
        }
    }
    document.location = 'index.php?option=com_virtuemart&lang='+jQuery('#lincos_set_language').val()+'&Itemid=2&product_currency='+jQuery('#lincos_set_currency').val()+'&lincos_country='+jQuery('#lincos_set_country').val()+'&lincos_country_3_code='+jQuery('#lincos_set_country_3_code').val()+'&cat_id='+jQuery('#tmp_akt_cat_id').val()+'&p_id='+jQuery('#tmp_akt_p_id').val();
    jQuery("#lincos_settings").dialog('close');
}

function set_language(lang){
    jQuery('#lincos_disp_language').html(jQuery('#lang_'+lang+' img').clone());
    jQuery('#lincos_set_language').val(lang);
}

function set_currency(currency){
    jQuery('#lincos_disp_currency').html(currency);
    jQuery('#lincos_set_currency').val(currency);
}

function set_default(value, c_name_from_map){
    jQuery.post('http://'+baseURL+'/index.php?option=com_content&view=article&id=29&tmpl=mymodule&moduleposition=lincos_set', {
        "set_default": true,
        "c_code": value
    },
    function(data){
        var data2 = data.split(';');
        if (data2[0] == '') {
            jQuery('#lincos_disp_country').html(c_name_from_map);
        }else{
            jQuery('#lincos_disp_country').html(data2[0]);
        }
        jQuery('#lincos_set_country').val(value);
        jQuery('#lincos_disp_language').html('<img src="/components/com_joomfish/images/flags/_'+data2[1]+'.gif" />');
        jQuery('#lincos_set_language').val(data2[1]);
        jQuery('#lincos_disp_currency').html(data2[2]);
        jQuery('#lincos_set_currency').val(data2[2]);
        jQuery('#lincos_set_country_3_code').val(data2[3]);
    });
}

function open_settings () {
    jQuery('#lincos_settings').dialog('open');
    jQuery('#lincos_settings #loader').remove();
    
    jQuery('#europe li a[name="'+jQuery('#linc_country_code').val()+'"]').parent().attr("class", "active-region focus");
}

function set_rank (cat_id, p_id) {
    var rankOptions = {
        set_rank: 1
    };

    if (cat_id) {
        rankOptions.cat_id = cat_id;
    } else {
        if (p_id) {
            rankOptions.p_id = p_id;
        }
    }

    jQuery.post('http://'+baseURL, rankOptions, function(data){});
}

function load_ask (cat_id, p_id) {
    var src = 'http://'+baseURL+'/index.php?option=com_virtuemart&manufacturer_id=1&page=shop.ask&Itemid=2&tmpl=raw&category_id='+cat_id+'&product_id='+p_id;
    jQuery('#pdetails_dialog #ask').html('<iframe src="'+src+'" style="width: 110%; height:310px; border: 0px;" ></iframe>');
}

function show_data(key) {
    if (jQuery("#"+key).is(":hidden") ) {
        jQuery("#"+key).slideDown("fast");
    } else {
        jQuery("#"+key).slideUp("fast");
    }
}
