
function setFocus()
{
  try
  {
    //ordertixWin
    if(ordertixWin != null) {
      if(ordertixWin.closed == false) {
        ordertixWin.focus();
      }
    }  	

    //infoWin
    if(infoWin != null) {
      if(infoWin.closed == false) {
        infoWin.focus();
      }
    }  	
  }
  catch (err)
  {
  }

}
window.onfocus=setFocus;



function gotoAction(path) {
  window.location.href=path;
}



var ordertixWin = null;
function openOrderTix(page) {
	var w = screen.width - 10 ;
	var h = screen.height - 80;
	winprops = 'left=0,top=0,height='+h+',width='+w+',toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes';
  winname = "OrderTix"
	if(ordertixWin != null) {
		if(ordertixWin.closed == true) {
			ordertixWin = window.open(page, winname, winprops);
		} 
    else {
			ordertixWin = window.open(page, winname, winprops);
		}
	} 
  else {
		ordertixWin = window.open(page, winname, winprops);
	}
  ordertixWin.focus();
}


var infoWin = null;
function openInfoWindow(page, width, height) {
	var w = width;
	var h = height;
	winprops = 'left=0,top=0,height='+h+',width='+w+',toolbar=yes,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes';
  winname = "InfoWin"
	if(infoWin != null) {
		if(infoWin.closed == true) {
			infoWin = window.open(page, winname, winprops);
		} 
    else {
			infoWin = window.open(page, winname, winprops);
		}
	} 
  else {
		infoWin = window.open(page, winname, winprops);
	}
  //infoWin.resizeTo(width,height);
  infoWin.focus();
}

var micrositeWin = null;
function openMicrosite( pageURL) {
	//var w = width;
	//var h = height;
	winprops = 'left=0,top=0,height=600,width=800,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes';
    winname = "micrositeWin"
    page = "http://remote.sight-sound.com/StaticContent/joseph"
    if(pageURL != null){
    	page = pageURL;
    }
	if(micrositeWin != null) {
		if(micrositeWin.closed == true) {
			micrositeWin = window.open(page, winname, winprops);
		} 
    else {
			micrositeWin = window.open(page, winname, winprops);
		}
	} 
  else {
		micrositeWin = window.open(page, winname, winprops);
	}
  //infoWin.resizeTo(width,height);
  micrositeWin.focus();
}


function printWindow(){
	if (window.print == null ) {
		alert("Your browser does not support this function. Please press CTRL+P to print the page");
	}
	else {
		window.focus();
		window.print();
	}
}
function documentOnKeyDown()
{
	//Kill any event caused by pressing the enter key.
	if(event.keyCode == 13) {
		event.cancelBubble = true;
		return(false);
	}
}
window.document.attachEvent("onkeydown",documentOnKeyDown);


var startDate = new Date();
var startTime = startDate.getTime();
var downloadTime = 0;
var id;
function findLoadTime() {
  var tempImg = new Image();
  tempImg.src = "/WebSiteSS/100.jpg";
  if(tempImg.complete) {
    var endDate = new Date();
    var endTime = endDate.getTime();
    downloadTime = (endTime - startTime);
    //if it is more than 2000 milliseconds, then it is dial-up
    //DSL or Cable will have minimum 100KB per secound.
    if(downloadTime > 2000) {
      document.forms[0].highSpeed.value = 'false';
    }
    clearTimeout(id);

  }
  else {
    id = setTimeout("findLoadTime();",500);
  }
}



var cal_open_date_place;
function cal_open(objFormItem)
{
	var urlstring = '/WebSiteSS/ordertix/javascript/calendar.htm'
	var top = screen.height/2;
	var left = screen.width/2;
	modalWindow = window.open(urlstring,'','top=' + top + ',left=' + left + ',height=200,width=225,toolbar=no,minimize=no,status=no,memubar=no,location=no,scrollbars=no')
	//Assign variable to global,
	//This global will get polled once newWindow is done loading
	cal_open_date_place = objFormItem;
}

var seatingTimer;
var timerText;
var oldStartTime;
function runSeatingTimer() {
	var now = new Date();
	var elapsedMilliSecs = now.getTime()-oldStartTime;
	var elapsedMins = Math.round(elapsedMilliSecs / (1000*60));
	var minsLeft = (15 - elapsedMins);
	if(elapsedMins > 0 && elapsedMins <= 15 && minsLeft <= 0) {
		var str = "";
		str += "As you have exceeded 15 minutes for your reservation, your seats have been released and your order has been cancelled.\n";
		str += "Please re-start your order.  If you need assistance, please contact the Sight & Sound Contact Center."
		alert(str);
		gotoAction("/WebSiteSS/ordertix/cancelOrderTicketsAct.do");
	} else {
		timerText.nodeValue = "" + minsLeft + "";
		seatingTimer = setTimeout(runSeatingTimer,60000);
	}
}
function startSeatingTimer(startTime) {
//alert("entering startSeatingTimer");
	timerText = document.getElementById("SEATING_TIMER").firstChild;
//alert("timerText: "+timerText);
	oldStartTime = startTime;
	if(typeof(timerText) != "undefined"){
		runSeatingTimer();	
	}
}

function stopSeatingTimer() {
	if(seatingTimer != "undefined") {
		clearTimeout(seatingTimer);
	}
}

//AJAX functions
function GetXmlHttpObject()
{ 
  var objXMLHttp=null
  if (window.XMLHttpRequest)
  {
    objXMLHttp=new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
} 

var xmlHttp;
function getCityState(txtZipCode)
{
  //zip code lookup is available only for USA or CAN
  objForm = txtZipCode.form;
  if(!(objForm.countryCD.options[objForm.countryCD.selectedIndex].value == "USA" || objForm.countryCD.options[objForm.countryCD.selectedIndex].value == "CAN") ) {
    return(false);
  }

  var strZipCode = txtZipCode.value;
  if (strZipCode.length==0)
  {
    document.getElementById("cityState").innerHTML="";
    return;
  }
  
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
  	// browser does not support AJAX: do it the old fashioned way
  	this.form.LOOKUP.value = 'YES';
  	this.form.submit();
    return;
  }
  var url="/WebSiteSS/servlets/citystateservlet";
  url=url+"?zipCode="+strZipCode;
  url=url+"&sid="+Math.random();

  xmlHttp.onreadystatechange=populateCityState;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function populateCityState()
{
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {
    var zscColl = eval('(' + xmlHttp.responseText + ')').zipCityStateCollection;
    cityStateCount = zscColl.length;
    
    var str = "<table width='100%' border='1' cellspacing='0' cellpadding='3' bgcolor='#ffffff'>";
        str += "<tr><th colspan='4'><b>Select your city state combination</b></td></tr>";
        str += "<tr>";
        str += "<th style='text-align:center'>Select</th>";
        str += "<th style='text-align:center'>City</th>";
        str += "<th style='text-align:center'>State</th>";
        str += "<th style='text-align:center'>Country</th>";
        str += "</tr>";
    
    for (var i=0;i<zscColl.length;i++)
    {
        str += "<tr>";
        str += "<td style='text-align:center'>";
        str += "<input type='radio' name='cityStateSelect' value='"+i+"'class='formelement' onclick='copyValues(this); resetCityState();'>";
        str += "<input type='hidden' name='lookupZipCode' value='"+zscColl[i].zipcode+"' >";
        str += "</td>";
        str += "<td style='text-align:center'>";
        str += "<input type='hidden' name='lookupCity' value='"+zscColl[i].city+"' >";
        str += zscColl[i].city;
        str += "</td>";
        str += "<td style='text-align:center'>";
        str += "<input type='hidden' name='lookupStateProvince' value='"+zscColl[i].stateProvinceName+"' >";
        str += "<input type='hidden' name='lookupStateProvinceCode' value='"+zscColl[i].stateProvinceCD+"' >";
        str += zscColl[i].stateProvinceName;
        str += "</td>";
        str += "<td style='text-align:center'>";
        str += "<input type='hidden' name='lookupCountryCode' value='"+zscColl[i].countryCD+"' >";
        str += zscColl[i].countryCD;
        str += "</td>";
        str += "</tr>";
    }
    str += "</table>";

    document.getElementById("cityState").innerHTML=str;
  } 
}

function resetCityState() {
    cityStateCount = 0;
	document.getElementById("cityState").innerHTML="";
}

function activateSession()
{
  //alert("inside activateSession");

  
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
    alert ("Browser does not support HTTP Request");
    return;
  } 
  var url="/WebSiteSS/servlets/activatesession";
//alert(url);
  xmlHttp.onreadystatechange=sessionActivated ;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
} 

var activateSessionId;
function sessionActivated(){
	//alert("Session Activated");
  clearTimeout(activateSessionId);
  genericTimer(600000,'activateSession()');
}

function genericTimer(interval, functionToExecute) {
    activateSessionId = setTimeout(functionToExecute,interval);
}

function validateDateString(str) {
	var dateFormat = /^(\d{1,2}\/\d{1,2}\/\d{4})$/;
	if(dateFormat.test(str)) {
		return true;
	} else {
		alert("Dates must be in the format \"mm/dd/yyyy\".");
		return false;
	}
}

function parseDate(str) {
	var fieldArray = str.split("/");
	return new Date(fieldArray[2],fieldArray[0]-1,fieldArray[1]);
}

function validateHotelDates(strCheckin,strCheckout) {
	if(! (validateDateString(strCheckin) && validateDateString(strCheckout)) ) {
		return false;
	}
	
	if(parseDate(strCheckin) < parseDate(strCheckout)) {
		return true;
	} else {
		alert("Check-in date must be before check-out date.");
		return false;
	}
}

//format to mm/dd/yyyy 
function formatDate(objDate) {
  var strDate = objDate.value.toString();
  if (strDate.length == 8) {
    objDate.value = strDate.substring(0,2) + "/" + strDate.substring(2,4)+ "/" + strDate.substring(4,8);
  }
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}


//get employee info
function getEmployeeInfo(objForm)
{
 var strEmpFirstName = '';
 var strEmpLastName = objForm.lastName.value;

  if (strEmpLastName.length==0)
  {
    return;
  }
  
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
  	// browser does not support AJAX: do not do anything
    return;
  }
  var url="/WebSiteSS/servlets/employeeinfoservlet";
  url=url+"?empFirstName="+strEmpFirstName+"&empLastName="+strEmpLastName;
  xmlHttp.onreadystatechange=populateEmployeeInfo;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function populateEmployeeInfo()
{
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
  	if(xmlHttp.responseText =="" ){
	  alert("Sorry, this Employee not found in database");
	}else {
    var empColl = eval('(' + xmlHttp.responseText + ')').employeeCollection;
    var str = "<table width='100%' border='1' cellspacing='0' cellpadding='3' bgcolor='#ffffff'>";
        str += "<tr><th colspan='4' style='text-align:center'><b>Select your Name</b></td></tr>";
        str += "<tr>";
        str += "<th style='text-align:center'>Select</th>";
        str += "<th style='text-align:center'>First Name</th>";
        str += "<th style='text-align:center'>Last Name</th>";
        str += "<th style='text-align:center'>Department Name</th>";
        str += "</tr>";
	    for (var i=0;i<empColl.length;i++) {
	        str += "<tr>";
	        str += "<td style='text-align:center'>";
	        str += "<input type='radio' name='empNo' value='"+empColl[i].empNo+"'class='formelement' onclick='copyEmployeeValues(this.form); resetEmployee();'>";
	        str += "</td>";
	        str += "<td style='text-align:center'>";
	        str += "<input type='hidden' name='empFirstName' value='"+empColl[i].empFirstName+"' >";
	        str += empColl[i].empFirstName;
	        str += "</td>";
	        str += "<td style='text-align:center'>";
	        str += "<input type='hidden' name='empLastName' value='"+empColl[i].empLastName+"' >";
	        str += empColl[i].empLastName;
	        str += "</td>";
	        str += "<td style='text-align:center'>";
	        str += "<input type='hidden' name='empSupervisorNumber' value='"+empColl[i].empSupervisorNumber+"' >";
	        str += empColl[i].deptName;
	        str += "</td>";
	        str += "</tr>";
	    }
    str += "</table>";

    document.getElementById("employeeList").innerHTML=str;
    }
  } 
}

//this function copies the employee values to appropriate fields.
function copyEmployeeValues(objForm) {
//when the no. of employee is 1, fields are accessed directly.
//Otherwise, appropriate index is used.
	if (typeof(objForm.empNo.length) == "undefined") {
		if( objForm.empNo.checked == true){		    
		    objForm.firstName.value = objForm.empFirstName.value;
		    objForm.lastName.value = objForm.empLastName.value;    
		    objForm.employeeNo.value = objForm.empNo.value;
			objForm.employeeSupervisorNo.value = objForm.empSupervisorNumber.value;
		}   
    } else {
		for(k=0; k < objForm.empNo.length; k++){ 
	  		if( objForm.empNo[k].checked == true){  
			    objForm.firstName.value = objForm.empFirstName[k].value;
			    objForm.lastName.value = objForm.empLastName[k].value;    
			    objForm.employeeNo.value = objForm.empNo[k].value;
				objForm.employeeSupervisorNo.value = objForm.empSupervisorNumber[k].value;      
			    break; 					
	  		}
  		}	
    }
}

function resetEmployee() {
	document.getElementById("employeeList").innerHTML="";
}

function writePageTitle(pageTitle, helpPageId) {
	document.getElementById("pageTitle").innerHTML=pageTitle;

	if(helpPageId > 0){
		var str = "<a class=\"helpLink\" href=\"javascript:openInfoWindow('/WebSiteSS/getpage.do?id="+helpPageId+"','600','500')\" >Help</a>";		
	    document.getElementById("pageHelp").innerHTML=str;		
	}	
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function checkEventDate(showDateTime, currentDateTime) {
	var objShowDate = new Date(parseInt(showDateTime));
	var objCurrentDate = new Date(parseInt(currentDateTime));	

	if(objShowDate < objCurrentDate) {
		if(confirm("Event occurs in the past, do you still wish to add it to the order?")) {
			return(true);
		} else {
			return(false);
		}
	}
	return(true);
}

function check(field) {
	if (checkflag == "false") {
		for (i = 0; i < field.length; i++) {
			if(field[i].disabled == false) {
				field[i].checked = true;
			}
		}
		checkflag = "true";
		return "Uncheck All";
	} else {
		for (i = 0; i < field.length; i++) {
			if(field[i].disabled == false) {
				field[i].checked = false;
			}
		}
	checkflag = "false";
	return "Check All"; }
}
function parseIntNull(strValue)
{
	if(strValue == null) {
		return(0);
	} else {
		if(strValue.length == 0) {
			return(0);
		} else {
			return(parseInt(strValue));
		}
	}
}
function  validateNumeric( strValue ) {
	/******************************************************************************
	DESCRIPTION: Validates that a string contains only valid numbers.

	PARAMETERS:
	   strValue - String to be tested for validity

	RETURNS:
	   True if valid, otherwise false.
	******************************************************************************/
	  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

	  //check for numeric characters
	  return objRegExp.test(strValue);
}

function validatePhone(strPhone){
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
function getSelected(opt)
{
	var selected = new Array();
	var index = 0;

	for (var intLoop=0; intLoop < opt.length; intLoop++)
	{
		if (opt[intLoop].selected)
		{
			index = selected.length;
			selected[index] = new Object;
			selected[index].value = opt[intLoop].value;
			selected[index].index = intLoop;
		}
	}
	return(selected);
}

function validateUSDate( strValue ) {
	/************************************************
	DESCRIPTION: Validates that a string contains only
	    valid dates with 2 digit month, 2 digit day,
	    4 digit year. Date separator can be ., -, or /.
	    Uses combination of regular expressions and
	    string parsing to validate date.
	    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

	PARAMETERS:
	   strValue - String to be tested for validity

	RETURNS:
	   True if valid, otherwise false.

	REMARKS:
	   Avoids some of the limitations of the Date.parse()
	   method such as the date separator character.
	*************************************************/
	  //var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	  var objRegExp = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/

	  //check to see if in correct format
	  if(!objRegExp.test(strValue))
	    return false; //doesn't match pattern, bad date
	  else{
	    var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
		var intDay = parseInt(arrayDate[1],10);
		var intYear = parseInt(arrayDate[2],10);
	    var intMonth = parseInt(arrayDate[0],10);

		//check for valid month
		if(intMonth > 12 || intMonth < 1) {
			return false;
		}

	    //create a lookup for months not equal to Feb.
	    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
	                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}

	    //check if month value and day value agree
	    if(arrayLookup[arrayDate[0]] != null) {
	      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
	        return true; //found in lookup table, good date
	    }

	    //check for February
		var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
	    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
	      return true; //Feb. had valid number of days
	  }
	  return false; //any other values, bad date
	}
