//! ################################################################
//! All Rights Reserved.
//! ################################################################

var ua         =  navigator.userAgent.toLowerCase();
var uv         =  navigator.appVersion.toLowerCase();

var isDOM      = document.getElementById;

var isMac      = (ua.indexOf("mac") != -1);
var isIEMac    = ((document.all)&&(isMac));

var isIE       = document.all;
var isIE4      = ((document.all)&&(uv.indexOf("msie 4.")!=-1));
var isIE5      = ((document.all)&&(uv.indexOf("msie 5.")!=-1));
var isIE6      = ((document.all)&&(uv.indexOf("msie 6.")!=-1));
var isIE7      = ((document.all)&&(uv.indexOf("msie 7.")!=-1));

var isNS4      = document.layers;

var isFirefox  = (ua.indexOf('firefox')   != -1);

var isOP7      = (window.opera && document.createComment);
var isGecko    = (ua.indexOf('gecko')     != -1 && ua.indexOf('safari') == -1);
var isOpera    = (ua.indexOf('opera')     != -1);
var isSafari   = (ua.indexOf('safari')    != -1);
var isWebtv    = (ua.indexOf('webtv')     != -1);


//! ################################################################
//! Configuration Begin
//! ################################################################

var BR   = "<br />";

//! ################################################################
//! Configuration Ends
//! ################################################################

//This is loaded from the script/tbrowser_ie.js and all the similars.
//It's the only to have both the pull-down menu and all the onload
//functions work together.
//2006-10-16
//place everything here to load
myOnload = function(){
   changeInputs();
}

///////////////////////////////////////////////
// IE DOM fix.
if (!window.Node) {
   var Node = {                  // If there is no Node object, define one
      ELEMENT_NODE:              1, // with the following properties and values.
      ATTRIBUTE_NODE:            2, // Note that these are HTML node types only.
      TEXT_NODE:                 3, // For XML-specific nodes, you need to add
      COMMENT_NODE:              8, // other constants here.
      DOCUMENT_NODE:             9,
      DOCUMENT_FRAGMENT_NODE:   11
   }
}

///////////////////////////////
// String function enhancement
String.prototype.trim = function() {
   return this.replace(/^\s*|\s*$/g,"")
};

String.prototype.ucwords = function(){
   return this.replace(   /\w+/g,  function(a){ return a.charAt(0).toUpperCase() + a.substr(1);}  );
};

String.prototype.ucfirst = function(){
   return this.charAt(0).toUpperCase() + this.substr(1);
};

String.prototype.endsWith = function(c) {
   return (c == this.charAt(this.length-1))
}

/* ########################################################################################## */

//2008-02-11
function id_update(id) { 
   //alert(xmlHttp.responseText);
   var o = document.getElementById(id);
   o.innerHTML=xmlHttp.responseText;
   if(xmlHttp.responseText=='error') o.style.backgroundColor = '#FFC0C0';
   else o.style.backgroundColor = '#C0D7A8';
}

function GetXmlHttpObject(){

   var xmlHttp=null;
   try{
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
   }
   catch (e){
      //Internet Explorer
      try{
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e){
         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return xmlHttp;
}  
  

/*
Name: General Tooltip
Compatibility: DOM level2, IE5+, IE4
Date: 3/21/2007, from The Definitive Guide, 5th Edition
Link:   1.  images/tooltip_pointer.gif has to exist
        2.  images/bg_tooltip.gif
        3.  css: tooltipContainer, tooltipPointer, tooltipShadow, tooltipContainer have to be ready
        4.  tooltip attribute of the object is the content of the tooltip. replace the " with &quot; 
Ex: <a href="www.goiaccess.com" tooltip="Tooltip content."  onmouseover="toolTip.doShow(this, event)">iAccess, Inc.</a>
*/
function Tooltip() { 
    
    this.X_OFFSET = 15;  
    this.Y_OFFSET =  15; 
    this.DELAY = 100;  
    
    this.tooltip = document.createElement("div");     //Container
    this.tooltip.style.position = "absolute";    
    this.tooltip.style.visibility = "visible";   
    this.tooltip.className = "tooltipContainer";  
    
    this.pointer = document.createElement("img");    //Pointer image
    this.pointer.src='images/tooltip_pointer.gif';
    this.pointer.style.position = "relative";   
    this.pointer.className = "tooltipPointer"; 

    this.shadow  = document.createElement("div");    //Shadow
    this.shadow.style.position = "relative";   
    this.shadow.className = "tooltipShadow"; 

    this.content = document.createElement("div");    //Content
    this.content.style.position = "relative";   
    this.content.className = "tooltipContent"; 

    this.tooltip.appendChild(this.pointer);   
    this.tooltip.appendChild(this.shadow);   
    this.shadow.appendChild(this.content);
}

Tooltip.prototype.show = function(text, x, y) {
    this.content.innerHTML = text;            
    this.tooltip.style.left = x + "px";      
    this.tooltip.style.top  = y + "px";
    this.tooltip.style.visibility = "visible";

    if (this.tooltip.parentNode != document.body)  document.body.appendChild(this.tooltip);
};

Tooltip.prototype.hide = function() {
    this.tooltip.style.visibility = "hidden";
};
 
Tooltip.prototype.doShow = function(target, e) {

    var text = target.getAttribute("tooltip");
    if (!text) return;

    var x = getMouseX(e);
    var y = getMouseY(e);

    x += this.X_OFFSET;
    y += this.Y_OFFSET;

    var self = this;  // We need this for the nested functions below
    var timer = window.setTimeout(function( ) { self.show(text, x, y); },this.DELAY);

    if (target.addEventListener) target.addEventListener("mouseout", mouseout,false);
    else if (target.attachEvent) target.attachEvent("onmouseout", mouseout);
    else target.onmouseout = mouseout;

    function mouseout( ) {
        self.hide( );              
        window.clearTimeout(timer);

        if (target.removeEventListener) target.removeEventListener("mouseout", mouseout, false);
        else if (target.detachEvent) target.detachEvent("onmouseout",mouseout);
        else target.onmouseout = null;
    }
}

// Define a single global Tooltip object for general use
var toolTip = new Tooltip( );



/*
Name: Draging an object
Compatibility: DOM level2, IE5+, IE4
Date: 3/21/2007, from The Definitive Guide, 5th Edition
It is important to note that the mousemove and mouseup handlers are registered as capturing event handlers because the user may move the mouse faster than the document element can follow it, and some of these events occur outside the original target element. Without capturing, the events may not be dispatched to the correct handlers. Also, note that the moveHandler( ) and upHandler( ) functions that are registered to handle these events are defined as functions nested within drag( ). Because they are defined in this nested scope, they can use the arguments and local variables of drag( ), which considerably simplifies their implementation.
Ex: onmousedown="drag(this.parentNode, event)";
*/

function drag(elementToDrag, event) {

    var startX = event.clientX
    var  startY = event.clientY;

    var origX = elementToDrag.offsetLeft;
    var origY = elementToDrag.offsetTop;

    var deltaX = startX - origX;
    var deltaY = startY - origY;

    if (document.addEventListener) {  // DOM Level 2 event model
        document.addEventListener("mousemove", moveHandler, true);
        document.addEventListener("mouseup", upHandler, true);
    }
    else if (document.attachEvent) {  // IE 5+ Event Model
        elementToDrag.setCapture( );
        elementToDrag.attachEvent("onmousemove", moveHandler);
        elementToDrag.attachEvent("onmouseup", upHandler);
        elementToDrag.attachEvent("onlosecapture", upHandler);
    }
    else {  // IE 4 Event Model
        // In IE 4 we can't use attachEvent( ) or setCapture( ), so we set event handlers directly on the document object and hope that the mouse events we need will bubble up.
        var oldmovehandler = document.onmousemove; 
        var olduphandler = document.onmouseup;
        document.onmousemove = moveHandler;
        document.onmouseup = upHandler;
    }

    // We've handled this event. Don't let anybody else see it.
    if (event.stopPropagation) event.stopPropagation( );  // DOM Level 2
    else event.cancelBubble = true;                      // IE

    // Now prevent any default action.
    if (event.preventDefault) event.preventDefault( );   // DOM Level 2
    else event.returnValue = false;                     // IE

    function moveHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        elementToDrag.style.left = (e.clientX - deltaX) + "px";
        elementToDrag.style.top = (e.clientY - deltaY) + "px";

        // And don't let anyone else see this event.
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }

    function upHandler(e) {
        if (!e) e = window.event;  // IE Event Model

        // Unregister the capturing event handlers.
        if (document.removeEventListener) {  // DOM event model
            document.removeEventListener("mouseup", upHandler, true);
            document.removeEventListener("mousemove", moveHandler, true);
        }
        else if (document.detachEvent) {  // IE 5+ Event Model
            elementToDrag.detachEvent("onlosecapture", upHandler);
            elementToDrag.detachEvent("onmouseup", upHandler);
            elementToDrag.detachEvent("onmousemove", moveHandler);
            elementToDrag.releaseCapture( );
        }
        else {  // IE 4 Event Model
            // Restore the original handlers, if any
            document.onmouseup = olduphandler;
            document.onmousemove = oldmovehandler;
        }

        // And don't let the event propagate any further.
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
        else e.cancelBubble = true;                  // IE
    }
}


/*
* 03/20/2007
*/
function getSelectedText() {
    if (window.getSelection) {
        // This technique is the most likely to be standardized.
        return window.getSelection().toString();
    }
    else if (document.getSelection) {
        // This is an older, simpler technique that returns a string
        return document.getSelection();
    }
    else if (document.selection) {
        // This is the IE-specific technique.
        return document.selection.createRange().text;
    }
}


/* give all the inputs a classname */
function changeInputs(){
   var em = document.getElementsByTagName('input');
   var i = 0;
   for ( i=0; i<em.length; i++ ) {
      if(em[i].className ==''){
         if ( em[i].getAttribute('type') ) {
            var t = em[i].getAttribute('type');
            switch(t){
               case "radio":     break;
               case "checkbox":  break;
               case "text":      em[i].className = 'text';
                                 break;
               case "password":  em[i].className = 'text';
                                 break;
               default:          em[i].className = 'button';
            }
         }
      }
   }
}

/*
* 10/19/2006
*/
function printPreview(){
   if(isIE && !isIE7){
      var OLECMDID = 7;
      /* OLECMDID values:
      * 1 - open window
      * 2 - close
      * 4 - Save As
      * 6 - print
      * 7 - print preview
      * 8 - page setup
      * 10- page property
      */
      var PROMPT = 1; // 2 DONTPROMPTUSER
      var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
      document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
      WebBrowser1.ExecWB(OLECMDID, PROMPT);
      WebBrowser1.outerHTML = "";
   }
   else{
      window.print();
   }
}


/* Submit a form to a page */
window.formSub = function(page) {
   document.myform.action=page;
   document.myform.submit();
}

window.pop  = function(url,name,options)   {
   var w = window.open(url,name,options);
   w.opener = this;
   w.focus();
}
window.redir  = function(url)   {  document.location.href=url;   }
//////////////////////////////////////////////////////////////////////
// scroll = 'yes', 'no'
window.popCenter  = function(url,n,w,h,scroll) {
   var winl = (screen.width - w) / 2;
   var wint = (screen.height - h) / 2;
   ops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
   win = window.open(url, n, ops)
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

// Change a decimal field value into $xxx;
function   to$(o){
   var s = o.value;
   if(isDecimal(s)) o.value='$'+s;
   return;
}


////////////////////////////////////////
// add extra event to an object
// addEvent( window, 'load', Startup );
function addEvent( node, evtType, func ) {

   if( node.addEventListener ) {
      node.addEventListener( evtType, func, false );
      return true;
   }
   else if( node.attachEvent )
      return node.attachEvent( "on" + evtType, func );

   else
      return false;
}


//Cross-browser version of getElementById();
function fetchObject(id) {
   if(isDOM)       return document.getElementById(id);
   else if(isIE)   return document.all[id];
   else if(isNS)   return document.layers[id];
}


//Check if the date is valid aginst the format "MDY";
//2006/10/25
function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();

   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   }
   else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   }
   else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; }
   else if (format.substring(1, 2) == "M") { var mm = parts[1]; }
   else { var mm = parts[2]; }

   if (format.substring(0, 1) == "D") { var dd = parts[0]; }
   else if (format.substring(1, 2) == "D") { var dd = parts[1]; }
   else { var dd = parts[2]; }

   if (format.substring(0, 1) == "Y") { var yy = parts[0]; }
   else if (format.substring(1, 2) == "Y") { var yy = parts[1]; }
   else { var yy = parts[2]; }

   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }

   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }

   return true;
}


function localDate(){
   var d = new Date().toLocaleString()
   return d.substring(0,d.length-12);   //Sunday, July 16, 2006
}

function localDateTime(){
   return new Date().toLocaleString()  //Sunday, July 16, 2006 10:11:03 AM
}

//01:02:31 PM
function currentTime(){
   var d = new Date();                 // Get the current time
   var h = d.getHours();               // Extract hours: 0 to 23
   var m = d.getMinutes();             // Extract minutes: 0 to 59
   var s = d.getSeconds();
   var ampm = (h >= 12)?"PM":"AM";      // Is it a.m. or p.m.?
   if (h > 12) h -= 12;                 // Convert 24-hour format to 12-hour
   if (h == 0) h = 12;                  // Convert 0 o'clock to midnight
   if (h < 10) h = "0" + h;             // Convert 0 minutes to 00 minutes, etc.
   if (m < 10) m = "0" + m;             // Convert 0 minutes to 00 minutes, etc.
   if (s < 10) s = "0" + s;             // Convert 0 minutes to 00 minutes, etc.
   var t = h + ':' + m + ':' + s + ' '+ ampm;    // Put it all together
   return t;
}

function URLEncode(s)
{
   // The Javascript escape and unescape functions do not correspond
   // with what browsers actually do...
   var SAFECHARS = "0123456789" +               // Numeric
               "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +   // Alphabetic
               "abcdefghijklmnopqrstuvwxyz" +   // Alphabetic
               "-_.!~*'()";                     // RFC2396 Mark characters
   var HEX = "0123456789ABCDEF";

   var encoded = "";
   for (var i = 0; i < s.length; i++ ) {
      var ch = s.charAt(i);
       if (ch == " ") {
          encoded += "%20";            // used to "+"; x-www-urlencoded, rather than %20
      } else if (SAFECHARS.indexOf(ch) != -1) {
          encoded += ch;
      } else {
          var charCode = ch.charCodeAt(0);
         if (charCode > 255) {
             alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
                      "(URL encoding only supports 8-bit characters.)\n" +
                    "A space (+) will be substituted." );
            encoded += "+";
         } else {
            encoded += "%";
            encoded += HEX.charAt((charCode >> 4) & 0xF);
            encoded += HEX.charAt(charCode & 0xF);
         }
      }
   } // for

   return encoded;
};

function URLDecode(s)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var plaintext = "";
   var i = 0;
   while (i < s.length) {
       var ch = s.charAt(i);
      if (ch == "+") {
          plaintext += " ";
         i++;
      } else if (ch == "%") {
         if (i < (s.length-2)
               && HEXCHARS.indexOf(s.charAt(i+1)) != -1
               && HEXCHARS.indexOf(s.charAt(i+2)) != -1 ) {
            plaintext += unescape( s.substr(i,3) );
            i += 3;
         } else {
            alert( 'Bad escape combination near ...' + s.substr(i) );
            plaintext += "%[ERROR]";
            i++;
         }
      } else {
         plaintext += ch;
         i++;
      }
   } // while
   return plaintext;
};

function getMin(a,aa){return a<aa?a:aa}
function getMax(a,aa){return a>aa?a:aa}

//////////////////////////////////////////////////////
// FUNCTION ARGUMENTS
function maxAll(){
   var m = Number.NEGATIVE_INFINITY;
   // Loop through all the arguments, looking for, and
   // remembering, the biggest
   for(var i = 0; i < arguments.length; i++)   if (arguments[i] > m) m = arguments[i];    // Return the biggest
   return m;
}

function Bookmark(){
   if ((navigator.appName == 'Microsoft Internet Explorer') && (window.clientInformation.javaEnabled() == true )) {
       window.external.AddFavorite(location.href,document.title);
   }
}

//////////////////////////////////////////////////////////////////////
// Change all the tags with a class a's style 'aa' to new value 'ab';
// ex: classStyleTo('myclass','color','#ff0000');
function classStyleTo(a,aa,ab){
   var ac=getTagArrayByName("*");   /* Get an array of all the tags */
   for(var ad=0;ad<ac.length;ad++){
      if(ac[ad].className==a){
         ac[ad].style[aa]=ab
      }
   }
}

function jumpOut()
{
  if (top != self)
    top.location = self.location
}


/*  "?:": no capture  */
function isEmail(email) {
   var re = /^(?:\w+\.?)*\w+@(?:\w+\.)+[a-z]{2,}$/i;
   return re.test(email);
}

function getBaseHref(){
    var oBaseColl = document.all.tags('BASE');
    return ( (oBaseColl && oBaseColl.length) ? oBaseColl[0].href : null );
}
function getBaseTarget(){
    var oBaseColl = document.all.tags('BASE');
    return ( (oBaseColl && oBaseColl.length) ? oBaseColl[0].target : null );
}


////////////////////////////////////////////////////////
// general utility for browsing a named array or object
// ex: arrayShow(window);
// This one is similar to the objShow. Because the object
// can always be used as an associative array.
function arrayShow(o) {
   s = '';
   for(e in o) {s += e+'='+o[e]+'\n';}
   alert( s );
}
////////////////////////////////////////////////////////
// show all properties of an obj.
// ex: objShow(window);
// !!! "for-in" loop is the only way to show an obj
// properties since we don't usually know the property
// name in advance.
function objShow(o) {
   var s = "";
   for(var name in o) {
      if(o[name]) s += name + '=' + o[name] + "\n";
   }
   alert(s);
}

//////////////////////////////////////////////////
// Convert an obj property names to an array
// ex: dW(objNameToArray(window).join(BR));
function objNameToArray(o){
   var a = new Array();
   for(a[i++] in o);
   return a;
}

//////////////////////////////////////////////////
// Convert an obj content to an associative array
// ex: dW(objToArray(window)['onload']);
function objToArray(o){
   var a = new Array();
   for(e in o){
      a[e] = o[e];
   }
   return a;
}


///////////////////////////////////////////////////////
// ShowArguments("argu1", "argu2", "argu3");
// !!! This is an example of showing the arguments.
function showArgs(){
   var a =showArgs.arguments;
   var s='';
   for(var i=0; i<a.length; i++){
      s += '(' + i + ')' + a[i] + '\r ';
   }
   alert(s);
}

function dW(s){
   document.write(s);
}

function hideId(id){
   var obj = fetchObject(id);
   if (obj)
     obj.style.display = 'none';
}

function showId(id){
   var obj = fetchObject(id);
   if (obj){
      if ( obj.nodeName == 'SPAN'){
           obj.style.display = 'inline';
      }
      else{
         obj.style.display = 'block';
      }
   }
}

////////////////////////////////////////////////
// The following 2 functions work together.
// The first one is a class contains 4 functions.
// The second one calls the first one and its
// one function getVale(by query key)
function PageQuery(q) {
   if(q.length > 1) this.q = q.substring(1, q.length);
   else this.q = null;

   this.keyValuePairs = new Array();

   if(q) {
      for(var i=0; i < this.q.split("&").length; i++) {
         this.keyValuePairs[i] = this.q.split("&")[i];
      }
   }

   this.getKeyValuePairs = function() {
      return this.keyValuePairs;
   }
   this.getValue = function(s) {
      for(var j=0; j < this.keyValuePairs.length; j++) {
         if(this.keyValuePairs[j].split("=")[0] == s)
         return this.keyValuePairs[j].split("=")[1];
      }
      return false;
   }
   this.getParameters = function() {
      var a = new Array(this.getLength());
      for(var j=0; j < this.keyValuePairs.length; j++) {
         a[j] = this.keyValuePairs[j].split("=")[0];
      }
      return a;
   }
   this.getLength = function() {
      return this.keyValuePairs.length;
   }
}
function queryString(key){

   var page = new PageQuery(window.location.search);
   var val = unescape(decodeURI(page.getValue(key)));
   if (val == 'false'){
      return '';
   }
   return val;
}


//EX: location = http://www.google.com/en/index.html?q=keyword&q1=query1
//uri.dom   = www.google.com
//uri.dir   = http://www.google.com/en
//uri.path  = en
//uri.page  = index
//uri.ext   = html
//uri.file  = index.html
//uri.arges = q=keyword&q1=query1

function getURLInfo() {
   var uri = new Object();
   uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
   uri.dom = uri.dir;
   if (uri.dom.substr(0, 7) == 'http:\/\/') uri.dom = uri.dom.substr(7);
   uri.path = '';
   var pos = uri.dom.indexOf('\/');
   if (pos > - 1) {
      uri.path = uri.dom.substr(pos + 1);
      uri.dom = uri.dom.substr(0, pos);
   }
   uri.page = location.href.substring(uri.dir.length + 1, location.href.length + 1);
   pos = uri.page.indexOf('?');
   if (pos > - 1) {
      uri.page = uri.page.substring(0, pos);
   }
   pos = uri.page.indexOf('#');
   if (pos > - 1) {
      uri.page = uri.page.substring(0, pos);
   }
   uri.ext = '';
   pos = uri.page.indexOf('.');
   if (pos > - 1) {
      uri.ext = uri.page.substring(pos + 1);
      uri.page = uri.page.substr(0, pos);
   }
   uri.file = uri.page;
   if (uri.ext != '') uri.file += '.' + uri.ext;
   if (uri.file == '') uri.page = 'index';
   uri.args = location.search.substr(1).split("?");
   return uri;
}

//get query array
//EX: http://www.google.com/index.html?q=keyword
//var ary = getQueryArray();
//ary['q'] = 'keyword'
function getQueryArray() {
   var qsParm = new Array();
   var query = window.location.search.substring(1);
   var parms = query.split('&');
   for (var i=0; i<parms.length; i++) {
      var pos = parms[i].indexOf('=');
      if (pos > 0) {
         var key = parms[i].substring(0,pos);
         var val = parms[i].substring(pos+1);
         qsParm[key] = val;
      }
   }
   return qsParm;
}

////////////////////////////////////////////////
// Show the variavles in the query string
// var text = "name=Broch&age=20&hair=blonde";
// showVariables(text);
function showQueryVariables(text){
   var keys = text.split(/&/);
   for (var i = 0; i < keys.length; i++) {
      var data = keys[i].split(/=/);
      document.writeln( data[0] + ' = ' + data[1] + '<br>');
   }
}


function simpleSize(filelen){
   var olen;
   if ( filelen > 1024 * 1024*1024*1024){
      olen = Math.floor(filelen * 10/ 1024 /1024/1024/ 1024) / 10;
      olen = olen + "TB";
   }else if ( filelen > 1024 * 1024 *1024){
      olen = Math.floor(filelen * 10/ 1024 / 1024 /1024) / 10;
      olen = olen + "GB";
   }else if ( filelen > 1024 * 1024){
      olen = Math.floor(filelen * 10/ 1024 / 1024) / 10;
      olen = olen + "MB";
   }else if ( filelen > 1024 ){
      olen = Math.floor(filelen * 10/ 1024) / 10;
      olen = olen + "KB";
   }else{
      olen = filelen + "B";
   }
   return olen;
}

function contactUs(subj){
   var hrf = "ma"+"ilto"+":info@"+"dealscheck.com";
   if ( typeof(subj) != 'undefined' ){
      hrf += "?subject="+encodeURI(subj);
   }
   document.location.href = hrf;
}

function myRand(min, max){
   return ( min + Math.floor( Math.random() * (max - min) ) );
}

function isCookieEnabled(){
   return navigator.cookieEnabled;
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a 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));
}

/**
 * Deletes the specified cookie.
 *
 * 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)
 */
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";
    }
}

var numb = '0123456789';
var lwr  = 'abcdefghijklmnopqrstuvwxyz';
var upr  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function isValid(s,val) {
  if (s == "") return true;
  for (i=0; i<s.length; i++) {
    if (val.indexOf(s.charAt(i),0) == -1) return false;
  }
  return true;
}

function isNum(s)       {return isValid(s,numb);}     //function isNum(s){   return   /[^\d]/.test(s) ? false : true; }
function isLower(s)     {return isValid(s,lwr);}
function isUpper(s)     {return isValid(s,upr);}
function isAlpha(s)     {return isValid(s,lwr+upr);}
function isAlphanum(s)  {return isValid(s,lwr+upr+numb);}
function isDecimal(s)   {return isValid(s,numb+'.');}

//: matches all occurrences of three equal non-whitespace characters following each other.
//EX: ArrayShow(getTriples("<b hrdfdffffef=>adf</444a>asdfffsdf"));
function getTriples(str){
   re = /(\S)\1\1/gi;
   return str.match(re);
}

//: get all the tags.
//EX: ArrayShow(anyTags("<b href=>adf</a>"));
function anyTags(html){
   re =  /<(\S+).*>(.*)<\/\1>/;
   return html.match(re);
}

function getMouseX(e) {
   
   if (isIE) {
      tempX = event.clientX + document.documentElement.scrollLeft;
   }
   else {
      tempX = e.pageX;
   }
   if (tempX < 0){tempX = 0;}
   return tempX;
}

function getMouseY(e) {
   
   if (isIE) {
      tempY = event.clientY + document.documentElement.scrollTop;
   }
   else {
      tempY = e.pageY;
   }
   if (tempY < 0){tempY = 0;}
   return tempY;
}

//2006/10/25:
//Check the keycode is arrow keys or delete key
//IE: event.keyCode;
function is_edit_key(k){
   var ary = new Array(8, 37, 39, 46, 35, 36);
   for(var a in ary){
      if(k==ary[a]) return true;
   }
   return false;
   //if(event.keyCode!=8 && event.keyCode!=37 && event.keyCode!=39 && event.keyCode!=46 && event.keyCode!=35 && event.keyCode!=36) return false;
   //else return true;
}

//onKeyUp="javascript:if(!is_edit_key(event.keyCode)) return mask_general(this.value,this,'3,6','//');"
//onBlur="javascript:if(!is_edit_key(event.keyCode)) return mask_general(this.value,this,'3,6','/-');"
function mask_general(str,textbox,loc,delim){

   str = str.replace(/\D/g,"");

   if(delim == null) delim = '/';

   var locs = loc.split(',');
   var dels = delim.split('');

   if(dels.length < locs.length){
      for(var i=0; i<= locs.length - dels.length; i++){
         dels.push(dels[0]);
      }
   }

   for (var i = 0; i <= locs.length; i++){
      for (var k = 0; k <= str.length; k++){
         if (k == locs[i]){
            if (str.substring(k, k+1) != dels[i]){
               str = str.substring(0,k) + dels[i] + str.substring(k,str.length)
            }
         }
      }
   }
   textbox.value = str;

   var re = /\d{2}\/\d{2}\/\d{4}/;
   if(re.test(str)==true) {
      if(!isValidDate(str)){
         alert('Invalid date!');
         textbox.style.backgroundColor='#ffcccc';
         textbox.focus();
      }
      else{
         textbox.style.backgroundColor='#ffffff';
      }
   }
}

//2008-12-28
function loadImage(url, callback) {

    var img = new Image(); //创建一个Image对象，实现图片的预下载
    img.src = url;
   
    if (img.complete) { // 如果图片已经存在于浏览器缓存，直接调用回调函数
        callback.call(img);
        return; // 直接返回，不用再处理onload事件
    }

    img.onload = function () { //图片下载完毕时异步调用callback函数。
        callback.call(img);//将回调函数的this替换为Image对象
    };
};
