var timeOutId = 0;
var fullBranchSelected = false;
var expiry = new Date();

$(document).ready(function(){

    if(!getCookie('cmp') && $('#product-listing-fitment-selector').length != 0) {
        $('#fitment_box').hide();
    }
    else {
        $('#product-listing-fitment-selector').hide();
    }


    //On fitment selection change
    $('body').delegate('.fitment_select', 'change', function() {
        //clear the timer and reset booleans since the user has changed her choices
        clearTimeout(timeOutId);
        fullBranchSelected = false;
        
        var element = $(this);
        var nextEle = element.next('select');
        //add loading
        if (nextEle.length > 0)
        {
        	//if (nextEle.val() == '-1')
        	//{
        		nextEle.html("<option value='-1'>Loading ...</option>");
        	//}
        }
        
        //check to see if select text is there and wasnt selected
        if ($(this).val() > 0)
        {
        	//remove the first 'select fitment' option so they cant go back to it.
        	$(this).find("option[value='-1']").remove();
        	
        }

        var data = {};
        //get the type from the end of the id of the selector box
        type = element.attr('class').split('_');
        data.type = type[4];
        
        if (data.type == 'year' && $('#fitment_year_model').length > 0)
        {
        	if ($('.sub_select_fitment_model').val() <= 0)
        	{
        		return true;
        	}	        	
        }
        
        if (data.type == 'year' && element.parents('#layout-left-sidebar').length == 0)
        {
        	//just check the others havnt been filled in
        	if (element.nextAll('select').nextAll('select').val() > 0)
        	{
        		//need to set this uuup
        		element = element.nextAll('select').nextAll('select');
        		type = element.attr('class').split('_');
                data.type = type[4];
        	}else if(element.prevAll('select').prevAll('select').val() > 0)
        	{
        		element = element.prevAll('select');
        		type = element.attr('class').split('_');
                data.type = type[4];
        	}
        }
        data.id = element.val();
        //try to get the ident for more precise car info
        var urlinfo = location.pathname.match(/\/parts\/(.*)\/(.*)/);
        if (urlinfo != null)
        {
        	data.ident = urlinfo[urlinfo.length-1];
        	//ident is last one
        }else{
        	data.ident = null;
        }
        


        //every make/model/submodel needs to find only children with a range that
        //fit in the selected year
        data.year = element.parents('.fitment_selects').find('select.sub_select_fitment_year').val();

        if ($('#product_id').length > 0 && $('#product_id').val() > 0 && (!$('#no-vehicle-dialog').is(':visible')))
        {
        	// on product details page
        	
        	data.product_ids = new Array($('#product_id').val());
        }
        
        buildFitmentComplete();

        //rebuild the selector list into a buffer and replace the current view when
        //the user selects a box below the currently built ones
        if ($('#product_id').length > 0 && $('#product_id').val() > 0)
        {
        	//check after 
        	element.nextAll('select').each(function(i, index){
        		
        		if (!$(this).hasClass('sub_select_fitment_make') && !$(this).hasClass('sub_select_fitment_model') && !$(this).hasClass('sub_select_fitment_year'))
        		{
        		$(this).remove();
//        			if ($(this).val() < 0)
//        			{
//        			//delete this and all next
//        				$(this).nextAll('select').each(function(i, index){$(this).remove();});
//        				$(this).remove();
//        			}
        		}
        	});

        }else{
        	if(element.prevAll('select').prevAll('select').val() > 0)
        	{
        		
        	}else{
        		//element.parents('.fitment_selects').replaceWith(selectorReset(element));
        	}
        }

        //set all fitment selectors of this type to the same value
        val = element.find('option:selected').val();

        className = element.attr('class').split(' ');
        className = className[1];

        //$('.'+className).val(val);
        var select_this = element;
        $.post('/fitmentSelect/processSelect/', data, function(response){
            type = response.type;
            //strip the digit off the end of the submodel and check if its actually
            //a submodel
            type = type.replace(/\d/, '');

            //if its not a submodel replace the disabled version
            if(type != 'submodel' && response.content) {
                $('.sub_select_fitment_'+response.type).replaceWith(response.content);

                if(type == 'model') {
                    $('.fitment_submit').show();
                    fullBranchSelected = true;
                    
                   
                    //alterSelect();
                }
            }
            if ($('#product_id').length > 0 && $('#product_id').val() > 0)
            {
            	if(type == 'submodel')
                {
                	select_this.next('select').nextAll('select:visible').each(function(i, index){
                		element.remove();
                	});
                }
            	if ((type == 'submodel' && !response.content) || (type == 'submodel' && $('#product-listing-fitment-selector').length > 0) || (type == 'submodel' && $('#no_submodel_list').length > 0))
            		{
            		setCookie($('#product-listing-fitment-selector .fitment_submit'));
                    buildFitmentComplete();
                    //logic for tween or alterselect thing so frontend looks nice
                   if ($('#fitment_box').length > 0 && $('#fitment_box').is(':visible'))
                   {
                   	 	alterSelect();
                   }else{
                   		tweenBoxes();
                   }
            	   }
                if(type == 'submodel' && response.content) {
                	if($('#no_submodel_list').length == 0)
            		{
                		$('#outer_select_container .select_box_container select:last').after(response.content);
            			//$('.sub_select_fitment_model').next('select').hide();
            		}
                	

                }
                //else add another selectbox
                else {
                    $('.fitment_submit').show();
                //$('#select_box_container select:last').after(response.content);
                }
            }else{
                if(type == 'submodel') {
                	
                	//$('#outer_select_container .select_box_container select:last').after(response.content);
                	 setCookie($('#product-listing-fitment-selector .fitment_submit'));
                     buildFitmentComplete();
                     //logic for tween or alterselect thing so frontend looks nice
                    if ($('#fitment_box').length > 0 && $('#fitment_box').is(':visible'))
                    {
                    	 	alterSelect();
                    }else{
                    		tweenBoxes();
                    }
                    // tweenBoxes();
                }
                //else add another selectbox
                else {
                    $('.fitment_submit').show();
                //$('#select_box_container select:last').after(response.content);
                }
            	
            }
            
//            if (typeof chooseNodeCallBack == 'function')
//            {
//            	chooseNodeCallBack($('.sub_select_fitment_year:selected').html(), $('.sub_select_fitment_make:selected').html(), $('.sub_select_fitment_model:selected').html());
//            }
            

        }, 'json');

    });

    //if they decide they want to change cars
    $('.alter_fitment').live('click', function(e){
        e.preventDefault();

        clearCar(false);
        
        $('.fitment_select').each(function(i, index){
        	$(this).val('-1');
        	var first = null;
        	if (i != 0)
        	{
        		first = $(this).children('option[value="-1"]');
        		$(this).html(first);
        	}
        });
        
        $('#fitment_complete').animate({
            opacity: 0
        }, 100, 'linear', function() {
            $('#fitment_container').animate({
                height: $('.fitment_selects').height()
            }, 150, 'linear', function() {
                $('#fitment_complete').hide();
                $('.fitment_selects').css('opacity', '0');
                $('.fitment_selects').show();
                $('.fitment_selects').animate({
                    opacity: 1
                }, 150);
                $('#fitment_container').height('auto');
            });
        });
    });

    $('#fitment_box .fitment_submit').live('click', function(e){
        if($('.sub_select_fitment_model').val() > 0) {
            e.preventDefault();
            expiry.setMonth(expiry.getMonth() + 6);
            //document.cookie = 'cmp=1;expires='+expiry+';path=/';
            //set the users cookies
            setCookie(this);
            buildFitmentComplete();
            alterSelect();
        }
    });

    $('#product-listing-fitment-selector .fitment_submit').live('click', function(e){
        if($('.sub_select_fitment_model').val() > 0) {
            e.preventDefault();
            expiry.setMonth(expiry.getMonth() + 6);
            //document.cookie = 'cmp=1;expires='+expiry+';path=/';
            //set the users cookies
            setCookie(this);
            buildFitmentComplete();
            tweenBoxes();
        }
    });
   
});


//once the user has decided on a car selection or theyve reached the end of the
//selection branch
function alterSelect() {
    clearTimeout(timeOutId);
    $('#fitment_box .fitment_selects').animate({
        opacity: 0
    }, 200, 'linear', function() {
        $('#fitment_container').animate({
            height: $('#fitment_complete').height()
        }, 250, 'linear', function() {
            $('#fitment_box .fitment_selects').hide();
            $('#fitment_complete').css('opacity', '0');
            $('#fitment_complete').show();
            $('#fitment_complete').animate({
                opacity: 1
            }, 150);
            $('#fitment_container').height('auto');
        })
    })
    if(typeof setPage == 'function') {
        setPage();
    }
}

function tweenBoxes() {
	//check that year box is > 0
	if ($('.sub_select_fitment_year').val() > 0)
	{
		
	
	    $('#product-listing-fitment-selector').animate({
	        opacity: 0
	    }, 200, 'linear', function() {
	        $('#product-listing-fitment-selector').animate({
	            height: $('#fitment_complete').height()
	        }, 250, 'linear', function() {
	            $('#product-listing-fitment-selector').hide();
	            $('#fitment_box .fitment_selects').hide();
	            $('#fitment_complete').show();
	            $('#fitment_box').show(200);
	
	        })
	    })
	    if(typeof setPage == 'function') {
	        setPage();
	    }
    
	}else{
		$('.sub_select_fitment_year').css('css', 'border: 1px solid #ff0000;');
	}
	
}

function buildFitmentComplete() {
    $('li.car_info').empty();
    paragraph = '<a href="">';
    //#fitment_box 
    $('.fitment_selects select').each(function() {
        if($(this).val() > 0) {
        	if ($(this).hasClass('sub_select_fitment_year'))
        	{
        		paragraph += $(this).find('option:selected').text().substr(-2) + ' ';
        	}else{
        		paragraph += $(this).find('option:selected').text() + ' ';
        	}
        }
    })
    paragraph += "</a>";
    paragraph += "<a href='javascript:clearCar();'>X</a>";
    $('li.car_info').append(paragraph);
}

function selectorReset(select_box) {
    //all this extra work just so theres not a ton of flicker on a new selection
    var old = $(select_box).parents('.fitment_selects');
    var copy = old.clone(true);
    //get the index of the selected box
    var index = old.find('select').index(select_box);

    copy.find('select').each(function(){
        //if the index is greater than the currently selected box
        if(copy.find('select').index(this) > index) {
            $(this).empty();

            //figure out which box we are modifying, mostly in order to delete
            //submodels
            type = getSelectType($(this));

            //submodels should disappear
            if(type == 'submodel') {
                //$(this).remove();
            }
            //others should just go back to their defaults
            else {
            	//alert('test');
                $(this).attr('disabled', 'disabled');
                //add the default selection
                if(type[0]) {
                    $(this).append('<option value="-1">Select a '+type[0].toUpperCase() + type.slice(1)+'</option>');
                }
            }
        }
        //otherwise we are still above/at the just changed box
        else {
            //find the corresponding select box in the original and set the copy to
            //have the same selection
            this_index = copy.find('select').index(this);
            $(this).val(old.find('select:eq('+this_index+')').val());
        }
    });

    return copy;
}

function getSelectType(select) {
    type = select.attr('class').split('_');
    type = type[4];
    type = type.replace(/\d/, '');

    return type;
}

function setCookie(select) {
   // cookie_time = new Date();
    //cookie_time.setMonth(cookie_time.getMonth() + 6);
    //if its the year selector flag it as
    //no fitment selected
    if($(select).attr('class') == 'fitment_select sub_select_fitment_year') {
        fit = -1;
    } else {
        //rebuild cookie list
        fit = buildFitmentCookie();
    }
/*
    document.cookie = "fit="
    + fit
    +";expires=" + cookie_time
    +";path=/";

    document.cookie = "yr="
    + escape($('.sub_select_fitment_year').val())
    +";expires=" + cookie_time
    +";path=/";*/

    return;
}
function buildFitmentCookie() {
    cookie = '';
    var yr = 0;
    $('select.sub_select_fitment_year').each(function(i, index){
    	if ($(this).val() > 0)
    	{
    		yr = $(this).val();
    	}
    });
    //check ALL THE SELECT FIELDS HAVE BEEN SELECTED!
    $('select.fitment_select').each(function(index, i){
    	if ($(this).val() <= 0)
    	{
    		return false;
    	}
    });
    

    if ($('#product-detail').length > 0 && $('#product-detail input#product_id').length > 0){
    	
    	//prod detail page, so handly difflydoo
    	$.post('/fitmentSelect/chooseNode/', {
            'node_id': $('.fitment_selects select:last').val(),
            'year': yr,
            'product_id': $('#product-detail input#product_id').val()
            }, function(data){
            	
            	if (typeof chooseNodeCallBack == 'function')
                {
                	chooseNodeCallBack($('.sub_select_fitment_year:selected').html(), $('.sub_select_fitment_make:selected').html(), $('.sub_select_fitment_model:selected').html());
                }
            	
            	if ($('#fitment_dialog').dialog('isOpen'))
            		{
		            	var prodId = $('#product_id').val();
		            	$('#fitment_dialog').dialog('close');
		            	if(typeof loadCartDialog == 'function') {            		
		            		loadCartDialog(prodId);
		            	}
            		}else{
            			if (data.realUrl != undefined)
        	            {
        	            	window.location=data.realUrl;
        	            }
            		}
            	/**/
            	
            }, 'json');
    }else{
    	
    	
    	//hack just incase:
    	var node_id = null;
    	$('.sub_select_fitment_model').each(function(i, index){
    		if ($(this).val() > 0)
    		{
    			node_id = $(this).val();
    		}
    	});
    	
    	var fail = true;
    	
    	//console.log($('.sub_select_fitment_year').val());
    	//console.log($('.sub_select_fitment_model').val());
    	
    	var fyr = true;
    	$('.sub_select_fitment_year').each(function(i, index)
    		{
    			if ($(this).val() > 1)
    			{
    				fail = false;
    			}
    		});
    	
    	var fmodel = true;
    	$('.sub_select_fitment_model').each(function(i, index)
        		{
        			if ($(this).val() > 1)
        			{
        				fail = false;
        			}
        		});
    	
    	if (!fmodel && !fyr)
    	{
    		fail = false;
    	}
    		
//    	$('.fitment_select').each(function(i, index){
//    		if ($(this).val() <= 0)
//    		{
//    			fail = true;
//    		}
//    		//console.log($(this).val());
//    	});
    	//console.log(fail);
    	if (fail == true)
    	{
    		return false;
    	}
    	//console.log(node_id);
    	$.post('/fitmentSelect/chooseNode/', {
        'node_id': node_id,
        'year': yr,
        'url': document.location.href
        },
        function(data)
        {
        	if (typeof chooseNodeCallBack == 'function')
            {
            	chooseNodeCallBack($('.sub_select_fitment_year:selected').html(), $('.sub_select_fitment_make:selected').html(), $('.sub_select_fitment_model:selected').html());
            }
        	
        	if ($('#fitment_dialog').length > 0 && $('#product_id').length > 0 && ('#product-listing-fitment-selector').length > 0)
            {
        		
            	//good chance on prod listing with collision
            	//anyway, close dialog
            	var prodId = $('#product_id').val();
            	$('#fitment_dialog').dialog('close');
            	if(typeof loadCartDialog == 'function') {            		
            		loadCartDialog(prodId);
            	}
            	//$('#fitment_dialog').dialog('close');
            	
            }else{
            	
            	if (data != null && data.realUrl != null && data.realUrl)
            	{
            		window.location = data.realUrl;
            	}else{
            		//try to reload page i guess
            		window.location = window.location;
            	}
            	
            }
        	
        }, 'json');
    }

    return ; //each(function(){
        /*if($(this).val() > 0 && $(this).attr('class') != 'fitment_select sub_select_fitment_year') {
            cookie += $(this).val() + ',';

        }
    })
    return cookie.replace(/,$/, '');*/
}

function getCookie(cookie) {
    var name = cookie + '=';

    var cArray = document.cookie.split(';');

    for (var i=0; i < cArray.length; i++) {
        var c = cArray[i];

        c = $.trim(c);

        if(c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }

    return false;
}

var selectFitmentCounter = 0;
var tFitment = 0;


function newSelect(ele)
{

    //try to get counter from prev..
    var t = ele.attr('class').replace('sub_select_', '');
    if (t > 0)
    {
        selectFitmentCounter = t;
    }else if (ele.hasClass('fitment_years'))
    {
        //wtf?
        return false;
    }

    ++selectFitmentCounter;
    if ($("#sub_select_"+selectFitmentCounter+"").length == 0){
        ele.after("<select class='fitment_select' id='sub_select_"+selectFitmentCounter+"'></select>");
        $("#sub_select_"+selectFitmentCounter+"").change(selectNode);
    }
    return $("#sub_select_"+selectFitmentCounter+"");
}

function selectYear(){
    if ($(this).val() > 0)
    {
        //check if all fields are selected
        var p = $(this).parent();
        checkSelects(p);
    }
}

function checkSelects(container)
{
    var fail = false;
    container.children('select').each(function(i, item){
        if ($(this).val() < 1)
        {
            fail = true;
            if ($(this).next('span').length == 0)
                $(this).after("<span class='select-fitment-error'>*</span>");
        }
    });
    return !fail;
}

function saveNode(ele)
{
	$('select.fitment_select').each(function(index, i){
    	if ($(this).val() <= 0)
    	{
    		return false;
    	}
    });
	
    var thisFitment = ele.prev('div').children('select:last');
    if (checkSelects(thisFitment.parent()))
    {
        var node_id = thisFitment.parent().children('select:not(".fitment_years"):last').val();

        if (node_id == undefined){
            node_id = $('#fitment_model').val();
        }
        $.post('/fitmentSelect/chooseNode/', {
            'node_id': node_id,
            'year': thisFitment.parent().children('select.fitment_years').val(),
            'url': document.location.href
        },
        function(data){
            window.location = window.location;
        }
        );
    }
}

function saveCartChangeFitment(ele, part_src_id)
{
    var fitmentCont = ele.prev('div');
    var fitmentNode = fitmentCont.children('select:not(".fitment_years"):last').val();
    var year = fitmentCont.children('select.fitment_years').val();
    if (year > 1900){
        $.post(get_base_url()+'cart/ajax/updateFitment/', {
            'part_source_id':part_src_id,
            orig_node_id: tFitment,
            node_id:fitmentNode,
            'year':year
        }, function(data){
            if (data.success == 'true')
            {
                fitmentCont.parent().html(data.car);
            }
        }, 'json');
    }else{
        var yrSel = fitmentCont.children('select.fitment_years');
        if (yrSel.next('span.error').length == 0)
        {
            yrSel.after('<span class="error" style="color:#ff0000;display:block;">*</span>');
        }

    }
}

function cartChangeFitment(part_src_id, fitment_id, ele)
{
    var span = ele.parent('span');//$('#cart-item-' + part_src_id).children('.cart-item-details').children('.cart-item-fitment');
    tFitment = fitment_id;
    $.get(get_base_url()+'cart/ajax/getFitmentChange/', {
        'part_source_id':part_src_id,
        'fitment_id': fitment_id
    }, function(data){
        span.html(data);
        $('.fitment_select').change(selectNode);
    });
}

