var opened_box_id = null;
var ptype = null;

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

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

function arrayexists(arr,search){
    for (var i=0; i<arr.length; i++)
        if (arr[i] == search) return true;

    return false;
}


function LoadFilterActions(){
    FullMatchContainer = $('#shop_products_list');
    PartMatchContainer = $('#shop_products_box');
    ProdFiltersContainer = $('#product_filters');
    MostPopulars = $('#shop_populars');
    ProductsMayLike = $('#brake');

    FullMatchContainer.hide();
    PartMatchContainer.hide();
    ProdFiltersContainer.hide();
    MostPopulars.hide();
    ProductsMayLike.hide();

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

    loading_interval = setInterval(isLoaded,200);

}

function isLoaded(){
    if(filters_loaded && products_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,p['FullPrice']+' '+currency_symbol);
            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){

    switch(ptype){
        case 'terr':loadFiltersTerr(result);break;
        case 'aero':loadFiltersAero(result);break;
		case 'farm':loadFiltersFarm(result);break;
    }


}

function loadFiltersTerr(result){
    try{

        features = result['features'];
        special  = result['special'];

        for(t in features){
            filtbox = null;

            if(t == 'Communications') filtbox = $('#'+ComFilterId);
            else if(t =='Multimedia') filtbox = $('#'+MulFilterId);
            else if(t =='Safe Driving') filtbox = $('#'+SafFilterId);
            else continue;

            for(i in features[t]){
                f = features[t][i];
                listelement = document.createElement('li');
                listelement.id = 'filt_'+f['id'];
                $(listelement).html('<input type="checkbox" id="chk_'+listelement.id+'" >'+f['label']);
                filtbox.append(listelement);

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

         var count=0;
        ProductFilters = $('#product_filters');
        for(t in special){
            count++;

            fid = "gr"+count+"_filter";
            filtboxtitle = $('<a href="#" class="filter_toggle">'+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 loadFiltersAero(result){
      try{

        ProductFilters = $('#product_filters');

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

        var count=0;

        for(t in features){
            
            count++;

            fid = "gr"+count+"_filter";
            filtboxtitle = $('<a href="#" class="filter_toggle">'+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 features[t]){
                f = features[t][i];
                listelement = document.createElement('li');
                listelement.id = 'filt_'+f['id'];
                $(listelement).html('<input type="checkbox" id="chk_'+listelement.id+'" >'+f['label']);
                filtbox.append(listelement);

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

        count=0;

        for(t in special){
            count++;

            fid = "gr"+count+"_filter";
            filtboxtitle = $('<a href="#" class="filter_toggle">'+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 loadFiltersFarm(result){
     try{

        features = result['features'];
        special  = result['special'];

        for(t in features){
            filtbox = null;

            if(t == 'Communications') filtbox = $('#'+ComFilterId);
            else if(t =='Multimedia') filtbox = $('#'+MulFilterId);
            else if(t =='Safe Driving') filtbox = $('#'+SafFilterId);
            else continue;

            for(i in features[t]){
                f = features[t][i];
                listelement = document.createElement('li');
                listelement.id = 'filt_'+f['id'];
                $(listelement).html('<input type="checkbox" id="chk_'+listelement.id+'" >'+f['label']);
                filtbox.append(listelement);

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

         var count=0;
        ProductFilters = $('#product_filters');
        for(t in special){
            count++;

            fid = "gr"+count+"_filter";
            filtboxtitle = $('<a href="#" class="filter_toggle">'+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 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;

    for(p in display_full_products ){
        i = display_full_products[p];
        if(++pcount > SHOW_POPULARS)
            break;
        popular_html+='<li><div>'+pcount+'</div><a href="'+products[i]['URL']+'">'+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();
    display_partial_products = new Array();

    bestmatch = active_filters.length;


    if(active_filters.length > 0)
        for(i in products){
            //See if it matches some filter
            score = 0;
            pfeats = products[i]['AffinityFeats'];
            for(f in active_filters)
                for(pf in pfeats)
                    if(pfeats[pf] == active_filters[f])
                        score++;

            if(score == 0)
                continue;
            else if(score < bestmatch)
                display_partial_products.push(i);
            else
                display_full_products.push(i);

        }
    else
        //When no filter selected
        for(i in products){
            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);

    if(display_partial_products.length>1)
        display_partial_products.sort(sort_method);

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

    partialmatch_html = '';
    for(i in display_partial_products)
        partialmatch_html+=products_html[display_partial_products[i]];

    if(partialmatch_html!='' && display_partial_products.length>0){
        ProductsMayLike.show();
        PartMatchContainer.fadeOut('fast',function(){
          $(this).html(partialmatch_html).fadeIn();
        });
    }
    else{
        ProductsMayLike.hide();
        PartMatchContainer.fadeOut('fast');
    }
        

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

    //FullMatchContainer.html(fullmatch_html);
    //PartMatchContainer.html(partialmatch_html);

    $('#numelems_part').html('('+display_partial_products.length+')');
    $('#numelems_full').html('('+display_full_products.length+')');

}

function updateFilters(){
    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(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 showProductList(){
	try{
		$('#product_details').remove();
        $('#similair_product_list').remove();
        $('#subMenu_product_name').remove();
		$('#shop_content').show();
	}catch(e){
	}
}

function showProductDesc(){
	try{
		 $("#product_detail_longDesc").slideToggle();
         $("#product_detail_shortDesc").slideToggle();
	}catch(e){
	}
}

function loadIncludedAccData(){
    $.post('ajax/shop/products.php?retrieve=includedAccessories&ipr='+p_id+'&type='+ptype, {}, function(result){
			if(result['return']=="success"){

                var inclAccHtml = '<div class="content_box_incAcc">'
                            +'<h3 class="title"><b>'+lblIncludedAcc+' </b></h3>'
                            +'<div><ul class="incAcc_list">#content#</ul></div>'
                            +'</div>';

                 $accHtmlList='';
                 for(i in result['value']){

                         $accHtmlList +='<li class="imageGalleryThumbnail_inc" id="'+result['value'][i]['ID']+'-inc"><a ><img width="50" height="43" id="'+result['value'][i]['ID']+'" src="upload/product/'+result['value'][i]['ID']+'s.jpg" class=""></a></li>';
                 }

                inclAccHtml = inclAccHtml.replace('#content#',$accHtmlList);
				includedAccessBox = $(inclAccHtml);

                 try{
                     includedAccessBox.insertAfter($('.product_description'));
                 }catch(e){
                     desc_p = t.find('p');
                     includedAccessBox.insertAfter(desc_p);
                 }
                  LoadBalloonsForIncAcc(p_id);

			}
		}, "json");
}

function afterProductsDraw(){

	//Add click handlers
	$('div.shop_listed_product').click(function(){
                
		try{ $('#product_details').remove(); }catch(e){}
        try{ $('#similair_product_list').remove(); }catch(e){}
        try{ $('#subMenu_product_name').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);
        priceBox = t.find('div.Shop_Price');
        priceBox.addClass('Shop_Price_box');


		/*$.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");*/

        $.post('ajax/shop/products.php?retrieve=shortDescription&ipr='+p_id+'&type='+ptype, {}, function(result){
			if(result['return']=="success"){
                var prodName = $('#product_details .shop_listed_product h3 a').html();
                if(prodName){
                    subMenu = $(' <li id="subMenu_product_name"> | '+prodName+'</li>');
                    $('#shop_breadcrumb').append(subMenu);
                }

                 
				desc_p = t.find('p');
				desc_p.addClass('product_description');

				desc_p.html("<div id='product_detail_shortDesc' >"+result['value']['shortDesc']+"</div>");
            //    if(result['value']['desc']){
				desc_img = t.find('img.prod_thumb');
				desc_img.attr('src',desc_img.attr('src').replace(p_id+'_shop.jpg',result['image']));
                var urlProduct=result['url'];
                readMoreLink = $('<a id="product_description_read_more" href="'+urlProduct+'"><br/>'+lblReadMore+'</a>');
                //readMoreLink.click(showProductDesc);
                $('#product_detail_shortDesc').append(readMoreLink);
                loadIncludedAccData();
               // longDesc = $("<div id='product_detail_longDesc' >"+result['value']['desc']+"</div>");
               // longDesc.hide();
               // desc_p.append(longDesc);
              //  }


                
			}
		}, "json");

         

        $.post('ajax/shop/products.php?retrieve=similairProducts&ipr='+p_id+'&type='+ptype, {}, function(result){
			if(result['return']=="success"){

                var inclAccHtml = '<div class="content_box_incAcc" id="similair_product_list">'
                             +'<h3 class="title"><b>'+mayLike+' (#count#) </b></h3>'
                            +'<div><ul class="incAcc_list">#content#</ul></div>'
                            +'</div>';

                 $accHtmlList='';
                 var countProd= 0;
                 for(i in result['value']){

                        $accHtmlList +='<li class="imageGalleryThumbnail_sim" id="'+result['value'][i]['ID']+'-sim"><a ><img width="50" height="43" id="'+result['value'][i]['ID']+'" src="upload/product/'+result['value'][i]['ID']+'s.jpg" class=""></a></li>';
                        countProd++;
                    
                    }

                inclAccHtml = inclAccHtml.replace('#count#',countProd);
                inclAccHtml = inclAccHtml.replace('#content#',$accHtmlList);
				includedAccessBox = $(inclAccHtml);

                 try{
                     includedAccessBox.insertAfter($('#product_details'));
                 }catch(e){
                     desc_p = t.find('p');
                     includedAccessBox.insertAfter(desc_p);
                 }

                 LoadBalloonsForSimilarProduct(p_id);
			}
		}, "json");


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

	});
if(prodNavId!=""){
		$("#product_"+prodNavId+" div:first").trigger('click');
		prodNavId="";
		}

}



