var tmenuPicPath;

function Trim(str) {
	var r=/\b(.*)\b/.exec(str);
	return (r==null)?"":r[1];
}


/* Sign-in box*/
// HD_Domain_HostName is the host name defined at Header page.

 

function show(object) {
	if (document.getElementById && (document.getElementById(object)!=null)) {
		document.getElementById(object).style.visibility = 'visible';
	}
	
	if (document.getElementById('formselect') != null){	
		document.getElementById('formselect').style.visibility="hidden";		
	}
}

function hide(object) {
//alert(object)
	if (document.getElementById && (document.getElementById(object)!=null)) {
		document.getElementById(object).style.visibility = 'hidden';
	}
	
	if (document.getElementById('formselect') != null){		
		document.getElementById('formselect').style.visibility="visible";		
	}
}

//login cookie setting code start
var expDate = new Date();
expDate.setTime(expDate.getTime()+365*24*60*60*1000); // one year

	function setCookie(isName,isValue,dExpires){      
		document.cookie = isName+"="+isValue+";expires="+dExpires.toGMTString();
	}

	function getCookie(isName){

		cookieStr = document.cookie;
		startSlice = cookieStr.indexOf(isName+"=");
		if (startSlice == -1){return false}
		endSlice = cookieStr.indexOf(";",startSlice+1)
		if (endSlice == -1){endSlice = cookieStr.length}
		isData = cookieStr.substring(startSlice,endSlice)
		isValue = isData.substring(isData.indexOf("=")+1,isData.length);
		return isValue;
	}

	function deleteCookie(isName){
   
		if (getCookie(isName)){document.cookie = isName + "="+ 
           		"; expires=Thu, 01-Jan-70 00:00:01 GMT";}
	}

function setCheck(obj) {
	var bCookie = getCookie('KeepEmail');
	var targetElement = document.getElementById("logonId");
	if (bCookie)
		 {
		  obj.firstChild.innerHTML = ""
		  deleteCookie('KeepEmail');
		 }
		 else
		 {
		  obj.firstChild.innerHTML = '<img src="'+tmenuPicPath+'checkmark.gif" alt="" border="0" style="margin-top: 2px; margin-left: 2px;">';
		  setCookie('KeepEmail',targetElement.value, expDate);
		 }
	obj.checked =!obj.checked;
}

function bsetCheck(name) {
	obj = document.getElementById(name);
	var bCookie = getCookie('KeepEmail');
	if (bCookie)
		 {
		  obj.firstChild.innerHTML = "";
		  deleteCookie('KeepEmail');
		 }
		 else
		 {
		  obj.firstChild.innerHTML = '<img src="'+tmenuPicPath+'checkmark.gif" alt="" border="0" style="margin-top: 2px; margin-left: 2px;">';
		  setCookie('KeepEmail',document.getElementById('logonId').value, expDate);
		  obj.checked=true;
		 }
	obj.checked =!obj.checked;
}

function getLoginID(){
  var loginID=getCookie('KeepEmail');
  if (loginID){
    obj=document.getElementById('cb');
    document.getElementById('logonId').value=getCookie('KeepEmail').toString();
    //check the checkbox
    obj=document.getElementById('cb');
    obj.firstChild.innerHTML = '<img src="'+tmenuPicPath+'checkmark.gif" alt="" border="0" style="margin-top: 2px; margin-left: 2px;">';
    //make sure that the clickable text is set to checked.
  }
}
  function GetCookie (name) {
  var arg = name + '=';                      
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
  var j = i + alen;
  if (document.cookie.substring(i, j) == arg)
    return getCookieVal (j);
  i = document.cookie.indexOf(' ', i) + 1;
  if (i == 0) break;
  }
  return null;
}

 function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (';', offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}


//login cookie setting code end


$(document).ready(function() {
	tmenuPicPath = HD_Domain_HostName + "/wcsstore/HomeDepotCanada/images/HDHeader/" + $('.storeWrapper').attr('lang') + "/";
	/* Global Header */
	// Top navigation
	$('#globalNav > li').hover(
		function() {
			$(this).addClass('hover');
			$('.subNav', this).show();
		},
		function() {
			$(this).removeClass('hover');
			$('.subNav', this).hide();
		}
	).find('.subNav').bgiframe();
	
	$('#searchAndBreadcrumbsArea').hover(
		function() {
			$('#globalNav .subNav').hide();
			$('#globalNav > li').removeClass('hover');
		},
		function() {

		}
	);
	
	if ($('#pageTitle h1').height() > 68) {
		$('#pageTitle h1').addClass('small');
		if ($('#pageTitle h1').height() > 68) {
			var text = $.trim($('#pageTitle h1').text());
			if (text.length > 50) {
				$('#pageTitle h1').text(text.substring(0, 50) + '...');
			}
		}
	}
	$('#pageTitle h1').css('padding-top', Math.floor((75 - $('#pageTitle h1').height()) / 2));
	
	//Sign-in box
	$('#signIn .btnSignIn').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	initEmailRegForm();
	
});



function initEmailRegForm() {
	$('form[name=addEmailReg]').submit(function() {
		var storeId = $('.storeWrapper').attr('storeId');
		var catalogId = $('.storeWrapper').attr('catalogId');
		var langId = $('.storeWrapper').attr('langId');
		
		var emailAddress = $('input[name=emailAddress]', this).val();
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if (filter.test(emailAddress)) {
			var url = HD_Domain_HostName + '/webapp/wcs/stores/servlet/EmailRegPopup?storeId=' + storeId + '&catalogId=' + catalogId + '&langId=' + langId;
			openFeatureFlex(url, 'security', '620', '400', true, true, false, false, false, false);
			$('input[name=URL]', this).val(location.href);	
		} else {
			var msg = 'Please enter a valid email address.';
			if ($('.storeWrapper').attr('lang') == 'fr_CA') {
				msg = 'Veuillez inscrire une adresse courriel valide.';
			}
			alert(msg);
			return false;
		}
	});
}


function ConstructURL(oldQueryString,removeterms,addterms) {

	var newQueryString = "";
	if(oldQueryString!=""){
		var params = BuildURLArray(oldQueryString);
		for (var i=0; i<params.length; i++) {
			var isRemovingTerm = CheckArray(removeterms,params[i][0]);
			if (isRemovingTerm == false)
				newQueryString += "&" + params[i][0] + "=" + params[i][1];
		}
	}
	
	for (var i=0; i<addterms.length; i++) {
		newQueryString += "&" + addterms[i];
	}

	return  newQueryString.substr(1);		
}

function BuildURLArray(sQueryString) {
	var returnArray = new Array();
	var params = sQueryString.split("&");
	for (var i=0; i<params.length; i++) {
		var param = params[i].split("=");
		returnArray[i] = param;
	}
	return returnArray;
}
 
function CheckArray(removeterms,checkterm) {
	for (var i=0; i<removeterms.length; i++) {
		if (removeterms[i] == checkterm)
			return true;
	}
	return false;
}

function GetValue(url, term) {
	var pos = url.indexOf('?');
	if(pos>0){
		url = url.substring(pos+1); 
	}
	if(url!=""){
		var params = BuildURLArray(url);
		for (var i=0; i<params.length; i++) {
			if (params[i][0] == term) {
				return params[i][1];
			}
		}
	}
	return -1;
}

var SuperHero = function(container) {
	var self = this;
	var timer = null;
	this.panels = new Array();
	this.currentIndex = 0;
	var flashPlayerVersion = swfobject.getFlashPlayerVersion();
	this.hasFlash = (flashPlayerVersion && flashPlayerVersion.major >= 8 ? true : false);

	this.init = function() {
		$('.panel', container).each(function(i) {
			var duration = Number($(this).attr('data-duration'));
			var imgDuration = Number($(this).attr('data-img-duration'));
			var swfDuration = Number($(this).attr('data-swf-duration'));
			var imgSrc = $(this).attr('data-img');
			var swfSrc = $(this).attr('data-swf');
			var type = 'image';
			var altText = $('a', this).text();
			var date = new Date();
			var id = 'hero' + i + date.getTime();
			$('a', this).attr('id', id).html('<img src="' + imgSrc + '" width="378" height="302" border="0" alt="' + altText + '" />');
			if (swfSrc) {
				if (self.hasFlash) {
					type = 'flash';
					var flashvars = {};
					var autoplay = (i == 0 ? 'true' : 'false' );
					var params = {wmode: 'opaque', play: autoplay, allowScriptAccess: 'always'};
					var attributes = {id: id, name: id};
					swfobject.embedSWF(swfSrc, id, '378', '302', '9', '', flashvars, params, attributes);
					duration = swfDuration;
				} else {
					duration = imgDuration;
				}
			}
			self.panels.push({elem: this, duration: duration, type: type, id: id});
		}).eq(0).addClass('show');
		
		self.buildControls();
		self.play();
		container.removeClass('loading');
	}
	
	this.buildControls = function() {
		var controls = $('<div class="controls"><a class="button btnPause" href="#">Play/Pause</a><div class="pagination"></div></div>');
		for (var i = 0; i < self.panels.length; i++) {
			$('<a href="#">' + (i+1) + '</a>').appendTo($('.pagination', controls));
		}
		$('.pagination a', controls).eq(0).addClass('selected');
		
		
		$('.button', controls).click(function() {
			if ($(this).hasClass('btnPlay')) {
				self.play();
			}
			else if ($(this).hasClass('btnPause')) {
				self.pause();
			}
			return false;
		});
		
		$('.pagination a', controls).click(function() {
			var index = Number($(this).text()) - 1;
			self.pause();
			self.gotoIndex(index);
			return false;
		});
		
		container.append(controls);
	}
	
	

	this.next = function() {
		var nextIndex = self.currentIndex + 1;
		if (self.currentIndex == (self.panels.length - 1)) nextIndex = 0;
		self.gotoIndex(nextIndex);
		var duration = self.panels[nextIndex].duration * 1000;
		self.timer = setTimeout(self.next, duration);
	}
	
	this.gotoIndex = function(nextIndex) {
		if (self.currentIndex == nextIndex) return false;
		
		var currentPanel = self.panels[self.currentIndex ].elem;
		var nextPanel = self.panels[nextIndex].elem;
		
		if (self.panels[self.currentIndex].type == 'flash') {
			var id = self.panels[self.currentIndex].id;
			document.getElementById(id).StopPlay();
			document.getElementById(id).Rewind();
		}
		$(currentPanel).fadeOut().removeClass('show');
		$(nextPanel).fadeIn(500, function() {
			$(this).addClass('show');
			if (self.panels[nextIndex].type == 'flash') {
				var id = self.panels[nextIndex].id;	
				document.getElementById(id).Play();
			}
		});
		self.currentIndex = nextIndex;
		
		$('.pagination a', container).removeClass('selected').eq(nextIndex).addClass('selected');
	}
	
	this.play = function() {
		var currentPanel = self.panels[self.currentIndex];
		var duration = currentPanel.duration * 1000;
		self.timer = setTimeout(self.next, duration);
		$('.controls .button', container).removeClass('btnPlay').addClass('btnPause');
	}
	
	this.pause = function() { 
		clearTimeout(self.timer);
		$('.controls .button', container).removeClass('btnPause').addClass('btnPlay');
	}
	
	this.init();
}