/*
 * $Id: itcommon.js,v 1.17 2006/01/04 08:26:12 tanvir Exp $
 *
 * Name: itcommon.js
 * Author: Sohel
 *
 * Common global variables and javascript functions.
 */

var apppath = "intourist_online";
var testmode = false;

var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
/**/
/*function setCalendarDate(val,dd,mmyy){
  var val1 = new Array();
  val1 = val.split("-");
  var i =val1[0];
  document.getElementById(dd).options[i-1].selected = true;
  i = val1[1]+" "+ val1[2];
  document.getElementById(mmyy).options[0].selected =true;
  for(j=0;j<document.getElementById(mmyy).length;j++){
  if(document.getElementById(mmyy).options[j].text == i ){
    document.getElementById(mmyy).options[j].selected = true;
  }
  }
}*/
//
// return ISO date yyyy-mm-dd
//

function getIsoDate(dateObj){
  if (!dateObj) return;
  var d = parseM4Date(dateObj);
  if (!d) return;
  var year = d.getFullYear()*1;
  var month =  d.getMonth()*1 + 1;
  month = month< 10 ? "0"+month:month;
  var day = d.getDate()*1;
  day = day< 10 ? "0"+day:day;
  return year+"-"+month+"-"+day;
}

function initPage(page) {
  if (page == 'plan') {
       collapseAll();
       var box = getCookie("ptype") != null ? getCookie("ptype") : "TW";
       toggleForm(box);
  }
}
function toggleForm(which){
  var tblObj = document.getElementById("tbl"+which);
  if (tblObj.rows[0].cells[0].className == "boxcollapsed"){
     
     collapseAll();
     tblObj.rows[0].cells[0].className = "boxexpanded";
     tblObj.rows[1].style.display = "";
     
  }
  else{
     tblObj.rows[0].cells[0].className = "boxcollapsed";
     tblObj.rows[1].style.display = "none";        
 
  }
}
function toggleSingleBox(which){
  var tblObj = document.getElementById("tbl"+which);
  if (tblObj.rows[0].cells[0].className == "boxcollapsed"){
     tblObj.rows[0].cells[0].className = "boxexpanded";
     tblObj.rows[1].style.display = "";
  }
  else{
     tblObj.rows[0].cells[0].className = "boxcollapsed";
     tblObj.rows[1].style.display = "none";        
  }
}

function collapseAll(){
  var tblObj;
  tblObj = document.getElementById('tblTR');
  tblObj.rows[0].cells[0].className = "boxcollapsed";
  tblObj.rows[1].style.display = "none";    
  tblObj = document.getElementById('tblTL');
  tblObj.rows[0].cells[0].className = "boxcollapsed";
  tblObj.rows[1].style.display = "none";    
  tblObj = document.getElementById('tblTW');
  tblObj.rows[0].cells[0].className = "boxcollapsed";
  tblObj.rows[1].style.display = "none";    
}

// Call this function to create a type-to-find dropdown
//
function smartOptionFinder(event, select) {
  var keycode = event.keyCode;
  var ch = String.fromCharCode(keycode);

  if (keycode>=32 && keycode<=126 ) {
    var now = new Date().getTime();
    if (select.getAttribute("finder") == null) {
      select.setAttribute("finder", ch.toUpperCase());
      select.setAttribute("timer", now);
    } else if ( now > parseInt(select.getAttribute("timer"))+1000) { //Rest all;
      select.setAttribute("finder", ch.toUpperCase());
      select.setAttribute("timer", now) //reset timer;
    } else {
      select.setAttribute("finder", select.getAttribute("finder")+ch.toUpperCase());
      select.setAttribute("timer", now); //up  timer;
    }
    var finder = select.getAttribute("finder");
    for (var i = 0; i < select.options.length ; i++) {
      if (select.options[i].text.toUpperCase().indexOf(finder) == 0) {
        select.options[i].selected = true;
        break;
      }
    }
    event.returnValue = false;
  } else {
    //Not a printable character, ignore
  }
}

// Cookie functions
//

// a date far far away 31st Dec 2099
var forever = new Date(2099, 11, 31);

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// Validate credit card number
//
function isCCNo(cardno) {
  if (testmode) {
    return (cardno != null && cardno != "");
  }

  var ccno = cardno.replace(/[^0-9]/g, "");
  while (ccno.length < 20) {
    ccno = "0" + ccno;
  }
  var checksum = 0;
  for (i=0; i<20; i+=2) {
    checksum += (parseInt((ccno.charAt(i)) * 2) + parseInt(ccno.charAt(i+1)));
    if (parseInt(ccno.charAt(i)) * 2 > 9) {
      checksum -= 9;
    }
  }
  if (checksum % 10) {
    return false;
  }
  return true;
}

// Validate email address
//
function isEmail(address) {
  if (testmode) {
    return (address != null && address != "");
  }

  var parts = address.split('@');
  // must have exactly one '@'
  if (parts.length != 2) {
    return false;
  }
  // must have al least one '.'
  var domain = parts[1].split('.');
  if (domain.length < 2) {
    return false;
  }
  // the top level domain must be two or three characters long
  if (domain[domain.length-1].length < 2 || domain[domain.length-1].length > 3) {
    return false;
  }
  return true;
}

// Go to the home page
//
function goHome() {
  var frmStart = document.getElementById("frmStart");
  if (frmStart) {
    frmStart.submit();
  }
}

// Show/hide progress pop-up window
//
function showProgress(show) {
  var pgbar = document.getElementById("spnProgress");
  if (show) {
    //sleep(5);
    pgbar.style.top = (document.body.clientHeight/2) - (pgbar.clientHeight/2);
    pgbar.style.left = (document.body.clientWidth/2) - (pgbar.clientWidth/2);
    pgbar.style.visibility = "visible";
  } else {
    //sleep(5);
    pgbar.style.visibility = "hidden";
  }
}
function allowInteger(e) {
  var reg;
  var keychar;
  var key;
  if(window.event) {
    //IE
  key = e.keyCode;
  }
  else if(e.which) {
    // netscape
    key = e.which;
    }
    else {
    // no event, so pass through
    return true;
    }
  var keychar = String.fromCharCode(key);
  reg = /\d/;
  if (reg.test(keychar) || key==8 || key == 46 || key == 37|| key == 39) return true
  else
  return false;
}
//
//  show debug message in alert
//
function debug(msg){
  alert(msg);
}
// submit login form
//
function doLogin(formname) {
  var form = document.getElementById(formname);
  if (validate_login(form)) {
    form.hidACT.value = 'login';
    form.action = "http://bookings.intouristuk.com/intourist/itmainsc.php";
    form.submit();
  }
}
// validate the login form
//
function validate_login(form) {
  var msgs = new Array(
             "Agent code is empty",
             "Password is empty",
             ""
             );
  var errmsg = "";

  if (form.txtAGENT.value == "") {
    errmsg = errmsg + "\n" + msgs[0];
  }
  if (form.txtPASSW.value == "") {
    errmsg = errmsg + "\n" + msgs[1];
  }
  if (errmsg != "") {
    alert("Please correct the following errors to proceed:" + "\n" + errmsg);
    return false;
  }
  form.txtAGENT.value = form.txtAGENT.value.toUpperCase();
  return true;
}
//
// Re-submit the page
//
function reSubmit(frmId, action, nextAct) {
  if ( !frmId || frmId == '' ) { return; }
  if ( !action || action == '' ) { return; }
  if ( !nextAct  ) { 
    nextAct = "";
  }
  var frmElement = document.getElementById(frmId);
  if ( frmElement.hidACT && frmElement.hidACT.value != ""){
    frmElement.hidACT.value = nextAct;
    frmElement.action = action;
    frmElement.submit();
  }
}
// 
// define visibility of an html element depending on
// element id and boolean condition 
//
function defineVisibility(eId, c){
  var element = document.getElementById(eId);
  if (!element) {return ;}
  element.style.display = "none";
  if (c){
    element.style.display = "";
  }
}
//
// call me implementation
//
function callme(){
  var phone = document.getElementById('txtCALLME');
  var errMsg = "";
  if (!phone || trim(phone.value) == '' || trim(phone.value).toUpperCase() == 'PHONE NUMBER' ||
    trim(phone.value).length < 8){
    errMsg = errMsg + "Please enter the valid phone number\n";
  }
  var name  = document.getElementById('txtLEADNM');
  if (!name || trim(name.value) == '' || trim(name.value).toUpperCase() =='NAME' ||
    trim(name.value).length < 2){
    errMsg = errMsg + "Please enter your name";
  }
  if (errMsg != ''){
    alert(errMsg);
    return;
  }
  // cookie phone number
  var cPhone = getCookie('callphone') != null?getCookie('callphone').toUpperCase():"";
  // cookie name
  var cName = getCookie('callname') != null?getCookie('callname').toUpperCase():"";
  if (cPhone == phone.value.toUpperCase() && 
     cName == name.value.toUpperCase()){
    showCallmeAlert();
    return;
  }
  var async = true;
  var app = document.getElementById('hidAPP').value;
  var sess= document.getElementById('hidSESS').value;
  var url = location.protocol + "//" + location.host+ "/"+app +"/itcallme.php?phone="+phone.value+"&name="+name.value;
  //debug(url);
  try{
    xmlhttp = XmlHttp.create();
    xmlhttp.open("GET", url, async);
    xmlhttp.onreadystatechange = onCallmeResponse;
    xmlhttp.send(null);
  }catch(ex){
    alert(ex);
  }
}
// process response message
//
function onCallmeResponse() {
  if (xmlhttp.readyState != 4) return;
  var response = xmlhttp.responseText;
  try {
    var xmldoc = XmlDocument.create();
    var errText = "";
    xmldoc.loadXML(response);
    //debug(response);
    var xmlerr = xmldoc.parseError;
    if (xmlerr.errorCode != 0) {
      /*errText = "Error (" + xmlerr.errorCode + "): " + xmlerr.reason
                + "\n"
                + "Error in line " + xmlerr.line + " character " + xmlerr.linepos
                + "\n"
                + xmlerr.srcText
                + "\n---------------------\n\n";
                alert(errText);*/
      // it should not go for infinity, maximum limit is 5 years
      return false;
    }
    var callmeStat = xmldoc.getElementsByTagName("Success")[0];
    if (get_nodeval(callmeStat) == 'true'){
      showCallmeAlert();
      var expdate = new Date ();
      // expires after 30mins
      expdate.setTime (expdate.getTime() + (1000 * 60 * 30)); 
      setCookie('callphone',document.getElementById('txtCALLME').value,expdate);
      setCookie('callname',document.getElementById('txtLEADNM').value,expdate);
    }else{
      alert('Sorry, your call me request couldn\'t be sent at the moment. Please try later.');    
    }
  } catch (ex) {
    alert(ex);
  }
}
//
// show call me alert on success
//
function showCallmeAlert(){
  alert('Your request has been sent to our reservations department.\n One of our reservationists will contact you shortly');
}
function get_nodeval(node)
{
  if (node && node.hasChildNodes()) {
    return node.childNodes[0].nodeValue;
  }
  else {
    return "";
  }
}
//
// trim function 
//
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}
// Flag - this script is loaded and execute
//
document.itcommon_js = true;


