
//2011-07-22
function httpsRedirect(secure)
{
   var url = window.location.hostname;
   if(url.indexOf('www') < 0) url = "www." + url;
   
   if(secure)  window.location = "https://" + url + window.location.pathname;
   else        window.location = "http://"  + url + window.location.pathname;
}


//2011-07-09
function img_size(o,w,h){
   var ratio = o.width/o.height;
   if(o.width > w) {
     o.width = w; 
     o.height = w / ratio; 
   } 
   if(o.height > h) {
     o.height = h; 
     o.width = h * ratio;
   } 
}


//2011-07-02
function general_form_check(o)
{
  $('#warning_message').hide();

  var good = true;
   
  $(".rq").each(function(){
    
	 if(this.value==''){
         $(this).addClass('input_err');
         good = false;
     }
     else{
         $(this).removeClass('input_err');
     }
  })

  if(!good){
    $('#warning_message').show(500);
    return false;
  } 
  else 
  {
	  if(!credit_valid()) 
	  {
		  return false;
	  }
	  else if(!check_expiration())
	  {
		   return false;
	  }
	  else 
	  {
		  return true;
	  }
  }
}

function check_expiration()
{
  var expr = $('#expr');
  if(expr){
	  var p = expr.val();
	  p = p.replace(/[^\d]*/gi,"");	
	  if (p.length != 4) 
	  {
		expr.addClass('input_err');
		return false;
	  } 
	  else
	  {
		  if(false) //????
		  {
			 expr.addClass('input_err');
			 return false; 
		  }
		  else
		  {
			 expr.removeClass('input_err');
			 return true;			  
		  }		  
	  }		
  }  
  return true;
}

function credit_valid()
{
	if($('#cardno') || $('#card_type'))
	{
	   
	   $('#invalid_card_message').hide();
	   
	   var no = $('#cardno').val();
	   var typ = $('#card_type').val();
	  
	   if(!(checkCreditCard(no, typ)))
	   {
		  $('#cardno').addClass('input_err');
		  $('#card_valid').val('');
		  $('#invalid_card_message').show(500);
		  
		  return false;
	   }
	   else
	   {
		  $('#cardno').removeClass('input_err');
		  $('#card_valid').val('1');
		  
		  return true;
	   }
	}
	else 
	{
		return true;
	}
}

function uniqid(){
	var newDate = new Date;
	return newDate.getTime();
}



function winopen(url){
   window.open(url,'','width=640, height=480,resizable=1,scrollbars=1');
   return;
}


//2008-05-19
//1. form with id '_rqd' focus on first element
//2. element with id '_rqd' will validate;
//3. in IE, rel attribute is used a alert information.
function formProcess(){
   
   var frms = document.getElementsByTagName('form');
   
   $each(frms, function(frm){

      if(frm.id.test(/_rqd/i)) {

         //using the ID as a mark, because some browsers don't support rel or any other arbitrary attributes
         //after the id is used, store the infor to el.rqd, and recover back to a 'normal' one (without the affix '_rqd', etc.)         
         var els = $(frm).getFormElements();
         var focused = false;
         
         $each(els, function(el){
            if(el.id.test(/_rqd$/i)){
               el.rqd=true; 
               el.id.replace(/_rqd$/i,'');   //????
            }
            if(!el.getValue() && !focused) {
               el.focus();
               focused = true;
            }
         });
      
         //same thing to the form id.
         frm.id = frm.id.replace(/_rqd$/i,'');
         frm.rqd = true;
         
         
         $(frm).addEvent('submit', function(e){
            
            var e = new Event(e);         

            for(var i=0; i<$A(els).length; i++){
               
               //an invalidate entry found
               if(!els[i].getValue() && els[i].rqd == true) {
                  
                  //invalidate the form submit action.
                  e.stop();
                  
                  //IE supports 'rel' attribute
                  alert(els[i].rel ? els[i].rel : 'Please fill the highlighted field!');
                  
                  els[i].focus();
                  
                  $(els[i]).addClass('required');
                  $(els[i]).addEvent('change', function(){
                                                   if(this.getValue()){
                                                      this.removeClass('required');
                                                   }
                                                });                  
                  break;
               }
            }
         });
      }
   })
}


function objShow(o) {
   var s = "";
   for(var name in o) {
      if(o[name]) s += name + '=' + o[name] + "\n";
   }
   alert(s);
}

function getOS(){
	
	var os, ua = navigator.userAgent;
	if (ua.match(/Win(dows )?NT 6\.0/)) {
		os = "Windows Vista";            // Windows Vista ???
	}
	else if (ua.match(/Win(dows )?NT 5\.2/)) {
		os = "Windows Server 2003";         // Windows Server 2003 ???
	}
	else if (ua.match(/Win(dows )?(NT 5\.1|XP)/)) {
		os = "Windows XP";            // Windows XP ???
	}
	else if (ua.match(/Win(dows)? (9x 4\.90|ME)/)) {
		os = "Windows ME";            // Windows ME ???
	}
	else if (ua.match(/Win(dows )?(NT 5\.0|2000)/)) {
		os = "Windows 2000";            // Windows 2000 ???
	}
	else if (ua.match(/Win(dows )?98/)) {
		os = "Windows 98";            // Windows 98 ???
	}
	else if (ua.match(/Win(dows )?NT( 4\.0)?/)) {
		os = "Windows NT";            // Windows NT ???
	}
	else if (ua.match(/Win(dows )?95/)) {
		os = "Windows 95";            // Windows 95 ???
	}
	else if (ua.match(/Mac|PPC/)) {
		os = "Mac OS";               // Macintosh ???
	}
	else if (ua.match(/Linux/)) {
		os = "Linux";               // Linux ???
	}
	else if (ua.match(/(Free|Net|Open)BSD/)) {
		os = RegExp.$1 + "BSD";            // BSD ????
	}
	else if (ua.match(/SunOS/)) {
		os = "Solaris";               // Solaris ???
	}
	else {
		os = "N/A";               // ???? OS ???
	}
	
	return os;
}

//2009-12-03:
function getBrowserInfo(){

	var java = navigator.javaEnabled();
	var cookie = navigator.cookieEnabled;

	var browser, version;
	
	var userAgent = navigator.userAgent.toLowerCase();
	$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
	 
	if($.browser.msie){
		browser = "IE";
		version = $.browser.version.substring(0,3);
	}
	else if($.browser.chrome){
		browser = "Chrome";
		userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
		version = userAgent.substring(0,3);
		$.browser.safari = false;
	}
	 
	else if($.browser.safari){
		browser = "Safari";
		userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
		version = userAgent.substring(0,3);
	}
	 
	else if($.browser.mozilla){
		if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
			browser = "FireFox";
			userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
			version = userAgent.substring(0,3);
		}
		else{
			browser = "Mozilla";
			version = "";
		}
	}
	 
	 // Is this a version of Opera?
	else if($.browser.opera){
		browser = "Opera";
		version = "";
	}   
	
	//This java is not javascript
	return {
				"java":  java,
				"cookie": cookie,
				"browser": browser,
				"version": version
			};
	
}


function showSystem($o)
{
   var os       = getOS();
   var browser  = getBrowserInfo();
   $o.text('Your are running ' + os + ', ' + browser['browser']+' '+browser['version'] + ', cookie: ' + (browser['cookie'] ? 'on' : 'off') );
}

function showNow($o){
   var now = new Date();   
   $o.text(now.format());
   setInterval(function(){now   = new Date(); $o.text(now.format());},1000);
}

/*
   Simplest jQuery Image Cycler;
   Made by Kevin Luo from http://www.fotosteps.com.
   on Feb 2nd, 2010      
*/
(function($){
   $.fn.simpleCycle = function(){                           
      return this.each(function(){
         var imgCount = -1;
         $sc = $(this)
         function showImg(){
            imgCount++;
            var imgs = $sc.children('img');
            if(imgCount >= imgs.length ) imgCount = 0;
            
            imgs.eq(imgCount).siblings().hide();
            imgs.eq(imgCount).fadeIn(2000, showImg);
            $sc.css('background-image','url('+ this.src +')');
          };
          showImg();
      });
    };
   
})(jQuery);      


/* phone number formating starts. */

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 14;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object){
  phonevalue1 = ParseChar(object.value, zChar);
}

function ParseForNumber2(object){
  phonevalue2 = ParseChar(object.value, zChar);
}

//Main 
function backspacerUP(object,e) {
  if(e){
    e = e
  } else {
    e = window.event
  }
  if(e.which){
    var keycode = e.which
  } else {
    var keycode = e.keyCode
  }

  ParseForNumber1(object)

  if(keycode >= 48){
    ValidatePhone(object)
  }
}

//Main
function backspacerDOWN(object,e) {
  if(e){
    e = e
  } else {
    e = window.event
  }
  if(e.which){
    var keycode = e.which
  } else {
    var keycode = e.keyCode
  }
  ParseForNumber2(object)
}

function GetCursorPosition(){

  var t1 = phonevalue1;
  var t2 = phonevalue2;
  var bool = false
  for (i=0; i<t1.length; i++)
  {
    if (t1.substring(i,1) != t2.substring(i,1)) {
      if(!bool) {
        cursorposition=i
        window.status=cursorposition
        bool=true
      }
    }
  }
}

function ValidatePhone(object){

  var p = phonevalue1

  p = p.replace(/[^\d]*/gi,"")

  if (p.length < 3) {
    object.value=p
  } else if(p.length==3){
    pp=p;
    d4=p.indexOf('(')
    d5=p.indexOf(')')
    if(d4==-1){
      pp="("+pp;
    }
    if(d5==-1){
      pp=pp+")";
    }
    object.value = pp;
  } else if(p.length>3 && p.length < 7){
    p ="(" + p;
    l30=p.length;
    p30=p.substring(0,4);
    p30=p30+") "

    p31=p.substring(4,l30);
    pp=p30+p31;

    object.value = pp;

  } else if(p.length >= 7){
    p ="(" + p;
    l30=p.length;
    p30=p.substring(0,4);
    p30=p30+") "

    p31=p.substring(4,l30);
    pp=p30+p31;

    l40 = pp.length;
    p40 = pp.substring(0,9);
    p40 = p40 + "-"

    p41 = pp.substring(9,l40);
    ppp = p40 + p41;

    object.value = ppp.substring(0, maxphonelength);
  }

  GetCursorPosition()

  if(cursorposition >= 0){
    if (cursorposition == 0) {
      cursorposition = 2
    } else if (cursorposition <= 2) {
      cursorposition = cursorposition + 1
    } else if (cursorposition <= 4) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 5) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 6) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 7) {
      cursorposition = cursorposition + 4
    } else if (cursorposition == 8) {
      cursorposition = cursorposition + 4
      e1=object.value.indexOf(')')
      e2=object.value.indexOf('-')
      if (e1>-1 && e2>-1){
        if (e2-e1 == 4) {
          cursorposition = cursorposition - 1
        }
      }
    } else if (cursorposition == 9) {
      cursorposition = cursorposition + 4
    } else if (cursorposition < 11) {
      cursorposition = cursorposition + 3
    } else if (cursorposition == 11) {
      cursorposition = cursorposition + 1
    } else if (cursorposition == 12) {
      cursorposition = cursorposition + 1
    } else if (cursorposition >= 13) {
      cursorposition = cursorposition
    }

    var txtRange = object.createTextRange();
    txtRange.moveStart( "character", cursorposition);
    txtRange.moveEnd( "character", cursorposition - object.value.length);
    txtRange.select();
  }

}

function ParseChar(sStr, sChar)
{

  if (sChar.length == null)
  {
    zChar = new Array(sChar);
  }
    else zChar = sChar;

  for (i=0; i<zChar.length; i++)
  {
    sNewStr = "";

    var iStart = 0;
    var iEnd = sStr.indexOf(sChar[i]);

    while (iEnd != -1)
    {
      sNewStr += sStr.substring(iStart, iEnd);
      iStart = iEnd + 1;
      iEnd = sStr.indexOf(sChar[i], iStart);
    }
    sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);

    sStr = sNewStr;
  }

  return sNewStr;
}

/* phone number formating ends. */







/* Credit Card validation starts*/

/*================================================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on the web, although the 
best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia
Updated:    11th Sep. 2010      Typos removed from Diners and Solo definitions (thanks to Noe Leon)

*/

/*
   If a credit card number is invalid, an error reason is loaded into the global ccErrorNo variable. 
   This can be be used to index into the global error  string array to report the reason to the user 
   if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard(cardnumber, cardname){
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types as follows.
  
  //  Name:         As in the selection box of the form - must be same as user's
  //  Length:       List of possible valid lengths of the card number for the card
  //  prefixes:     List of possible prefixes for the card
  //  checkdigit:   Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305,36,38,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmericanExpress", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334,6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the length if all else was 
  // hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*================================================================================================*/



/* Credit Card validation ends */
