// Enable/disable different debuging info
var DEBUG = false;

//DEFAULTS SCROLL DISPLAY

// SCROLL VARS
var heightInterval = HEIGHTINTERVAL;
var speed = SPEED;
var scrollInfo_crop = SCROLLINFO_CROP;
var scrollInfo_postfix = SCROLLINFO_POSTFIX;
var scrollInfo_split = SCROLLINFO_SPLIT;

var PATHS = new Array();
PATHS['flash'] = 'fileadmin/templates/flash/';
var swfVars = '';

// MAIN DATA ARRAY. OUTGOING ARRAY
var state = new Array();

// FLASH SELECTOR SETTINGS 
var flashSelectors = new Array();
flashSelectors['2'] = new Array();
flashSelectors['2']['name'] = 'COLOR';
flashSelectors['2']['placeholder'] = 2;
flashSelectors['2']['flashHeight'] = '100';
flashSelectors['2']['flashWidth'] = '170';
flashSelectors['2']['flashFile'] = 'fileadmin/templates/flash/farveskala_9.swf';
flashSelectors['2']['flashVersion'] = '8.0';
flashSelectors['2']['flashBG'] = '#F6F4F4',
flashSelectors['2']['swfVar'] = 'color';

flashSelectors['4'] = new Array();
flashSelectors['4']['name'] = 'PATTERN';
flashSelectors['4']['placeholder'] = 4;
flashSelectors['4']['flashHeight'] = '100';
flashSelectors['4']['flashWidth'] = '170';
flashSelectors['4']['flashFile'] = 'fileadmin/templates/flash/moenstervaelger_8.swf';
flashSelectors['4']['flashVersion'] = '8.0';
flashSelectors['4']['flashBG'] = '#F6F4F4',
flashSelectors['4']['swfVar'] = 'pattern';

flashSelectors['2']['label'] = new Array();
flashSelectors['2']['label']['1'] = 'Test 1';
flashSelectors['2']['label']['2'] = 'Test 2';
flashSelectors['2']['label']['3'] = 'Test 3';


// Debug info (state array)
function print_category(arr){
	
	for(i=0;i<arr.length;i++){
		for (key in arr[i]){
			alert("\n"+key+"=>" + arr[i][key]);
		}
	}
}



function eventEffect(item, event){
	  
	var searchItem = document.getElementById(item);
	var currentClass = document.getElementById(item).className;
	var newClass = currentClass;
		  
	if(currentClass != 'item-on'){
		if(event == 'on'){
			newClass = 'item-on'  
		}

		if(event == 'out'){
			newClass = 'item-off';  
		} 
		
		if(event == 'over'){
			newClass = 'item-over';
		}
	
	} else {
		if(event == 'on'){
			newClass = 'item-off'
		}
	}
	searchItem.className = newClass;	  
}

// Class Search. 
// Creates an new object when user click in a scroll element. 
// Collects the selected items in items array
// Methods to add, remove and find collected items

function Search(){
	this.items = new Array();
	this.itemID;
	this.itemName;
	
	this.AddX = AddX;
	this.RemoveX = RemoveX;
	this.FindX = FindX;

	function AddX(itemID, itemName) {
		x = {'id':itemID, 'name':itemName}
		this.items.push(x);
	}
	function RemoveX(){
		 this.items.splice(this.indexNum, 1);
	}
	
	function FindX(itemToFind) {
		this.indexNum;
		found = false;
		var i = 0;
		for (key in this.items){
			testID = this.items[key]['id'];
			if(testID == itemToFind){
		  		found = true;
				this.indexNum = i;
			}
		i++;  
		}
		return found;
	}
}

function clearCategory(category){
	if(state[category] != null){
		for(i=0;i<state[category].items.length;i++){
			for (key in state[category].items[i]){
				document.getElementById(category + '_' + state[category].items[i]['id']).className = 'item-off';
			}
		}
	
	state[category].items.length = 0;
	
	// LM - 2008.09.28
	updateAnalytics();
	
	showSearchInfo(category);
	
	if(countState() > 0){   
		parent.startAt = 0;
		parent.indexStart = 0;
		parent.pageNum = 1;
		parent.updateResult();
	} else {
		  parent.resetData();
	}		
		return true;
	}
	return false;
}

// Event handler
// Add items to object Search and to the global array state.
// Remove items if they already exists
function addCategory(category, iID, iName){
	
	
	if(state[category] == null){
		state[category] = new Search();
	}
	
	// Test if clicked item allready is active
	// IF true remove the item
	// If false add the item
	active = state[category].FindX(iID);
	switch(active) {
		case true:
			state[category].RemoveX();
			effect = 'item-off';
		break;
		case false:
	 		state[category].AddX(iID, iName);
			effect = 'item-on';
		break;
		default:
			state[category].RemoveX();
			effect = 'item-off';
			
	}
	
	// LM - 2008.09.28
	updateAnalytics();
	
	showSearchInfo(category);

	if(DEBUG){
	 	print_category(state[category].items);
	} else {
	   	
		if(countState() > 0){   
			parent.startAt = 0;
	   		parent.indexStart = 0;
	   		parent.pageNum = 1;
			parent.updateResult();
	 	} else {
			parent.resetData();
		}
	}
	var itemName =  category + '_' + iID;
	var scrollItem = document.getElementById(itemName);
	if(scrollItem){
		scrollItem.className = effect;
	}
	
}

/*======================================================================================
== Function to send a hit to Google Analytics, everytime a new Collection choice is made
====================================================================================== */
function updateAnalytics()
{
	//http://www.kvadrat.dk/textiles/collection/martindale/less 25.000/product/AF 96	
	//http://www.kvadrat.dk/textiles/collection/type/Curtains/colour/Light Blue/pattern/Organic/designer/Alexander Girard/fabric/Aqua 2/martindale/35000
	
	var uris = new Array();
	uris['type'] = '';
	uris['color'] = '';
	uris['pattern'] = '';
	uris['designer'] = '';
	uris['product'] = '';
	uris['martindale'] = '';
	
	for (key in state)
	{
		for(i=0; i<state[key].items.length; i++)
		{
			keyval = state[key].items[i]['name'];
			//keyval = keyval.replace(/\s/ig, '-');
			uris[key.toLowerCase()] += (i>0?',':'')+keyval;
		}
	}

	uri = '';
	for (key in uris)
	{
		keyname = (key=='product'?'fabric':key); // Hack: product is named fabric in Google Analytics
		if (uris[key] != '') uri += '/'+keyname+"/"+uris[key];
	}
	
	if (uri!='')
	{
		window.parent.analytics_state = '/textiles/collection'+uri;
		//debug: alert('/textiles/collection'+uri);
		window.parent.pageTracker._trackPageview('/textiles/collection'+uri);
	}
}


function countState() {
  counter = 0;
  for (key in state){
    if(state[key]['items'] != null){
		counter = counter + state[key]['items'].length;
	}
  }
  return counter;
}

// Initiates the scrolllayer with scrolling functionality on click
function dw_showLayers() {
  if ( document.getElementById ) {
    var lyr, i;
    for (i=0; arguments[i]; i++) {
      lyr = document.getElementById("scrollbar"+arguments[i]);
      if(lyr){
	    lyr.style.visibility = "visible";
	 }
    }
  }
}

function inArray(needle, haystack){
	found = false;
	for(i=0;i<haystack.length;i++){
		if(haystack[i] == needle){
		  found = true; 
		}
	}
	return found;
}

// Scrollbar with selected info
function showSearchInfo(category){
	var headlineInfo = document.getElementById(category);
	var infoString = '';
	var crop = scrollInfo_crop;
	var cropPostFix = scrollInfo_postfix;
	var splitChar = scrollInfo_split;
	var useOverlib = true;
	
	var infoArr = new Array();
	if(headlineInfo){

		for(i=0;i<state[category].items.length;i++){

			if(FLASHLABELS[category] && FLASHLABELS[category][state[category].items[i]['id']] != undefined){
		    	if(!inArray(FLASHLABELS[category][state[category].items[i]['id']], infoArr)){
					infoArr.push(FLASHLABELS[category][state[category].items[i]['id']]);
				}
			} else {
				if(!inArray(state[category].items[i]['name'], infoArr)){
					infoArr.push(state[category].items[i]['name']);
				}
			} 
		  
		}
		
		infoString = infoArr.join(splitChar);
		
		if(infoString.length <= crop) {
			cropPostFix = '';
		}
		
		infoString_cropped = infoString.slice(0, crop) + cropPostFix;
		
		if(useOverlib) {
			olString = infoArr.join('<br/>');
			infoString_cropped = '<div class="selectedInfo" onmouseover="return overlib(\'' + olString +'\', CAPTION, captionText);" onmouseout="return nd();">' + infoString_cropped + '</div>';
		} else {
			headlineInfo.title = infoString;  
		}
		
		headlineInfo.innerHTML = infoString_cropped;
		
	}
}

// Create swf-vars to send along
// Adds ability to remember selections even though flash file is removed when scroll layer closes
function collectSWFvars(category){
	swfVars = new Array();
	if(state[category] != undefined) {
		for(i=0;i<state[category].items.length;i++){
			swfVars.push(state[category].items[i]['id']);
		}
	}

	return swfVars;
}


function createFlashObj(elem_id){
	var so = new SWFObject(
							flashSelectors[elem_id]['flashFile'],
							"flash_" + flashSelectors[elem_id]['name'],
							flashSelectors[elem_id]['flashWidth'],
							flashSelectors[elem_id]['flashHeight'],
							flashSelectors[elem_id]['flashVersion'],
							flashSelectors[elem_id]['flashBG'],
							true);
	var flashParams = collectSWFvars(flashSelectors[elem_id]['name']);
	flashParams = "'" + flashParams.toString() + "'";
	so.addVariable(flashSelectors[elem_id]['swfVar'], flashParams);
	so.write("flash"+elem_id);
}

var xcount = 0;
var isOpen = '';
var openThis = '';
var keepOpen = false;

// Test if scrolltype is flash
function testScrollType(elem_id) {
	for(key in flashSelectors) {
		if(key == elem_id){
	  		return true; 
		}
	}
	return false;
}
// Expand or collapse the scrolling layer
function collapseMenu(elem_id){
	
	if(isOpen != elem_id){
		closeMenu(isOpen);
		openThis = elem_id;
		openMenu();
		isOpen = elem_id;
	} else {
	 	closeMenu(isOpen); 
	 	isOpen = '';
	}
	
	//If content of scrolling layer is flash object then create the object (use of SWFObject-lib)
	if(testScrollType(elem_id)){
  		createFlashObj(elem_id);
	}
}

var tmpFlash = new Array(2);
function closeMenu(closeId) {
	
	holder = document.getElementById("holder"+closeId);
	container = document.getElementById("container"+closeId);
	scrollbar = document.getElementById("scrollbar"+closeId);
	track = document.getElementById("track"+closeId);
	wn = document.getElementById("wn"+closeId);
	flashElement = document.getElementById("flash"+closeId);
	arrow = document.getElementById("arrow"+closeId);

	if(holder && container && scrollbar && track && wn) {
		holder.style.height = "0px";
		container.style.height = "0px";
		holder.style.borderBottom = "0";
		wn.style.height = "0px";
		wn.style.clip ="rect(0, 239px, 0, 0)"; 
		scrollbar.style.height = "0px";
		track.style.height = "0px";
	}
	
	if(flashElement && container){
		container.style.height = "0px";
		flashElement.style.display = 'none';
		flashElement.style.height = "0px";
	}
	
	if(arrow) {
	  arrow.src = 'fileadmin/templates/res/scrollbar/src/images/arrow_down.gif';
	}
 
	return 1;
	
}

function debug(command){
  if(DEV['IPMASK']){
	  eval(command);
  }
  return true;
}


// Open items 
// Animate open sequence
function openMenu(){
	var activeHeight = LAYER[openThis]['height'];
	
	holder = document.getElementById("holder"+openThis);
	holderBorder = document.getElementById("holder"+openThis);	
	container = document.getElementById("container"+openThis);
	scrollbar = document.getElementById("scrollbar"+openThis);
	track = document.getElementById("track"+openThis);
	wn = document.getElementById("wn"+openThis);
	flashElement = document.getElementById("flash"+openThis);
	arrow = document.getElementById("arrow"+openThis);

	if(xcount < activeHeight){
				
		xcount = (xcount + heightInterval);  
		if(xcount > activeHeight){
		 xcount = activeHeight;
		}
		
		window.setTimeout('openMenu()', speed);
		
		if(holder && container && scrollbar && track && wn) {
			holder.style.height = xcount+"px";
			container.style.height = xcount+"px";
			holder.style.borderBottom = "1px solid #D2CECC";
			wn.style.height = xcount+"px";
			wn.style.clip ="rect(0, 239px, " +xcount+"px, 0)"; 
			scrollbar.style.height = xcount+"px";
			track.style.height = xcount+"px";
		}
	
		if(flashElement && container){
			container.style.height = xcount+"px";
			flashElement.style.height = xcount+"px";
			flashElement.style.display = 'block';
		}
		
	} else {
		if(arrow) {
	  		arrow.src = 'fileadmin/templates/res/scrollbar/src/images/arrow_up.gif';
		}
		
		xcount = 0;
		return 1;

	}
	
}


