var activeChannel = null;
var activeTags = [];

// this flag is used to know if the list of products cshouldbe loaded every time a new channels is clicked
var hasNoTags = true;
var colorFilterOn = false;

// this flag is set to know which slot is currently used
var currentClickSlot = null;

var slots = {sex:null,measure:null,clr:null,explore:null,cat:null};
var slotList = ["sex","measure","clr","explore","cat"];
var activeTagMarkerRef = new Array();
var activeColorFilterTag = null;
var firstTimeOnExploreChannel = true;

jQuery(document).ready(function()
	{
		
		setAllChannelLinks();

		jQuery("#channelSize").click(function(){openChannel("Size");});
		jQuery("#channelColor").click(function(){openChannel("Color");});
		jQuery("#channelRanges").click(function(){openChannel("Ranges");});
		
		jQuery("#channelExplore")
			.click(function(){openChannel("Explore");})
			.click(openExploreChannel);
		
		
		jQuery("#channelCategory").click(function(){openChannel("Category");});
		jQuery("#channelBoy").click(function(){openChannel("Boy");});
		jQuery("#channelGirl").click(function(){openChannel("Girl");});
		jQuery("#channelBaby").click(function(){openChannel("Baby");});
		jQuery(".closeChannelsButton").click(function(){openChannel(activeChannel);});
		
		jQuery("#channelStoresMapView").click(function(){openChannel("channelsContentStoresMapView");});
		jQuery("#channelStoresListView").click(function(){openChannel("channelsContentStoresListView");});
		jQuery("#channelStoresOnline").click(function(){openChannel("channelsContentStoresOnline");});
		
		
		jQuery(".showThemAll").click(function(){openChannel("reset");});
		
		// this is used to preview a collection
		jQuery("#channelPreview").click(function(){openChannel("Collection", {collection: true, collectionId: 6});});
		
		// this is used to look at an old collection
		jQuery("#channelAW09").click(function(){openChannel("AW09", {collection: true, collectionId: 5});});
		
		// this can be used to se a subset of a collection by tags. REMEMBER to change the selector if needed
		//jQuery("#channelHW09").click(function(){openChannel("HW09", {tags: ["hw09"]});});
		//jQuery("#resetAllChannelsLink").click(function(){resetAllChannels();});
		
	/*	jQuery(".channelsContainer").scrollable(
			{ 
	    		size: 3, 
				items: ".channelBox"
			}
		);*/
		

		if (isAdmin)
		{
			var tagDebug = jQuery("<div id='tagDebug' style='display: none;position: absolute; width: 300px; top: 0px; left: 0px; background-color: #F0F0F0; color: #666666; font-size: 10px; padding: 10px;'><h3 style='margin-top: 2px;'>Chosen channel tag list:</h3><div class='tagList'></div></div>");
			jQuery(document.body).append(tagDebug);
		}

		
	});
	
	
function openExploreChannel()
{
	jQuery(".linklistHeaderLi .ciActive").removeClass("ciActive");
	if (firstTimeOnExploreChannel)
	{
		if (defaultExplorePage != "")
		{
			openExplorePage(defaultExplorePage);
		}
		firstTimeOnExploreChannel = false;
	}
}

function openChannelFromGender()
{	
	openChannel("channelsContentGender", "sex");
}


function openChannel(id, newOptions)
{

	var options = {
		collection: false, 
		collectionId: 1,
		tags: []
	};
	
	if (arguments.length > 1)
	{
		for (key in newOptions)
		{
			options[key] = newOptions[key];
		}
	}
	
	// clear the previewId
	previewId = "";
	
	// google analytics
	if (activeChannel != id) urchinTracker(pageType + '/channels/' + id);

	// if a filter color is selected, mark for reload of products
	//if (colorFilterOn) hasNoTags = false;
	
	// if there is at least one tag, 
	if (activeTags.length > 0) 
	{
		// HERE WE HAVE TO CHECK IF ITS A GENDER TAG AND ITS THE SAME AS BEFORE. IF THATS THE CASE, WE DONT RELOAD THE PRODUCTS
		//	hasNoTags = false;
	}

	// if there is a channel selected, and its not the same as the one clicked now, we slide it up.
	if ((activeChannel != null) && (activeChannel != id)) 
	{
		jQuery("#channelsContent" + activeChannel).slideUp();	
	}

	// if its a new channel compared to the one active
	if (activeChannel != id) 
	{
		
		if (activeChannel != "Collection")
		{
			jQuery("#channelsContent" + id).slideDown(
				function()
				{ 
					if (options.tags.length > 0)
					{		
					
						// if we sent a predefined tags list we create a new array here
						var newTagList = [];
						
						// then we get grough all tags ans get there reference
						for(var i = 0; i < options.tags.length; i++)
						{
							var tagName = options.tags[i];
							tagName = tagName.replace(/^\s*|\s*$/g, "");
							newTagList.push(tt[tagName].id);
						}
						
						// the we call the open function to show the products
						openChannelTag(newTagList);
						
					}
					else
					{
						if (activeTags.length > 0) 
						{	
							activeTags = []; 
							getProducts([]);
						}
					}
				}
			);
		}
		else
		{
			jQuery("#channelsContent" + id).slideDown(
				function()
				{ 
					activeTags = []; 
					getProducts([]);
				}
			);
		}
		
		if (id == "reset")
		{
			activeTags = []; 
			getProducts([]);
		}
		
		if (options.collection)
		{
			activeTags = ["Collection"]; 
			previewId = "&collectionId=" + options.collectionId;
		//	getProducts([]);
		}
		
		jQuery("#channelsSubStripe").slideDown('fast');	
		
		jQuery(".channelBox" + activeChannel + " .channelBoxContent").removeClass("activeChannel");
		jQuery(".channelBox" + id + " .channelBoxContent").addClass("activeChannel");
			
	}
	else
	{
		//  otherwise (ie its the same channel as before)
		// -----------------------------------------------
		
		// we first check if some tag is active, in wich case we reload the product list
		if (!hasNoTags) 
		{
			// clear the tags and reload the complete productlist
			// getProducts([]);
		}
		
		var isActive = jQuery(".channelBox" + activeChannel + " .channelBoxContent").hasClass("activeChannel");
		
		
		isActive = !isActive;
		
		// if the channel is active, do the right thing
		// else just close the div
		if (isActive) 
		{
			jQuery("#channelsContent" + activeChannel).slideDown();
			jQuery("#channelsSubStripe").slideDown('fast');	
			jQuery(".channelBox" + activeChannel + " .channelBoxContent").addClass("activeChannel");
		}
		else 
		{
			activeTags = [];
			jQuery("#channelsContent" + activeChannel).slideUp();
			jQuery("#channelsSubStripe").slideUp(700);	
			jQuery(".channelBox" + activeChannel + " .channelBoxContent").removeClass("activeChannel");
		}
		
	}
	
	if (id == "reset") id = null;
	// remeber the active channel
	activeChannel = id;
	
	// we remove the code for the sub color filter. if we want to activate it again, we just remove the comments tags
	/*if (slot != "clr")
		jQuery(".colorFilter").slideDown();
	else
		jQuery(".colorFilter").slideUp();*/
	
	jQuery(".ciFilter").css("opacity", "1");
	
	if (activeTagMarkerRef != null) 
	{
		jQuery("*[tags='" + activeTagMarkerRef + "']").removeClass("ciActive");
		activeTagMarkerRef = null;
	}
	
	//hasNoTags = true;
	//colorFilterOn = false;
	
	if (activeColorFilterTag != null) 
	{
		jQuery("#t" + activeColorFilterTag).removeClass("ciActive");
		activeColorFilterTag = null;
	}
	
}

/**
 * This is a fix to be able to have a channel that opens another colleciton.
 * It resets the "previewid" string and changes it to another. Also, it empties the current tag array.
 */



function getChannelCombinations()
{
	// we begin with an empty list
	var tags = activeTags;//.join(",") + "," + colorTag).split(",");
	//tags.push(colorTag);
	
	
	//alert(activeTags);
	// put together the list of tags from the slot
	/*// go trough all slots
	for (var i = 0; i < slotList.length; i++) 
	{
		var slot = slots[slotList[i]];
		
		// if the current slot is ok
		if ((slot != null) && (slotList[i] != channelSlot))
		{
			// since each slot might have more than one tag, we go trough all of them
			for (var j = 0; j < slot.length; j++) 
			{
				tags.push(slot[j]);
			}
		}
	}*/
	
	var tagsListWithMetaData = new Array();
	for(var i = 0; i < tags.length; i++)
	{
		var tagItem = tagObjectList[tags[i]];
		var metaData = tagItem.metaData;

		var tagName = tagItem.name;
		tagName = tagName.replace(/\+/gi, "^^");
		tagsListWithMetaData.push(tags[i] + ":" + tagName + ":" + metaData);
	}
	
	//alert(tagsListWithMetaData);
	if (tagsListWithMetaData.length > 0) 
	{
		
		//currentClickSlot = channelSlot;
		ajaxReadWithCallBack(channelsCombinationXmlUrl + "?tags=" + tagsListWithMetaData.join("|") + "&currentMetaData=clr&seed=" + currentSeed + previewId, updateChannelsTags);
	}
}







function setAllChannelLinks()
{
	// print out colors
	createColorChannel();
	
	var links = jQuery(".ci");
	for(var i = 0; i < links.length; i++)
	{
		var linkItem = jQuery(links[i]);
		
		// set the content of the title attribute to a new attirbute caleld tags. 
		// this is done both fror the tooltip and to keep w3c standards
		linkItem.attr("tags", linkItem.attr("title"));
		if (tt[linkItem.attr("tags")] != null) 
		{
			//linkItem.attr("id", "t" + tt[linkItem.attr("tags")].id);
			linkItem.attr("metadata", tt[linkItem.attr("tags")].metaData);
		}
		linkItem.click(channelTagClick);
	}
	
	var links = jQuery(".ciFilter");
	for(var i = 0; i < links.length; i++)
	{
		var linkItem = jQuery(links[i]);
		
		// set the content of the title attribute to a new attirbute caleld tags. 
		// this is done both fror the tooltip and to keep w3c standards
		linkItem.attr("tags", linkItem.attr("title"));
		if (tt[linkItem.attr("tags")] != null) 
		{
			linkItem.attr("id", "t" + tt[linkItem.attr("tags")].id);
			linkItem.attr("metadata", tt[linkItem.attr("tags")].metaData);
		}
		linkItem.click(colorFilterTagClick);
	}
	
	
	
	var slotContainers = jQuery(".slot");
	for(var i = 0; i < slotContainers.length; i++)
	{
		var slotContainer = jQuery(slotContainers[i]);
		slotContainer.attr("slot", slotContainer.attr("title"));
		slotContainer.attr("title", "");
	}
}


function channelTagClick()
{
	var tagString = this.getAttribute("tags");
	var tagStringList = tagString.split(",");
	
	var tagList = new Array();
	var tag;
	
	var debugContainer = jQuery("#tagDebug").hide().find(".tagList").empty();
	
	
	for(var i = 0; i < tagStringList.length; i++)
	{
		var tagName = tagStringList[i];
		tagName = tagName.replace(/^\s*|\s*$/g, "");
		var tagWasFound = false;
		if (tt[tagName] != null)
		{
			tagList.push(tt[tagName].id);
			tag = tt[tagName];
			tagWasFound = true;
		}
		
		if (isAdmin)
		{
			var tagObj = jQuery("<div>" + tagName + " - " + (tagWasFound ? "[TAG OK]" : "<strong>[NOT FOUND - <a rel='" + tagName + "'>CREATE</a>]</strong>") + "</div>");
			tagObj.find("a").bind("click", _createTag);
			debugContainer.append(tagObj);
			jQuery("#tagDebug").show()
		}
	}

	openChannelTag(tagList);
	
	// this is used to get a sublist oif all avaliable tags withing the selection. We have commented it out because they might be used later on
	//if (tag.metaData != "clr") getChannelCombinations();
	
	if (activeTagMarkerRef != null) 
	{
		jQuery("*[tags='" + activeTagMarkerRef + "']").removeClass("ciActive");
	}

	jQuery("*[tags='" + tagString + "']").addClass("ciActive");
	activeTagMarkerRef = tagString;
	
}


function _createTag(event)
{
	var aObj = jQuery(event.target);
	var tagName = aObj.attr("rel");
	
	jQuery.getJSON("/public/API-2.0/Tags.aspx", {collectionId: collectionId, tag: tagName}, function(response)
	{
		aObj.parent().parent().html(tagName + " - [TAG OK]");
	});
	
}


function colorFilterTagClick()
{
	var tag = tt[this.getAttribute("tags")];
	var tags = activeTags.length > 0 ? activeTags.join(",").split(",") : [];
	tags.push(tag.id);
	colorFilterOn = true;
	
	if (activeColorFilterTag != null) 
	{
		jQuery("#t" + activeColorFilterTag).removeClass("ciActive");
	}

	activeColorFilterTag = tag.id;
	jQuery("#t" + activeColorFilterTag).addClass("ciActive");
	
	
	getProducts(tags);
}


function setChannelIndicatorColor(tag)
{
	jQuery("#channelIndicatorDivColor").html("<img src='/public/media/colors/" + createFileName(tag.name) + ".jpg'>");
}


function openChannelTag(tagNameList)
{
	jQuery(".ciFilter").css("opacity", .1);
	
	// we begin with an empty list
	activeTags = new Array();

	for (var j = 0; j < tagNameList.length; j++) 
	{
		activeTags.push(tagNameList[j]);
	}
	
	// lastly, we call the search function with the array of tags
	getProducts(activeTags);
	
	displayChannelBreadcrumb(activeTags);
}



function resetTags()
{
	jQuery(".ciFilter").css("opacity", 1);
	
	// we begin with an empty list
	activeTags = new Array();

	// lastly, we call the search function with the array of tags
	getProducts(activeTags);
	
	displayChannelBreadcrumb(activeTags);
}




function displayChannelBreadcrumb(tag)
{
	
}



// this function creates color items from all colors on the product database (but only for the current collection)
function createColorChannel()
{
	var colorContainer = jQuery("#channelsContentColor .channelsSubBoxContent");
	var colorFilterContainer = jQuery("#colorFilterContainer");
	for(var i = 0; i < tm["clr"].length; i++)
	{
		var c = tm["clr"][i];
		var cDom = jQuery("<div class='channelColor ci tooltip' title='" + c.name + "'><img src='/public/media/colors/" + createFileName(c.name) + ".jpg'>");
		colorContainer.append(cDom);
		
		var cDom = jQuery("<div class='channelColor tooltip ciFilter' title='" + c.name + "'><img src='/public/media/colors/" + createFileName(c.name) + ".jpg'>");
		colorFilterContainer.append(cDom);
	}
}


function createFileName(name)
{
	name = name.replace(/[ \/]/gi, "");
	return name;
}

function updateChannelsTags(xml, channelSlot)
{
	
	// if the active tag list is empty, we just activate all tags
	// otherwise we turn of all and then we turn on only the active ones.
	if (activeTags.length > 0) 
	{

		var scope = ""; //div[slot='" + channelSlot + "'] ";
			
		// make all tags semitransparent
		jQuery(scope + ".ciFilter").css("opacity", .1);
		
		// get a list of all active tags
		var productTags = XPath.selectNodes("//ta", xml);
		
		// iterate trough all tags
		for(var i = 0; i < productTags.length; i++)
		{
			// show the ones that are active
			var ci = jQuery("#t" + productTags[i].getAttribute("id"));
			
			ci.css("opacity", 1);
			
		}
		
	}
}

// reset all channels and active all tags
function resetAllChannels()
{
	jQuery(".ci").css("opacity",1);
	jQuery(".ci").removeClass("ciActive");
	jQuery(".channelIndicator").html("");
	activeTags = [];
	currentClickSlot = null;
	slots = {sex:null,measure:null,clr:null,explore:null,cat:null};
	activeTagMarkerRef = new Array();
	getProducts(activeTags);
}


