var opened_box_id = null;
var ptype = null;
var pclass = null;

var c_id = -1;
var c_products = null;
var c_accessories = null;

var currency_symbol= '&euro;';
if(shop_currency)
    currency_symbol = shop_currency;

try{
    if(products_type)
        ptype=products_type;
}catch(e){
    pype='terr';
}

try{
	if(products_class)
		pclass=proucts_class;
}catch(e){
	pclass = 'acc';
}

function arrayexists(arr,search){
    for ( z in arr)
        if (arr[z] == search) return true;

    return false;
}

function LoadFilterActions(){
    FullMatchContainer = $('#shop_products_list');

    ProdFiltersContainer = $('#product_filters');
    MostPopulars = $('#shop_populars');
    ProductsMayLike = $('#brake');

    FullMatchContainer.hide();

    ProdFiltersContainer.hide();
    MostPopulars.hide();

    $.post('ajax/shop/products.php?retrieve=products&type='+ptype+'&class='+pclass, {}, loadProducts, "json");
    $.post('ajax/shop/products.php?retrieve=filters&type='+ptype+'&class='+pclass, {}, loadFilters, "json");
	$.post('ajax/shop/products.php?retrieve=navigatorslist&type='+ptype, {}, loadNavigatorsList, "json");

    loading_interval = setInterval(isLoaded,200);

	$('#toggle_view').toggle(
	function(){
		$('#shop_products_list').removeClass('grid_view');
		$('#shop_products_list').addClass('list_view');
		$('#toggle_view').removeClass('grid');
		$('#toggle_view').addClass('list');
	},
	function(){
		$('#shop_products_list').removeClass('list_view');
		$('#shop_products_list').addClass('grid_view');
		$('#toggle_view').removeClass('list');
		$('#toggle_view').addClass('grid');
	});


}

function isLoaded(){
    if(filters_loaded && products_loaded && list_loaded){
        clearInterval(loading_interval);
        afterLoad();
    }
}

function loadProducts(result){
     
    try{

        for(i in result)
            products[ result[i]['ProductId'] ] = result[i];

        htmltext='';

        for(i in products){

            p = products[i];

            htmltext = product_template;

            htmltext = htmltext.replace(/#p_id#/g,p['ProductId']);
            htmltext = htmltext.replace(/#p_name#/g,p['Name']);
            htmltext = htmltext.replace(/#p_url#/g,p['URL']);
            htmltext = htmltext.replace(/#p_img#/g,p['Image']);
            htmltext = htmltext.replace(/#p_alt#/g,p['Alt']);
            htmltext = htmltext.replace(/#p_price#/g,currency_symbol+' '+p['FullPrice']);
            htmltext = htmltext.replace(/#p_desc#/g,p['Description']);
            htmltext = htmltext.replace(/#p_carturl#/g,p['CardURL']);
			htmltext = htmltext.replace(/#promoBadgeSmall#/g,(p['discPrice']!=''?'<div id="promoBadgeSmall"></div>':'' )  );
			
            //Store html in array
            products_html[products[i]['ProductId']] = htmltext;
        }


        pcount = 0;
        
        for(p in products)
            display_full_products[pcount++] = p;
        
        //Webkit bug
        display_full_products.sort(sort_popularity_desc);
   
        products_loaded = true;
    }catch(e){
        alert(e);
    }

}

function loadFilters(result){
      try{

        ProductFilters = $('#product_filters');

        features = result['features']; //..empty
        special  = result['special'];

        var count=0;

        for(t in special){
            count++;

            fid = "gr"+count+"_filter";
            filtboxtitle = $('<a class="filter_title">'+t+'</a>');
            filtboxlist  = $('<ul id="'+fid+'" class="filters_box"></ul>');
            filtbox = $('<li></li>');

            filtbox.append(filtboxtitle);
            filtbox.append(filtboxlist);
            ProductFilters.append(filtbox);
            
            for(i in special[t]){
                
                f = special[t][i];

                listelement = document.createElement('li');
                listelement.id = 'filt_'+f['id'];
                $(listelement).html('<input type="checkbox" id="chk_'+listelement.id+'" >'+f['label']);

                $('#'+fid).append(listelement);

                filters[f['id']] = f;
            }
        }

        fcount = 0;
        for(f in filters)
            display_filters[fcount++] = f;

        filters_loaded = true;

    }catch(e){
        alert(e);
    }
}

function loadNavigatorsList(result){

	try{

		ProductFilters = $('#product_filters');

		fid = "prodsel_filter";
		filtbox = $('<li></li>');

		filtboxtitle = $('<a class="filter_title">'+lblCompatibility+'</a>');

        prodselection = $('<ul class="filters_box" ><li><select id="'+fid+'"><option value="-1">'+lblAllProducts+'</option></select></li></ul>');

		filtbox.append(filtboxtitle);
		filtbox.append(prodselection);

		ProductFilters.prepend(filtbox);

		prodlist = $('#'+fid);

		c_products = new Array();

		for(i in result){
			p = result[i];
			prod = $('<option value="'+p['Id']+'">'+p['Name']+'</option>');
			prodlist.append(prod);
			c_products[p['Id']] = p;
		}

		//onChange listener
		prodlist.change(selectCompatibility);

		list_loaded = true;
		
	}catch(e){
		alert(e);
	}

}

function afterLoad(){

    //Assign to products also the "special features"
    //Scan all filters, find those whose id starts with 's' and have 'Products' defined
    for(i in filters){
        try{
            f = filters[i];
            if(f['id'].charAt(0)=='s' && f['Products'].length > 0){
                for(p in f['Products']){
                    pid =f['Products'][p];
                    try{
                        pfeatures = products[pid]['AffinityFeats'];
                        products[pid]['AffinityFeats'][pfeatures.length] = f['id'];
                    }catch(e){}
                }
            }

        }catch(e){
        //Do nothing
        }
    }

    //Define Actions For filters
    $('input[id^="chk_filt_"]').click(function(){

        id = this.id.replace('chk_filt_','');
        listitem = $('#filt_'+id);

        active = $(this).attr('checked');

        if(active){
            //Add it to active filters list
            active_filters[active_filters.length] = id;
        }else{
            //Remove from active filters
            tmp_filters = new Array();
            for(i in active_filters){
                if(active_filters[i]!=id)
                    tmp_filters[tmp_filters.length++] = active_filters[i];
            }

            active_filters = tmp_filters;
        }

        filterProducts();

        updateProducts();
        updateFilters();
    });

    //Define toggle actions  :  jQuery(this).next().slideToggle('normal');
    $('a[class="filter_toggle"]').click(function(){

        //Check if contains active filters
        if($(this).next().css('display')=='none'){
            $(this).removeClass('linkclosed');
            $(this).addClass('linkopened');
        }else{
            $(this).removeClass('linkopened');
            $(this).addClass('linkclosed');
        }

       $(this).next().slideToggle('normal');
    });
	
    $('a[class="filter_toggle"]').each(function(){
        $(this).addClass('linkopened');
    });

    //Fill the "most popular" container
    var popular_html = '';
    var pcount = 0;

    var accPrefixLink = (products_type=='aero'?'0508':(products_type=='farm'?'0515':'0504'));
    var navPrefixLink = (products_type=='aero'?'0507':(products_type=='farm'?'0516':'0506'));

    for(p in display_full_products ){
        i = display_full_products[p];
        if(++pcount > SHOW_POPULARS)
            break;
		
		var link = ''

		if(products[i]['ProductCode'].toLowerCase().indexOf('nav') == 0)
			link = 'href="index.php?swt='+navPrefixLink+'&ipr='+products[i]['ProductId']+'"';
        else if(products[i]['ProductCode'].toLowerCase().indexOf('acc') == 0)
            link = 'href="index.php?swt='+accPrefixLink+'&com=-1&acc='+products[i]['ProductId']+'"';

        popular_html+='<li><div>'+pcount+'</div><a '+link+' >'+products[i]['Name']+'</a></li>';
    }
    
    MostPopulars.html(popular_html).slideDown('fast');

    updateProducts();
    updateFilters();

}

function filterProducts(){
    //Filter products according to active_filters

    display_full_products = new Array();
   
    if(active_filters.length > 0 )
        for(i in products){

			//Required compatibility with nav id
			if( c_id > 0 && !arrayexists(c_accessories,i))
				continue;
			
            //See if it matches some filter
            score = 0;
            
			try{
				pfeats = products[i]['AffinityFeats'];
			}catch(e){
				alert(i);
				alert(products[i]);
			}

            for(f in active_filters)
                for(pf in pfeats)
                    if(pfeats[pf] == active_filters[f])
                        score++;

            if(score != 0)
                display_full_products.push(i);

        }
    else
        //When no filter selected
        for(i in products){

			//Required compatibility with nav id
			if( c_id > 0 && !arrayexists(c_accessories,i))
				continue;

            display_full_products.push(i);
        }

}

function doSort(select){

    chosen_method = '';
    try{
        chosen_method = $(select).val();
        
        switch(chosen_method){
            case 'sort_popularity_desc': sort_method = sort_popularity_desc;break;
            case 'sort_name_asc': sort_method = sort_name_asc;break;
            case 'sort_name_desc': sort_method = sort_name_desc;break;
            case 'sort_price_asc': sort_method = sort_price_asc;break;
            case 'sort_price_desc': sort_method = sort_price_desc;break;
                default:  sort_method = sort_popularity_desc;
        };

        if( display_full_products.length>1 || display_partial_products.length>1 )
            updateProducts();
        
    }catch(e){
        //do nothing
    }

}

function updateProducts(){

    //Sort data
    if(display_full_products.length>1)
        display_full_products.sort(sort_method);

    fullmatch_html = '';
    for(i in display_full_products)
        fullmatch_html+=products_html[display_full_products[i]];

    if(fullmatch_html!=''){
        FullMatchContainer.fadeOut('fast',function(){
          $(this).html(fullmatch_html);

		  	//Add alpha and omega class
			var p_count = 0;
			cols = 3;
			
			for(i in display_full_products){
				p = display_full_products[i];
				prod =$('#product_'+p);

				if(p_count%cols == 0)
					prod.addClass('alpha');
				else if(p_count%cols == cols-1 )
					prod.addClass('omega');

				if(p_count < cols)
					prod.addClass('firstRow');
			
				p_count++;
			}

		 $(this).fadeIn(afterProductsDraw);
        });

	}else{
        FullMatchContainer.fadeOut('fast');
    }
    
    $('#numelems_full').html('('+display_full_products.length+')');

}

function updateFilters(){

	showProductList();

    ProdFiltersContainer.show();
    dialogtext = '';
    br = '<br>';
    
    //find the ones to disable
    disable_list = new Array();

    for(i in display_full_products)
        dialogtext +=display_full_products[i]+"&nbsp;";

    dialogtext+=br;

    //Fake search of current full matching
    for(f in filters){
        //Skip already active filters
        if( arrayexists(active_filters,f) )
            continue;

        found = false;
        dialogtext+='<b>Analyze <span style="color:red;">'+f+' - '+filters[f]['label']+'</span></b><br>';
        //Search into the full matching products if any matches also this filter
        for(i in display_full_products){

            p = products[ display_full_products[i]];

            pfeats = p['AffinityFeats'];

			//If compatibility porduct enabled filter according to that
			if( c_id > 0 && !arrayexists(c_accessories,display_full_products[i])){
				found = false;
				break;
			}

            if(pfeats && arrayexists(pfeats,f)){
                found = true;
                break;
            }
        }

        if(found)
            dialogtext+='=> found in products<br>';

        if(!found)
            disable_list[disable_list.length]=f;

    }

   /*
    dialog = $('<div id="dialogbox" style="position:absolute;top:0px;left:100px;background-color:black;color:green;width:500px;height:300px;overflow:auto;z-index:15;"></div>').html(dialogtext);
    $('body').append(dialog);
    dialog.click(function(){ $(this).remove(); } )
    */

    for(f in filters){
        if( arrayexists(disable_list,f))
            $('#filt_'+f).slideUp();
        else
            $('#filt_'+f).slideDown();

    }

}


function selectCompatibility(){
	c_id = $(this).val();
	
	c_accessories = (c_id > 0)?c_products[c_id]['Accessories']:null;

	$('input[id^="chk_filt_"]').each(function(){
		$(this).attr('checked',false);
	});

	active_filters = new Array();

	filterProducts();

	updateFilters();
	updateProducts();

	
}

function showProductList(){
	try{
		$('#product_details').remove();
		$('#shop_content').show();
	}catch(e){
	}
}

function afterProductsDraw(){

	//Add click handlers
	$('div.shop_listed_product').click(function(){

		try{ $('#product_details').remove(); }catch(e){}

		t = $(this).parent().clone();
		p_id = t.attr('id');
		p_id = p_id.replace('product_','');

		t.attr('id',"product_details");
		
		closeBtn = $('<a id="closeProductDetailsBtn">'+lblBack+'</a>');
		closeBtn.click(showProductList);
		t.prepend(closeBtn);

		


		$.post('ajax/shop/products.php?retrieve=description&ipr='+p_id+'&type='+ptype, {}, function(result){
			if(result['return']=="success"){
				desc_p = t.find('p');
				desc_p.addClass('product_description');
				desc_p.html(result['value']);
				
				desc_img = t.find('img.prod_thumb');
				desc_img.attr('src',desc_img.attr('src').replace(p_id+'_shop.jpg',result['image']));
			}
			
		}, "json");
		

		$('#shop_content').hide();
		$("#shop_container").prepend(t);

	});
if(isSelectedProduct!=""){
		$("#prodsel_filter").val(isSelectedProduct);
		$("#prodsel_filter").trigger('change');
		$("#product_"+accId+" div:first").trigger('click');
		isSelectedProduct="";
		}

}
