// Refinement checkbox functionality to color the selected label text and check the hidden input
var timeoutMap = {};
var refinementTimeout;
$(document).ready(function(){
    
	brandDirectoryUrl = "/app/brandDirectory";
    storeDirectoryUrl = "/app/storeDirectory";
    currentDirectoryUrl = storeDirectoryUrl;
    directoryIframeId = "#bs_directory";
 
    
 
    
    
 /*
	$("a#sbdirectory").colorbox({inline:true, href:"#the_directory", title:"Store and Brand Directory"},
		function() {
	    	$("#store_loading").show();
	    	$.get("/app/storeDirectory", function(response) {
				$("#sbResults").html(response);
				$("#store_loading").hide();
			});
	    	
	  
	});
*/
	$("#scrollLinks").localScroll({target: '#scrollTest',duration:1000});
	




	var brandbutton = $("a#directory_brand_toggle");
	var storebutton = $("a#directory_store_toggle");
	
	

	$("a#directory_store_toggle").click(function(e) {
		e.preventDefault();
		$("#sbResults").html("");
		$("#store_loading").show();
		$.get("/app/storeDirectory", function(response) {
			$("#sbResults").html(response);
			$("#store_loading").hide();
		});
		brandbutton.parent("li").removeClass("on");
		$(this).parent("li").addClass("on");
	});

	$("a#directory_brand_toggle").click(function(e) {
		e.preventDefault();
		$("#sbResults").html("");
		$("#store_loading").show();
		$.get("/app/brandDirectory", function(response) {
			$("#sbResults").html(response);
			$("#store_loading").hide();
		});
		storebutton.parent("li").removeClass("on");
		$(this).parent("li").addClass("on");
	});

	
	$("#refine_bybrand,#refine_bystore,#refine_bysales,#refine_bynew").hover(function() {
		$(this).find("a").css("text-decoration","underline");
	},function() {
		$(this).find("a").css("text-decoration","none");
	});

	$("#refine_bybrand,#refine_bybrand_lhn").colorbox(
	    {
	        inline:true, 
	        href:"#brand_dialog", 
	        title:"Choose Your Brands : Pick all you want to see"
	    },
	    function() { 
	        $('#the_brands').html("");
	        $("#brand_loading").show();
    	    var dataUrl =  getCurrentRequestArgsSansIdentifier() + '/attributeSearch?sort=brand';
        	$.get(dataUrl, function(response) {
                $('#the_brands').html(response);
                initializeRefinementModal('#brand_dialog');
        	    initRefinementModal({
                    search_input: '#brand_search_input',
                    form_id: '#brand_att_refine',
                    selector: '#brand_directory a',
                    popular: '#popular_brands',
                    popular_link: '#brand_pop',
                    data_div: '#brands_data',
                    loading: '#brand_loading',
                    content_div: '#the_brands',
                    request_sort: 'brand'
                });
                $("#brand_loading").hide();
                initializeSelectAll();
    		});
    	}
	);

    $("#refine_bystore,#refine_bystore_lhn").colorbox(
        { 
            inline:true, 
            href:"#store_dialog", 
            title:"Choose Your Stores : Pick all you want to see"
        },
        function() { 
            $('#the_stores').html("");
	        $("#store_loading").show();
    	    var dataUrl =  getCurrentRequestArgsSansIdentifier() + '/attributeSearch';
        	$.get(dataUrl, function(response) {
                $('#the_stores').html(response);
                initializeRefinementModal('#store_dialog');
            	initRefinementModal({
            		search_input: '#store_search_input',
            		form_id: '#stores_att_refine',
            		selector: '#store_directory a',
            		popular: '#popular_stores',
            		popular_link: '#store_pop',
            		data_div: '#stores_data',
            		loading: '#store_loading',
            		content_div: '#the_stores',
            		request_sort: 'stores'
            	});
                $("#store_loading").hide();
                initializeSelectAll();
    		});
    	}
    );

//	$("#refine_bybrand").bind('cbox_load', );
	
	

	$("#refine_bysales").colorbox({inline:true, href:"#sales_dialog", title:"Refine by Sale Items"});

	$("#refine_bynew").colorbox({inline:true, href:"#new_prods_dialog", title:"Refine by New Items"});


    function getCurrentRequestArgsSansIdentifier() {
        var url           = document.location.toString().split("?")[0];
        url               = url.split("#")[0];
        // full uri sans the "http://"
        var host          = url.substring(url.indexOf("/") + 2, url.length);
        // just the path after the host
        var path          = host.substring(host.indexOf("/") + 1, host.length);
        if (path.substring(path.length - 1 ) != "/") {
            path = path + '/';
        }
        var parts         = path.split("/");
        return '/' + parts.slice(0, parts.length - 1).join('/');
    }



    function initRefinementModal(config) {
        for (field in {selector:null, popular:null, data_div: null, form_id:null, popular_link:null,
                loading:null, content_div:null, request_sort:null, search_input: null}) {
            if (! config[field]) {
                return;
            }
        }
        
        
        function unhighlightAlpha() {   
            $(config.popular_link).parent("div").removeClass("chosen");
        	$(config.selector).each(function() {
        		$(this).parent("div").removeClass("chosen");
        	});
        }
        $(config.selector).each(function() {
            $(this).click(function(e) {
                e.preventDefault();
                unhighlightAlpha();
                $(this).parent("div").addClass("chosen");
            });
        });
        
        $(config.popular_link).click(function(e) {
            e.preventDefault();
            unhighlightAlpha()
            $(this).parent("div").addClass("chosen");
        });

        $(config.form_id).click(function(e){
            e.preventDefault();
            var form = this;
			
            var atts = new Array();
            var req_parts = getCurrentRequestPartsSansAttributes();
            $('.selected_attribute').each(function() {
                atts.push(this.id);
            });
            var end = null;
            var query = getRequestParameters();
            if (req_parts.length > 1 )  {
            	if(isTriggerWord(req_parts[req_parts.length-1])) {
            		end = req_parts.pop();
            	}
            }
            var newUrl = '/' + req_parts.join('/');

            if (atts.length)  {
            	newUrl = terminateWithSlash(newUrl) + atts.join('/');
            } 	
            
            if(end) {
            	newUrl = terminateWithSlash(newUrl) + end;
            }	
            
            if (query) {
                newUrl += '?' + query;
            }
            document.location =  newUrl.replace(/\??start=\d+\&?/, "");
            return false;
        });
        
    }

    
    

    var theChosenBrands = $("#brand_dialog .chosen_refinements span#chosenBrands span.selected_attribute");
	var theChosenStores = $("#store_dialog .chosen_refinements span#chosenStores span.selected_attribute");
	var theChosenAttsOuterContainer = $("#brand_dialog .chosen_refinements");
	var theChosenStoreAttsOuterContainer = $("#store_dialog .chosen_refinements");
	
//	var numberChosenBrands = $("#brand_dialog #chosen_refinements").children().size();
	
    if (theChosenBrands.length) {
        theChosenAttsOuterContainer.find('.default').hide();
        
        $(theChosenBrands).each(function() {          
            initializeChosenRefinement($(this));
        });
        manageChosenAttributes();
    }
    
    if (theChosenStores.length) {
        theChosenStoreAttsOuterContainer.find('.default').hide();
        
        $(theChosenStores).each(function() {          
            initializeChosenRefinement($(this));
        });
        manageChosenAttributes();
    }
    
 
	function manageCheckbox(input, appendWhere, listItem) {
		return function(e) {
		    e.preventDefault();
			if (input.is(':checked')) {
				input.attr('checked',false);
				listItem.removeClass("checked");
				$('#' + input.val()).remove();
				manageChosenAttributes();
			} else {
				input.attr('checked',true);
				listItem.addClass("checked");
				appendRefinement({
					appendTo: appendWhere,
					id: input.val(), 
					label: listItem.find(".name").html() 
				});
			}   				
		};		
	}
	
	function manageTheCheckbox(input, appendWhere, listItem) {
		return function(e) {
			if (input.is(':checked')) {
				input.attr('checked',true);
				listItem.addClass("checked");
				appendRefinement({
					appendTo: appendWhere,
					id: input.val(), 
					label: listItem.find(".name").html() 
				});
			} else {
				input.attr('checked',false);
				listItem.removeClass("checked");
				$('#' + input.val()).remove();
				manageChosenAttributes();
			}		
		};		
	}
	

    var selected_attr_click_handler = function(e) {
        e.preventDefault();
        var parent =  $(this).parent("span.selected_attribute");
        var input = $("input[value='" + parent.attr("id") + "']"); 
        $(input).attr("checked", "");
        $(input).parent("li").removeClass("checked");
        $(parent).remove();
        manageChosenAttributes();
    };
    
    function appendRefinement(ref) {
        for (field in {appendTo:null, id:null, label:null} ) {
            if (! ref[field] )
                return;
        }
        $(ref.appendTo).parent().find('.default').hide();
        var obj = "<span class='selected_attribute' id='" + ref.id +"'><p>" + ref.label + "</p> <div class='attr_remove_tab'> </div></span> ";
        $(ref.appendTo).append(obj);
        initializeChosenRefinement($('#' + ref.id));
        manageChosenAttributes();
    }
    
    function initializeChosenRefinement(obj) { 	
    	var rm_me = obj.find(".attr_remove_tab");
		var rm_name = obj;

		obj.mouseover(function() {
			var attr_width = $(this).width();
			var lefty = (((attr_width - 12)/2) - 30)
			var attr_left = $(this).position().left + lefty;
			var attr_top = ($(this).position().top) - 24;
            
            rm_me.css("top",-24);
    		rm_me.css("left",lefty);
    		rm_me.show();
    		rm_me.unbind("click");
    		rm_me.click(selected_attr_click_handler);
		});
		obj.mouseout(function() {
		    timeoutMap[$(obj).attr("id")] = setTimeout(function() {
		     rm_me.hide();
		    }, 150);
		});
		obj.unbind("click");
		obj.click(function() {
        	var input = $("input[value='" + $(this).attr("id") + "']"); 
        	$(input).attr("checked", "");
        	$(input).parent("li").removeClass("checked");
        	$(this).remove();
        	manageChosenAttributes();			
		});
		rm_me.mouseover(function() {
		    clearTimeout(timeoutMap[$(this).parent().attr("id")]);
		    delete(timeoutMap[$(this).parent().attr("id")]);
		});
	}
    
    
    
    function manageChosenAttributes() {
    	var numberOfStoresChosen = $("#chosenStores").children().length;
    	var numberOfBrandsChosen = $("#chosenBrands").children().length;
    	var clearAllStores = $("#clear_all_stores");
    	var clearAllBrands = $("#clear_all_brands");
		
		var clearAll = "<span id='clear_all_refinements'>x Clear All</span>";
		
		if (numberOfStoresChosen > 0) {
        	clearAllStores.show();
        	initializeClearAllChosenAttributes();
        }
        if (numberOfBrandsChosen > 0) {
        	clearAllBrands.show();
        	initializeClearAllChosenAttributes();
        }
        
		if (numberOfStoresChosen < 2) {
			clearAllStores.hide();
		}
		
		if (numberOfBrandsChosen < 2) {
			clearAllBrands.hide();
		}
		if (numberOfStoresChosen < 1) {
			$("#chosenStores").parent().find(".default").show();
		}
		if (numberOfBrandsChosen < 1) {
			$("#chosenBrands").parent().find(".default").show();
		}
    }

    
    function initializeClearAllChosenAttributes() {
    	
    	$("#clear_all_stores").click(function() {
    		var thoseToClear = $(this).parent().children(".the_chosen_ones").children("span");
    		thoseToClear.each(function() {
    			var input = $("input[value='" + $(this).attr("id") + "']"); 
				$(input).attr("checked", "");
				$(input).parent("li").removeClass("checked");
				$(this).remove();
    			
    		});
    		manageChosenAttributes();
    	});
    	$("#clear_all_brands").click(function() {
    		var thoseToClear = $(this).parent().children(".the_chosen_ones").children("span");
    		thoseToClear.each(function() {
    			var input = $("input[value='" + $(this).attr("id") + "']"); 
				$(input).attr("checked", "");
				$(input).parent("li").removeClass("checked");
				$(this).remove();
    			
    		});
    		manageChosenAttributes();
    	});
    }
    
    $("#sales_dialog>ul>li,#new_prods_dialog>ul>li").find(".label").hover(function() {
    	$(this).parent("div").parent("li").addClass("over");
    },function() {
    	$(this).parent("div").parent("li").removeClass("over");
    });
    
	$(".buttons .cancel").click(function(e) {
	    e.preventDefault();
		$.fn.colorbox.close();
	});
        
   
   
	function initializeRefinementModal(id) {
		var appendWhere = $(id).find(".the_chosen_ones");
		
		$("#scrollTest2 > ul").each(function() {
    		var theListItems = $(this).children();
    		
       		theListItems.each(function() {
       			var theCheckbox = $(this).children("input");
       			var listItem = $(this);
       			var itemLabel = $(this).find("label");
       			var replacedCheckbox = $(this).children(".checkboximg");
       			
				theCheckbox.click(manageTheCheckbox(theCheckbox,appendWhere,listItem));
				
				itemLabel.click(manageCheckbox(theCheckbox,appendWhere,listItem));
      
				itemLabel.mouseover(function() {
					listItem.addClass("poover");
				});
				itemLabel.mouseout(function() {
					listItem.removeClass("poover");
				});
/*
				replacedCheckbox.mouseover(function() {
					listItem.addClass("poover");
				});
				replacedCheckbox.mouseout(function() {
					listItem.removeClass("poover");
				});
*/
			});
		});
	}
    
    
    function initializeSelectAll() {
    	$("#select_all_Favorites").click(function(e) {
			var choices = $("#scrollTest2").children(".Favorites_container").children();
			e.preventDefault();
			
			choices.each(function() {
				var theCheckbox = $(this).children("input");
				var listItem = $(this);
				var itemLabel = $(this).find("label");
				
				itemLabel.click();
			});
			
//			$("#select_all_Favorites b").toggle();

		});
		
		$("#select_all_Popular").click(function(e) {
			var choices = $("#scrollTest2").children(".Popular_container").children();
			e.preventDefault();
			
			choices.each(function() {
				var theCheckbox = $(this).children("input");
				var listItem = $(this);
				var itemLabel = $(this).find("label");
				
				itemLabel.click();						
			});
		});
    }
    
    
    
	$("#alphascroll_store").localScroll({target: '#scrollTest2',duration:1000});
	$("#alphascroll_brand").localScroll({target: '#scrollTest2',duration:1000});
   

	function manageAllFaves(input,atts) {
		return function(e) {
		    e.preventDefault();
			
			var imgCheckbox = input;
			var metaCheckbox = input.children("input");
			
			var faveSelections = atts.children();
			
			// console.log(faveSelections);
			
			
			if (metaCheckbox.is(':checked')) {
				metaCheckbox.attr('checked',false);
				imgCheckbox.parent().removeClass("checked");
				
				faveSelections.each(function() {
					var input = $(this).children().children("input");
					input.attr('checked',false)
				});
				submitRefinement("#outer_stores_form");
				
			} else {
				metaCheckbox.attr('checked',true);
				imgCheckbox.parent().addClass("checked");
				
				faveSelections.each(function() {
					var input = $(this).children().children("input");
					input.attr('checked',true);
					
				});
				submitRefinement("#outer_stores_form");
			}
			
		};		
	}

	function initializeAllFaves() {
		var checkboxStore = $("#all_faves_store");
		var checkboxBrand = $("#all_faves_brand");
		
		var faveSelectionsStore = $("#allFavestore");
		var faveSelectionsBrand = $("#allFavebrand");
	
		var afstore = $("#afstore");
		var afbrand = $("#afbrand");
	
		checkboxStore.click(manageAllFaves(checkboxStore,faveSelectionsStore));
		checkboxBrand.click(manageAllFaves(checkboxBrand,faveSelectionsBrand));
		
		afstore.click(manageAllFaves(checkboxStore,faveSelectionsStore));
		afbrand.click(manageAllFaves(checkboxBrand,faveSelectionsBrand));
	}
	

  
    $("#storerefiner li,#brandrefiner li,#faves_296935 li,#faves_259 li").each(function() {
    	var fakeInput = $(this).children(".checkboximg");
    	var itemLabel = $(this).children().children("label");
    	
    	fakeInput.click(function() {
    		var input = $(this).children("input");
    		
    		if (input.is(':checked')) {
    			input.attr('checked',false);
    			$(this).parent().removeClass("checked");
    		} else {
    			input.attr('checked',true);
    			$(this).parent().addClass("checked");
    		}
    		delayedSubmitRefinement("#outer_stores_form");
    	});
    	
    	itemLabel.click(function() {
    		var input = fakeInput.children("input");
    		
    		if (input.is(':checked')) {
    			input.attr('checked',false);
    			$(this).parent().removeClass("checked");
    		} else {
    			input.attr('checked',true);
    			$(this).parent().addClass("checked");
    		}
    		delayedSubmitRefinement("#outer_stores_form");
    	});
    	
    });
    

    function delayedSubmitRefinement(formId) {
        clearTimeout(refinementTimeout);
        refinementTimeout = setTimeout("submitRefinement('" + formId + "')", 1);
    }

    
    
    function checkFavorites() {
    
    	var totalFaves = $("#allFavestore input").length;
    	var numUnchecked = $("#allFavestore input:not(:checked)").length;
    	var numChecked = $("#allFavestore input:checked").length;
    	    	
    	if ((totalFaves > 0) && (numChecked == totalFaves)) {
    		$("#all_faves_store").parent("li").addClass("checked");
    		$("#all_faves_store").children("input").attr('checked',true);
    	}
    	
    	var totalFavesBrand = $("#allFavebrand input").length;
    	var numUncheckedBrand = $("#allFavebrand input:not(:checked)").length;
    	var numCheckedBrand = $("#allFavebrand input:checked").length;
    	
    	if ((totalFavesBrand > 0) && (numCheckedBrand == totalFavesBrand)) {
    		$("#all_faves_brand").parent("li").addClass("checked");
    		$("#all_faves_brand").children("input").attr('checked',true);
    	}
    	
    	
	}
	
    // TODO: remove me?
	function clearRefinements() {
		var checkedFavorites = $("#allFavestore input:checked").length;
		var checkRefinements = $("#faves_296935 input:checked").length;

		var checkedFavoritesBrand = $("#allFavebrand input:checked").length;
		var checkRefinementsBrand = $("#faves_259 input:checked").length;

	}


	function showRefinement(item) {
		return function() {
			var cname = $(this).attr('class').split(' ').slice(-1); 

			item.toggle();
			if (cname == 'open') {
				$(this).removeClass("open");
			} else {
				$(this).addClass("open");
			}
			
			
		};
	}
	

	$("#brands_showtoggle").click(showRefinement($("#brandrefwrapper")));
	$("#stores_showtoggle").click(showRefinement($("#storerefwrapper")));



	function checkForStoreRefinement() {
		var numChecked = $("#storerefwrapper input:checked").length;
		
		if (numChecked > 0) {
			var cname = $("#stores_showtoggle").attr('class').split(' ').slice(-1);
			
			$("#storerefwrapper").toggle();
			if (cname == 'open') {
				$("#stores_showtoggle").removeClass("open");
			} else {
				$("#stores_showtoggle").addClass("open");
			}
		}
	}
	
	checkForStoreRefinement();
	initializeAllFaves();	
	checkFavorites();
	clearRefinements();
});
 
var triggerWords = new Array('on-sale', 'filteredAttributeSearch', 'attributeSearch', 'search', 'browse', 'browseStore', 'browseBrand', 'new-items', 'sitemap');

function isTriggerWord(value) {
    // make sure we've eliminated any trailing # or ? characters
    var word = value.split(/(#|\?)/)[0];
    var isTrigger = false;
    for(i=0; i < triggerWords.length && !isTrigger; i++) {
        if(triggerWords[i] == word) {
            isTrigger=true;
        }
    }	
    return isTrigger;
}

function getRequestParameters() {
    var url = document.location.toString();
    // XXX: until sas allows us to search from cid 1
    // hopefully, the parameters wont get shifted around 
    // as this expects the cid to be at the end
    if (query = url.split("?")[1]) {
        return query.replace(/&categoryId=1$/, '').replace(/\&?logged_in=1/, '');
    } else {
        return "";
    }
}

function getCurrentRequestPartsSansAttributes() {
    var url           = document.location.toString();
    url               = url.split("?")[0];
    // full uri sans the "http://"
    var host          = url.substring(url.indexOf("/") + 2, url.length);
    // just the path after the host
    var path          = host.substring(host.indexOf("/") + 1, host.length);
    var parts         = path.split("/");
    var cleaned = new Array();
    for (var i = 0; i < parts.length; i++) {
        if (! parts[i].match(/^\d+\-\d+/) ) {
            cleaned.push(parts[i]);
        }
    }
    return cleaned;
}

/*
 * Ensure that the string ends with a slash. Takes a string, 
 * returns that string plus a slash if necessary.
 */
function terminateWithSlash(path) {
    if(path.length > 0 && path.charAt(path.length-1) == '/') {
        return path;
    }
    return path + '/';
}		

// TODO: this is duplicating alot of the method ~line 208
function submitRefinement(formId) {
    var atts = new Array();

    var req_parts = getCurrentRequestPartsSansAttributes();

    $(formId + " input:checked").each(function() {
            atts.push($(this).attr("value"));
            });

    var end = null;

    var query = getRequestParameters();

    if (req_parts.length > 1 )  {
        if(isTriggerWord(req_parts[req_parts.length-1])) {
            end = req_parts.pop();
        }
    }

    var newUrl = '/' + req_parts.join('/');

    if (atts.length)  {
        newUrl = terminateWithSlash(newUrl) + atts.join('/');
    } 	

    if(end) {
        newUrl = terminateWithSlash(newUrl) + end;
    }	

    if (query) {
        newUrl += '?' + query;
    }
    document.location =  newUrl.replace(/\??start=\d+\&?/, "");
    return false;
}

