var global_product_id = null;
var panels = null;

$(document).ready(function(){
	
	//check hash

	if (window.location.hash != undefined && window.location.hash != null)
	{
		var hash = window.location.hash.substr(1);

		if (hash > 1)
			{
		        var data = {};
		        data.page = parseInt(hash);
		        data.slug = $('#slug').val();
		        data.identifier1 = $('#id1').val();
		        data.node_id1 = $('#node1').val();
		        data.identifier2 = $('#id2').val();
		        data.node_id2 = $('#node2').val();
		        data.brands = getCurrBrands();
		        data.filters = getCurrFilters();

		        modal_busy(true);

		        $.get(
		            '/parts/changePage/',
		            data,
		            function(response){
		                response = $.parseJSON(response)
		                $('#product_pane').html(response.productlist);
		                fitWindow();
		                $('.page_btn_container').each(function(i, index){
		                	$(this).html(response.pageList);
		                	if (response.pageList != false){
		                		$('.product_pre_options').show();
		                	}
		                });
		                modal_busy(false);		                
		                
		                
		            });
			}
		
	}

    //init the number of panels
    panels = Math.floor($('#product_pane').width()/385);
    if(panels < 3) {
        panels = 3;
    }

    $.ajaxSetup({
        cache: false,
        error: function(XMLresponse, textStatus, error){
            if(textStatus == 'error'){
        //set_message('Error: Could not communicate with the server.  Try reloading the page (F5).');
        }
        }
    });

    $('#fitment_dialog').dialog(
    {
        title: 'Please select your car to continue',
        autoOpen: false,
        width: 600,
        modal: true,
        buttons: {
            'Add to cart': function(){
            	var flag = true;
            	$('.option_select').each(function(i, index){
            		if ($(this).val() == 0)
            			{
            			flag = false;
            			}                    		
            	});
                if(($('#add-to-cart-complete').length != 0) && (flag == true)) {
                    saveCart();
                }
            }
        },
        open: function(event){

        },
        close: function(event){
            $('#fitment_dialog').empty();
            $('#fitment_dialog').dialog({
                buttons: {
                    'Add to cart': function(){
                    	var flag = true;
                    	$('.option_select').each(function(i, index){
                    		if ($(this).val() == 0)
                    			{
                    			flag = false;
                    			}                    		
                    	});
                        if(($('#add-to-cart-complete').length != 0) && (flag == true)) {
                            saveCart();
                            $('#fitment_dialog').dialog('close');
                        }
                    }
                },
                title: 'Please select your car to continue'
            })

        }

    });

    $('.pagination-buttons a').live('click', function(event){

        event.preventDefault();
        var data = {};
        //data.page = $(this).attr('href').charAt($(this).attr('href').length-1);
      //build page hack
        var pstring = $(this).attr('href');
        var page = '';
        
        var i = 1;
        while (is_int(pstring.charAt(pstring.length-i)) == true)
        {
        	page = pstring.charAt(pstring.length-i) + '' + page;
        	++i;
        }
        
        data.page = page;
        
        if (!is_int(data.page))
        {
        	data.page = $(this).attr('href').substr(-1);
        }
        if (!is_int(data.page))
        {
        	alert('An error has occured. Please refresh the page and try again.');
        	data.page = 1;
        }
        data.slug = $('#slug').val();
        data.identifier1 = $('#id1').val();
        data.node_id1 = $('#node1').val();
        data.identifier2 = $('#id2').val();
        data.node_id2 = $('#node2').val();
        data.brands = getCurrBrands();
        data.filters = getCurrFilters();

        modal_busy(true);

        $.get(
            '/parts/changePage/',
            data,
            function(response){
                response = $.parseJSON(response)
                $('#product_pane').html(response.productlist);
                fitWindow();
                modal_busy(false);
                $('.page_btn_container').each(function(i, index){
                	$(this).html(response.pageList);
                	if (response.pageList != false){
                		$('.product_pre_options').show();
                	}
                });
                window.location.hash = data.page;
            });
    });

    $('.filter_link').live('click', function(event) {

        event.preventDefault();
        setPage($(this).parent());

    });

    $("input[name='fitments']").live('change', optionSelected);

    $('#price_crumbs a').live('click', function(event) {
        event.preventDefault();

        $(this).parent().remove();
        setPage();
    });
    
    //brand cbrumbs
    $('.brand_crumb a').live('click', function(e){
    	e.preventDefault();
    	var brand = $(this).prev('h1').html();
    	var brand_id = null;
    	var goto_url = $(this).attr('href');

    	$("#brand_filters ul").children('li').each(function(i, index){
    		//console.log($.trim($(this).find('a').html()));
    		if ($.trim($(this).find('a').html()) == brand)
    		{
    			//get id
    			brand_id = $(this).find('input[type="checkbox"]').val();
    		}
    	});
    	$.post('/parts/clearBrand/', {'brand_id':brand_id}, function(){
    		window.location = goto_url;
    	}); 
    });

    $('#brand_filters a').live('click', function(e){
    	if ($(this).parent('li').hasClass('see_more') || $(this).parent('li').hasClass('see_less'))
    	{
    		return true;
    	}
        if($('#brand_filters input:checked').length != 0) {
            e.preventDefault();
            box = $(this).parent().parent().find('input[name=brands]');

            //uncheck the box and remove the brand filter if its checked
            if(box.is(':checked')) {
            	$(this).removeClass('filter_selected');
            	
                box.attr('checked', false);
                //check if its the last one to be removed
                if($('#brand_filters input:checked').length == 0) {
                	$.post('/parts/clearBrand/', {'brand_id':box.val()}, function(){
                		window.location = $('.brand_crumb a').attr('href');
                	});                    
                }else{	
	                //if the user unchecked the 'url'ed brand
	                var first_remaining_brand = $('#brand_filters input:checked:first').parent().find('a').attr('href');
	                if(box.parent().find('#current_brand').length != 0 && typeof first_remaining_brand !== 'undefined') {
	                    window.location = first_remaining_brand;
	                } else {
	                    setPage();
	                }
                }
            }
            //check the box and add it to the filters if its unchecked
            else {
                box.attr('checked', true);
                $(this).addClass('filter_selected');
                setPage();
            }
        }
    })

    $('.brand_crumb a').live('click', function(e) {
        brand_id = $(this).parent().find('.brand_id').val();
        checkbox = $('#brand'+brand_id);
       
        //uncheck the box and remove the brand filter if its checked
        if(checkbox.is(':checked')) {
            checkbox.attr('checked', false);
            //check if its the last one to be removed
            if($('#brand_filters input:checked').length != 0) {
                e.preventDefault();
            }

            //if the user unchecked the 'url'ed brand
            if(checkbox.parent().find('#current_brand').length != 0) {
            	 var getGoto = $('#brand_filters input:checked:first').parent().find('a').attr('href');
            	 if (getGoto != undefined)
            	 {
            		window.location = getGoto;
            	 }
                //window.location = $('#brand_filters input:checked:first').parent().find('a').attr('href');
            	//alert('kk');
            	//console.log(getGoto);
            } else {
                setPage();
            }
        }
        //check the box and add it to the filters if its unchecked
        else {
            e.preventDefault();
            box.attr('checked', true);
            setPage();
        }
    })

    $('#brand_filters input:checkbox').live('change', function(e){

        box = $(this);

        if(box.is(':checked')) {
            setPage();
            //if this is the first one to be checked, send it to the proper page
            box.parent().children('label').children('a').addClass('filter_selected');
            if($('#brand_filters input:checked').length == 1) {
                window.location = box.parent().find('a').attr('href');
            }
        }
        else {
        	box.parent().children('label').children('a').removeClass('filter_selected');
            //check if its the last one to be removed
            if($('#brand_filters input:checked').length == 0) {
            	//send a clear brand
            	$.post('/parts/clearBrand/', {}, function(){
            		window.location = $('.brand_crumb a').attr('href');
            	});
                
            }
            //if the user unchecked the 'url'ed brand
            else if(box.parent().find('#current_brand').length != 0) {
                window.location = $('#brand_filters input:checked:first').parent().find('a').attr('href');
            } else {
                setPage();
            }
        }
        
    })

    $('.add-to-cart').live('click', function(e) {
        e.preventDefault();
        product_id = $(this).parent().parent().find('.product_id').val();
        loadCartDialog(product_id);
    });
    
    
    
    $('.product_sort_by').live('change', function(e) {
    	data = {};
    	data.sort_by = $(this).val();
    	
    	$.post('/parts/sortBy/', data, function(data){
    		setPage();
    	});
    	
    });
    
    

    $(window).resize(function() {
        fitWindow();
    });

    fitWindow();
});


function optionSelected()
{
	data = {};
	data.fitment_id = $("input[name='fitments']:checked").val();
	data.product_id = $("input[name='fitments']:checked").parent().find('#fit_prod_id').val();
	data.ajaxAction = 'updateOptions';
	dialog = $('#fitment_dialog');
	
	if ($('select.option_select').length > 0){

		var valid = true;
		$('select.option_select').each(function(i, index){
			if ($(this).val() == 0)
			{
				alert('Please make sure all options are selected');
				valid = false;
				return false;
			}
		});
		if (valid == false)
		{
			return false;
		}	
		
		
		data.options = new Array();
		data.options.push($(this).val());

		$(this).parent('li').prevAll('li').each(function(i, index){
			if ($(this).children('select').val() > 0)
			{
				data.options.push($(this).children('select').val());
			}
			//console.log($(this).children('select').val());
		});

		$(this).parent('li').nextAll('li').each(function(i, index){
			$(this).remove();
		});

		 //= $('select.option_select:last').val();
		//data.last_option = $('select.option_select:last').attr('id');
	}else{
		$("input[name='fitments']").not("input[name='fitments']:checked").parent().hide();		
	}

	
     $.get(get_base_url()+'cart/ajax/',
         data,
         function(response) {
    	 	
    	 	
    	 	
    	 	$('select.option_select').unbind('change');
    	 	
             if($('#product_options_list').length == 0) {            	 
                 $('#fitment_dialog').append(response.content);                 
             } else {            	 
                 $('#product_options_list ul').append(response.content);                 
             }
             
             $('select.option_select').change(optionSelected);
             
             if ($('#fitment_dialog select').length == 0)
     	 	 {
     	 		saveCart();                
     	 	 }
             
             if (!response.complete)
	     	 {
	     	 		dialog.dialog('open');
	     	 }
             
             $('#fitment_dialog').dialog('option', 'title', 'Select your Options:');
             $('#fitment_dialog').dialog('option', 'position', 'center');
             
         }
         ,'json');
}

function setPage(add_filter) {
    var data = {};
    var brands = [];

    filters = getCurrFilters();
    if(add_filter != undefined && add_filter.length) {   	
        filters = appendFilter(filters, add_filter);
    }
    brands = getCurrBrands();

    data.page = 1;
    data.slug = $('#slug').val();
    data.identifier1 = $('#id1').val();
    data.node_id1 = $('#node1').val();
    data.identifier2 = $('#id2').val();
    data.node_id2 = $('#node2').val();
    data.identifier3 = $('#id3').val();
    data.node_id3 = $('#node3').val();
    data.filters = filters;
    data.brands = brands;

    modal_busy(true);
    setTimeout(function(){
    $.get('/parts/setPage/',
        data,
        function(response) {

            $('#filter_crumbs').html(response.filter_crumbs);
            $('#product_pane').html(response.productlist);
            $('#filterPane').replaceWith(response.filters);
            $('.page_btn_container').each(function(i, index){
            	$(this).html(response.pageList);
            	if (response.pageList != false){
            		$('.product_pre_options').show();
            	}
            });
            fitWindow();
            modal_busy(false);
            if (data.page != 1)
            {
            	window.location.hash = data.page;
            }
        }, 'json');
    }, 100);
}

function getCurrBrands() {
    brandObj = [];
    $('#brand_filters input:checked').each(function(){
        brandObj[brandObj.length] = $(this).val();
    })
    return brandObj;
}

//function setPage() {
//    var data = {};
//
//    filters = getCurrFilters();
//    filters = appendFilter(filters, $(this).parent());
//    data.page = 1;
//    data.slug = $('#slug').val();
//    data.identifier1 = $('#id1').val();
//    data.node_id1 = $('#node1').val();
//    data.identifier2 = $('#id2').val();
//    data.node_id2 = $('#node2').val();
//    data.filters = filters;
//
//    $.get('/parts/setPage',
//        data,
//        function(response) {
//            response = $.parseJSON(response);
//            $('#filter_crumbs').html(response.filter_crumbs)
//            $('#product_pane').html(response.productlist);
//            $('#filterPane').replaceWith(response.filters);
//            fitWindow();
//        })
//}

function getCurrFilters() {
    filterObj = [];

    $('#filter_crumbs ul li').each(function() {
        filter_type = $(this).children('.filter-type').val();
        filter_id = $(this).children('.filter-id').val();
        filter_end = $(this).children('.filter-end').val();

        filterObj[filterObj.length] = {
            filter_data: {
                id: filter_id,
                end: filter_end
            },
            type: filter_type
        };
    })
    return filterObj;
}

function appendFilter(filterObj, newFilter) {
    filter_type = newFilter.children('.filter-type').val();
    filter_id = newFilter.children('.filter-id').val();
    filter_end = newFilter.children('.filter-end').val();
    //will remove a price filter if one already exists
    if (filter_type == 'price')
    {
	    var i = 0;
	    for (i = 0; i < filterObj.length; ++i)
	    {
	    	if (filterObj[i]['type'] == 'price')
	    	{
	    		filterObj[i] = {
	    		        filter_data: {
	    		            id: filter_id,
	    		            end: filter_end
	    		        },
	    		        type: filter_type
	    		};
	    		
	    		return filterObj;
	    	}
	    }
    }
    filterObj[filterObj.length] = {
        filter_data: {
            id: filter_id,
            end: filter_end
        },
        type: filter_type
    };

    return filterObj;
}

function fitWindow() {
	//alert($(".product_pre_options").width());
    //var min_width = parseInt($('.product_cell').css('min-width'));
	
    var number = parseInt($(".product_pre_options").parent().width()/260);
    $(".product_pre_options").width((number*260)-5);
   
    //alert($(".product_pre_options").width());
    /*
    var max_width = 385;
    var margin = parseInt($('.product_cell').css('margin-left'));
    var padding = parseInt($('.product_cell').css('padding-left'));
    var parent_width = $('#product_pane').width();

    //this handles the variability of floating point numbers as widths; widths
    //dont count fractions, changed to suit the number of panels you want on each
    //row
    var magic_constant = panels*2;

    if(parent_width <= (min_width*panels + (margin*panels*2) + (padding*panels*2)) + magic_constant) {
        panels--;
    }
    else if (parent_width >= (max_width*panels + (margin*panels*2) + (padding*panels*2)) + magic_constant){
        panels++;
    }

    width = (parent_width - (margin*panels*2) - (padding*panels*2))/panels - magic_constant;
    $('.product_cell').width(width);*/
}

function loadCartDialog(product_id) {
    /*data = {}
    global_product_id = product_id;
    data.product_id = global_product_id;
    data.ajaxAction = 'getFitmentsOptions';
    dialog = $('#fitment_dialog');
    dialog.dialog('open');
    dialog.html("<img class='loadingDialog' src='/global/images/ajax-loader.gif' alt='Loading...'/>");
    
    $.get(get_base_url()+'cart/ajax',
        data,
        function(response) {
           

            if(response.show) {
                
            	if ($('.loadingDialog').length == 0)
            	{
            		dialog.append(response.content);
            	}else{
            		dialog.html(response.content);
            	}
            	
                
                //dialog.dialog('open');
            }
            else {
            	if ($('.loadingDialog').length == 0)
            	{
            		dialog.append(response.content);
            	}else{
            		dialog.html(response.content);
            	}
                dialog.dialog({
                    buttons: {
                        'Close' : function(){
                            dialog.dialog('close');
                        }
                    },
                    title: 'Please select a car'
                });
                //dialog.dialog('open');
            }
            
            dialog.dialog('option', 'width', 'auto');
            dialog.dialog('option', 'position', 'center');
        }, 'json');*/
    data = {};
    global_product_id = product_id;
    data.product_id = global_product_id;
    data.ajaxAction = 'getFitmentsOptions';
    dialog = $('#fitment_dialog');
    
    dialog.html("<img class='loadingDialog' src='/global/images/ajax-loader.gif' alt='Loading...'/>");
    
    $.get(get_base_url()+'cart/ajax/',
            data,
            function(response) {
               

                if(response.show) {
	                	if ($('.loadingDialog').length == 0)
	                	{
	                		dialog.append(response.content);
	                	}else{
	                		dialog.html(response.content);
	                	}
	                	
	                	if (response.skip != undefined)
	                	{
	                		optionSelected();
	                	}else{
	                		dialog.dialog('open');
	                	}
                	
                	
                    //dialog.dialog('open');
                }
                else {
                	dialog.dialog('open');
	                	if ($('.loadingDialog').length == 0)
	                	{
	                		dialog.append(response.content);
	                	}else{
	                		dialog.html(response.content);
	                	}
	                    dialog.dialog({
	                        buttons: {
	                            'Close' : function(){
	                                dialog.dialog('close');
	                            }
	                        },
	                        title: 'Please select a car'
	                    });
	                //}
                    //dialog.dialog('open');
                }
                
                dialog.dialog('option', 'width', 'auto');
                dialog.dialog('option', 'position', 'center');
            }, 'json');
}

function saveCart() {
    data = {};
    data = getProductData();
    data.ajaxAction = 'addCart';

    $.post(get_base_url()+'cart/ajax/',
        data,
        function(response) {
    	window.location = "/cart/view";
            /*$('#layout-cart').replaceWith(response.content);
            $('#fitment_dialog').html(response.message);
            dialog.dialog({
                buttons: {
                    'Close' : function(){
                        //dialog.dialog('close');
                    	window.location = "/cart/view";
                    }
                },
                title: response.title
            });*/

        }, 'json');
}

function getProductData() {
    data = {};
    data.product_id = $("input[name='fitments']:checked").parent().find('#fit_prod_id').val();
    data.fitment_id = $("input[name='fitments']:checked").val();

    if(data.fitment_id == undefined) {
        data.fitment_id = $('#options_fitment').val();
    }

    options = '';

    $('#product_options_list select').each(function(){
        options += $(this).val() + ',';
    })
    options = options.slice(0, options.length - 1);

    data.option_ids = options;

    return data;
}

function show_message(message) {
    $('#fitment_dialog').html(message);
}

function seeMore(div_id)
{
	if ($('#' + div_id + ' ul li.toggled').length > 0)
	{
		$('#' + div_id + ' ul li.toggled').each(function(i, index){
			$(this).hide();
			$(this).removeClass('toggled');
		});
		$('#' + div_id + ' ul li.see_less').addClass('see_more').removeClass('see_less').children('a').html('See More');
	}else{
		$('#' + div_id + ' ul li').each(function(i, index){
			if (!$(this).is(':visible'))
			{
				$(this).show();
				$(this).addClass('toggled');
			}
		});	
		$('#' + div_id + ' ul li.see_more').addClass('see_less').removeClass('see_more').children('a').html('See Less');
	}
}

function is_int(value){
	  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
	      return true;
	  } else {
	      return false;
	  }
	}
