/***************************************************************************************************
* This file holds all of the sites scripts that effect a lot of pages.
***************************************************************************************************/

/*
Global variables
*/
var rootPath = '';
//var Cookie = new clsCookie();


/*
	Add a zoom icon to an image with a class of addZoom.
	Please note that this file is dependant on prototype.js.  Please make sure that prototype.js and scriptaculous.js are included before this file is included.
*/
function addZoomIcon(positionX, positionY){   		
	var elements =  $$('.addZoom');
	for(var i = 0; i < elements.length; i++)
	{
		elements[i].insert({ after: new  Element('img', {
												  src: 'images/glass.png',
												  style:'position:absolute; display:inline; bottom: ' + positionX + '; left: ' +positionY + ';  border: 0;'
										 })
							   });		
	}
}

/*
	Return a value from the query string
*/
function  getValueFromQueryString(strTarget) {
	var QS = window.location.search.substring(1, window.location.search.length);
	var qsPairs = QS.split("&");
	
	var key, item, splitIndex;
		
	for(var i = 0; i < qsPairs.length; i++) {
		splitIndex = qsPairs[i].indexOf("=");
		key = qsPairs[i].substring(0, splitIndex);
		item = qsPairs[i].substring(splitIndex + 1, qsPairs[i].length);
	    if(strTarget == key)		
			return  item;
	}
	
	return '';
}

/*
	This function pops up a product snapshot window.  
*/
function getProductSnapshot(elem)
{
	var arrInfo = elem.id.split("-");
	
	var url = 'ajax/product/getProductInfoLite.asp';
	new Ajax.Request(url, {
		method: 'get',
		parameters: {
			cat_id: arrInfo[1],
			sku: arrInfo[0]
		},		
		onSuccess: function(transport){		
			//transport..evalScripts();
			if(!$('product-window')){
				$('body_content').insert({bottom: new Element('div', {id: 'product-window', style:'position:absolute; display:none; zIndex:100;'})});
			}						
			$('product-window').innerHTML = transport.responseText;
			
			//We have to do this because CTG is coded so poorly that even prototype can't help us.  Adding a doctype will correct this but it breaks to many pages.
			if(document.viewport.getWidth() == 0)
				var height =  500  - ($('product-window').getWidth() / 2) + 'px';
			else
				var height = (document.viewport.getWidth() / 2) - ($('product-window').getWidth() / 2) + 'px';
				
			$('product-window').setStyle({
				left: height,
				top: 150 + $('product-window').cumulativeScrollOffset()[1] + 'px'
			});
			
			$('product-window-hud').observe('mousedown', function(event){
				var drag = new Draggable('product-window',{
														   onEnd: function(){drag.destroy()},
														   starteffect:null,
														   endeffect:null,
														   scroll: window
										 });
				drag.initDrag(event);
			});
						   
			$('product-window').show();
			
			$('product-window-close').observe('click', function(event){
												event.stop();
												$('product-window').hide();
											  });
			
		}//end onSucess: function(transport)
	});
   return false;
}

/*
	Set up product snapshot trigger event.  Look for elements that have a class of product-snapshot
*/
function  setupProductSnapshot(){
    var elements = $$('.product-snapshot');
	
    for(var i = 0; i < elements.length; i++){
	
	elements[i].observe('mouseover', function(event){
				if( $(this.identify() + '-overlay') == null){
					this.setStyle({border: 'solid 1px black'});
					var rolloverElem = new Element('div', {id:this.identify() + '-overlay'});
					rolloverElem.setStyle({
								position: 'absolute',
								top:'0px',
								left:'0px',
								backgroundColor:'Black',
								 display: 'block',
								width:'160px',
								textAlign: 'center',
								color: 'white',
								paddingTop: '5px',
								paddingBottom: '5px',
								cursor: 'hand',
								cursor: 'pointer',
								fontWeight: 'bold'
								});
								
					this.setStyle({
						cursor: 'hand',
						cursor: 'pointer'
						});
					
								
					rolloverElem.update('Quick View');
					rolloverElem.setOpacity(0.25);
					this.insert({top: rolloverElem});
					
					rolloverElem.observe('click', function(event){
		                                        event.stop();
		                                        getProductSnapshot(this);
		                                        }.bind(elements[i]));					 
				}
			}.bind(elements[i]));


	elements[i].observe('mouseout', function(event){
				 if(fixOnMouseOut(this, event)){
				  this.setStyle({border: 'solid 1px white'});
				  $(this.identify() + '-overlay').remove();
				}
			}.bind(elements[i]));

    }
}

function bubbledEvent(element, parent){

    var elems = parent.descendants();
    boolReturn = false; 
    for(var j=0; j<elems.length; j++)
    {
        if(element == elems[j])
            boolReturn = true;
    }
    return boolReturn;
}


/*********************************************************************
 * No onMouseOut event if the mouse pointer hovers a child element 
 * *** Please do not remove this header. ***
 * This code is working on my IE7, IE6, FireFox, Opera and Safari
 * 
 * Usage: 
 * <div onMouseOut="fixOnMouseOut(this, event, 'JavaScript Code');"> 
 *		So many children
 *	</div>
 *
 * @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com		
**/
function is_child_of(parent, child) {
	if( child != null ) {			
		while( child.parentNode ) {
			if( (child = child.parentNode) == parent ) {
				return true;
			}
		}
	}
	return false;
}

function fixOnMouseOut(element, event) {
	var current_mouse_target = null;
	if( event.toElement ) {				
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {				
		current_mouse_target 			 = event.relatedTarget;
	}
	if( !is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
		return true;
	}
	return false;
}


/*
    Utility function.  This takes a radio/select and returns which selection was made.
    Please note that this returns an HTML element.
*/

function getSelectedRadioButton(radioButton) {   
    for(var i=0; i < radioButton.length; i++)
    {
        if(radioButton[i].checked || radioButton[i].selected)
           return radioButton[i];
    }    
}

/*
	Returns how many folders deep we are away from the root.
*/
function resolveURLPath(){
	var URL = document.location.pathname.split('/');
	var returnVal = '';
	
	if (URL.length > 3){
		for(var i = 2; i < URL.length  - 1 ; i++){
			returnVal = returnVal + URL[i] + '/';
			}
	}
	
	if(returnVal.length == 0)
		return 0;
	else
		var tempArr = returnVal.substring(0, returnVal.length - 1).split('/');
	
	return  tempArr.length;
}

var leftnavAjaxCache = $A();
var t;

function valueSet(element) {
	var elem = $(element);
	var defValue = $F(elem);
	if (elem) {
		elem.observe('focus', function(event) {
			event.stop();
			if ($F(elem) == defValue) {
				elem.clear();
			}
		});
		elem.observe('blur', function(event) {
			event.stop();
			if ($F(elem) == "") {
				elem.value = defValue;
			}	
		});
	}
}

// Execute some code once the dom has loaded.
document.observe("dom:loaded", function() {
										
	valueSet('quick_search_box');

	$$('input[type=text]').each(function(elem) {
		elem.observe('focus', function(event) {
			event.stop();
			elem.activate();
		});
	});
	
	$$('.hover').each(function(elem) {
		elem.observe('mouseover', function(event) {
			event.stop();
			elem.src = elem.src.replace('.gif', '_hover.gif');
		});
		elem.observe('mouseout', function(event) {
			event.stop();
			elem.src = elem.src.replace('_hover', '');
		});
	});

	//Add zoom icons to pictures
	addZoomIcon('5px', '5px');
	
	//Set up left nav category menus
	var categoryAnchorTemplate = new Template('<li><a href="http://'+ document.domain +'/categories.asp?cat_id=#{dept_id}">#{dept_name}</a></li>');			

	$$('.leftNav li a').each(function(elem) {
		elem.observe('mouseover', function(event) {			
			event.stop();
			clearTimeout(t);
			t = setTimeout(function() {
				hideSubcats(); 				
				var params = $H(elem.href.toString().toQueryParams());			
				if (params.get('cat_id') && params.get('cat_id') != 1600 && params.get('cat_id') != 7000){
					$$('.leftNav li a').each(function(elem) {						
						if (this != elem) { 
							elem.setStyle({background:'', color:''}); 
						} else {						
							this.setStyle({backgroundColor:elem.getStyle('background-color'), color:elem.getStyle('color')});
						}
					}.bind(elem));
					if (!leftnavAjaxCache[params.toQueryString()]) {	
						new Ajax.Request('/ajax/json/getCategories.asp', {
							method: 'post',
							parameters: params,
							onSuccess: function(transport, json) {
								var strTemp = '';								
								json.each(function(elem) {
									strTemp += categoryAnchorTemplate.evaluate(elem);									
								});							
								leftnavAjaxCache[params.toQueryString()] = strTemp;
								drawSubCats(elem, leftnavAjaxCache[params.toQueryString()]);
							}
						});								
					} else {
							drawSubCats(elem, leftnavAjaxCache[params.toQueryString()]);
					}
				} else { hideSubcats(); }
			}, 100);	
		});
		elem.observe('mouseout', function(event) {
			event.stop();
			clearTimeout(t);
			t = hideSubcats.delay(0.1);
		});
	});

	
	/*See if we need to display the NPS survey
	var displaySurvey = false;
	Cookie.setCookieName("cablestogo-temp");
	if(!Cookie.get("cablestogo-temp", "survey") || !Cookie.get("cablestogo-temp", "orders")){
		new Ajax.Request('/ajax/global/getDisplayGlobalNPSSurvey.asp', {
			method: 'get',
			parameters: {id: Cookie.get("cablestogo-temp", "ShopperID")},
			onSuccess: function(transport, json){
				Cookie.set('cablestogo-temp', 'orders', json.orders);
				Cookie.set('cablestogo-temp', 'survey', json.survey);
			}
		});	
	} else {
		alert('cookie found');
	}
	*/
});

function drawSubCats(elem, subCats) {
	if (!$('leftNavSubCat')) {
		var leftNavSubCatDivShadow1 = $(Builder.node('div', {'id': 'leftNavSubCatShadow1'}));
		leftNavSubCatDivShadow1.setStyle({background:'#333', padding:'0px'});
		leftNavSubCatDivShadow1.setOpacity(0.2);
		var leftNavSubCatDivShadow2 = $(Builder.node('div', {'id': 'leftNavSubCatShadow2'}));
		leftNavSubCatDivShadow2.setStyle({background:'#333', padding:'0px'});
		leftNavSubCatDivShadow2.setOpacity(0.2);
		var leftNavSubCatDivShadow3 = $(Builder.node('div', {'id': 'leftNavSubCatShadow3'}));
		leftNavSubCatDivShadow3.setStyle({background:'#333', padding:'0px'});
		leftNavSubCatDivShadow3.setOpacity(0.2);
		var leftNavSubCatDiv = $(Builder.node('ul', {'class':'leftNav', 'id': 'leftNavSubCat'}));
		leftNavSubCatDiv.observe('mouseover', function(event) {
			event.stop();
			clearTimeout(t);
		});
		leftNavSubCatDiv.observe('mouseout', function(event) {	
			event.stop();
			clearTimeout(t);
			t = hideSubcats.delay(0.5);
		});
		$('outerWrapper').insert({bottom: leftNavSubCatDivShadow1.hide()});
		$('outerWrapper').insert({bottom: leftNavSubCatDivShadow2.hide()});
		$('outerWrapper').insert({bottom: leftNavSubCatDivShadow3.hide()});
		$('outerWrapper').insert({bottom: leftNavSubCatDiv.hide()});
	}
	$('leftNavSubCat').update(subCats);
	$$('#leftNavSubCat li').each(function(elem) {				
		elem.observe('mouseover', function(event) {
			$$('#leftNavSubCat li').each(function(elem) {
				elem.setStyle({backgroundColor:'', color:''}); 
			});		
			elem.setStyle({backgroundColor:'#EEE', color:'#000'}); 			
		});
		elem.observe('mouseout', function(event) {	
			elem.setStyle({backgroundColor:'', color:''}); 
		});
	});
	var offsetTop = -1;
	if (document.viewport.getHeight() - elem.viewportOffset()[1] < $('leftNavSubCat').getHeight())
		offsetTop -= $('leftNavSubCat').getHeight() - elem.getHeight();
	$('leftNavSubCat').absolutize().clonePosition(elem, {setHeight:false, offsetLeft:160, offsetTop:offsetTop});
	$('leftNavSubCat').setStyle({height:'', width:''}).show();
	$('leftNavSubCatShadow1').absolutize().clonePosition($('leftNavSubCat'), {offsetLeft:1, offsetTop:1}).show();
	$('leftNavSubCatShadow2').absolutize().clonePosition($('leftNavSubCat'), {offsetLeft:2, offsetTop:2}).show();
	$('leftNavSubCatShadow3').absolutize().clonePosition($('leftNavSubCat'), {offsetLeft:3, offsetTop:3}).show();
}

function hideSubcats() {
	try {
		elem = $('leftNavSubCatShadow1')
		if (elem) { elem.hide(); }
		elem = $('leftNavSubCatShadow2')
		if (elem) { elem.hide(); }
		elem = $('leftNavSubCatShadow3')
		if (elem) { elem.hide(); }
		elem = $('leftNavSubCat')
		if (elem) { elem.hide(); }
		$$('.leftNav li a').each(function(elem) {	
			elem.setStyle({backgroundColor:'', color:''}); 
		});
	} catch(e) {}
}

/***************************************************************************************************
* Search pages CoreMetrics tagging code - Initialization
***************************************************************************************************/
var baseURL = 'http://www.cablestogo.com/';
var searchHost = 'search.cablestogo.com';
if (location.host == searchHost) {
	if (typeof(_cm)=='undefined'){document.write('<script type="text/javascript" src="'+baseURL+'/Coremetrics/v40/eluminate.js"></script>');}
	if (typeof(cmCreatePageviewTag)=='undefined'){document.write('<script type="text/javascript" src="'+baseURL+'/Coremetrics/cmdatatagutils.js"></script>');}
	document.write('<script type="text/javascript" src="'+baseURL+'/js_storage/cmsearch.js"></script>');
}