function open_popup(url, window_name, options)
{
	window.open(url, window_name, options);
}

function returnObjById( id ) 
{ 
	if (document.getElementById) 
		var returnVar = document.getElementById(id); 
	else if (document.all) 
		var returnVar = document.all[id]; 
	else if (document.layers) 
		var returnVar = document.layers[id]; 
	return returnVar; 
}

var checkflag = 'false';
function checkAll(field)
{
	if (checkflag == 'false')
	{
		var elems = document.getElementsByName(field);
		for (i = 0; i < elems.length; i++)
		{
			elems[i].checked = true;
		}
		checkflag = 'true';
	}
	else {
		var elems = document.getElementsByName(field);
		for (i = 0; i < elems.length; i++)
		{
			elems[i].checked = false;
		}
		checkflag = "false";
	}
}

function checkBoxAll(field)
{
	var elems = document.getElementsByName(field);
	for (i = 0; i < elems.length; i++)
	{
		elems[i].checked = true;
	}
}

function uncheckBoxAll(field)
{
	var elems = document.getElementsByName(field);
	for (i = 0; i < elems.length; i++)
	{
		elems[i].checked = false;
	}
}

/* XML LIB */
/*
	url: URL to load
	ready_function: function to call when ready
	
	SAMPLE CODE:
	var req;
	function loadXMLDoc() {
		req = loadXMLFile('my_url.xml', 'processRequestedXML');
	}
	function processRequestedXML()
	{
		var the_id = req.responseXML.getElementsByTagName("tagname")[i].getAttribute('id');
		var my_tag = req.responseXML.getElementsByTagName("my_tag")[0].firstChild.data;
	}

*/

function loadXMLFile(url, ready_function) {
	var r = false;
    /* branch for native XMLHttpRequest object */
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			r = new XMLHttpRequest();
        } catch(e) {
			r = false;
        }
    /* branch for IE/Windows ActiveX version */
    } else if(window.ActiveXObject) {
       	try {
        	r = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		r = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		r = false;
        	}
		}
    }
	if(r) {
		r.onreadystatechange = function()
		{
			if (r.readyState == 4) {
				if (r.status == 200) {
					window[ready_function]();
				}
			}
		}
		r.open("GET", url, true);
		if(r.overrideMimeType)
		{
			r.overrideMimeType("text/xml");
		}
		r.send("");
	}
	return r;
}

function getXMLTagInfo(xml_request, tagname, i, attribute)
{
	if(attribute != '')
	{
		var info = xml_request.responseXML.getElementsByTagName(tagname)[i].getAttribute(attribute);
	}
	else
	{
		var info = xml_request.responseXML.getElementsByTagName(tagname)[i].firstChild.data;
	}
	return info;
}

/**
 * SWFObject v1.4.1: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.createElement||!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
var _25=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=3;axo!=null;i++){axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);_25=new deconcept.PlayerVersion([i,0,0]);}}
catch(e){}
if(_23&&_25.major>_23.major){return _25;}
if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
catch(e){}}}return _25;};
deconcept.PlayerVersion=function(_29){
this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
this.minor=parseInt(_29[1])||0;
this.rev=parseInt(_29[2])||0;};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}return true;};
deconcept.util={getRequestParameter:function(_2b){
var q=document.location.search||document.location.hash;
if(q){var _2d=q.indexOf(_2b+"=");
var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
if(q.length>1&&_2d>-1){return q.substring(q.indexOf("=",_2d)+1,_2e);}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){
var _2f=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2f.length;i++){
for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=null;}}}};
if(typeof window.onunload=="function"){
var oldunload=window.onunload;
window.onunload=function(){deconcept.SWFObjectUtil.cleanupSWFs();oldunload();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}
if(Array.prototype.push==null){
Array.prototype.push=function(_32){
this[this.length]=_32;
return this.length;};}

var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for backwards compatibility
var SWFObject = deconcept.SWFObject;

function getHTTPObject()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
	try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
		xmlhttp = false;
	  }
	}
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	try {
	  xmlhttp = new XMLHttpRequest();
	} catch (e) {
	  xmlhttp = false;
	}
  }
  return xmlhttp;
}

function getContent(url,location) {
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('GET', url,true);
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			document.getElementById(location).innerHTML = xObj.responseText;
			if(xObj.responseText.indexOf('<' + 'script') != -1) {
				beginning = xObj.responseText.indexOf('<' + 'script');
				beginning = xObj.responseText.indexOf('>',beginning) + 1;
				ending = xObj.responseText.indexOf('</' + 'script')-1;
				scriptText = xObj.responseText.substring(beginning, ending);
				eval(scriptText);
			}
		}
	}
	xObj.send(null)
}

function postContent(url,location, post_string) {
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('POST', url,true);
	xObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			document.getElementById(location).innerHTML = xObj.responseText;
			if(xObj.responseText.indexOf('<' + 'script') != -1) {
				beginning = xObj.responseText.indexOf('<' + 'script');
				beginning = xObj.responseText.indexOf('>',beginning) + 1;
				ending = xObj.responseText.indexOf('</' + 'script')-1;
				scriptText = xObj.responseText.substring(beginning, ending);
				eval(scriptText);
			}
		}
	}
	xObj.send(post_string)
}//Image Uploader detection
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
    document.writeln('<scr' + 'ipt language="VBscript">');
    document.writeln('Function supportImageUploader()');        
    document.writeln('  If ScriptEngineMajorVersion >= 2 Then');    
    document.writeln('      On Error Resume Next');
    document.writeln('      supportImageUploader = "NotInstalled"');    
    document.writeln('      Dim installed');
    document.writeln('      installed = False');
    document.writeln('      installed = IsObject(CreateObject("Aurigma.ImageUploader4"))');
    document.writeln('    If installed Then');
    document.writeln('      supportImageUploader = "Installed"');
    document.writeln('    End If');        
    document.writeln('    Else');
    document.writeln('    supportImageUploader = "Unsupported"');
    document.writeln('    End If');
    document.writeln('End Function');
    document.writeln('</scr' + 'ipt>');
}
else {
    document.writeln('<scr' + 'ipt language="JavaScript">');
    document.writeln('function supportImageUploader() {');
    document.writeln('    return "Unsupported";');
    document.writeln('}');
    document.writeln('</scr' + 'ipt>');
}

//Make all buttons disabled whenever a form is submitted
function initForms() {
  var objForms = document.forms;
  for(f=0;f<objForms.length;f++) {
    el = objForms[f];
    if (el.addEventListener) {
//      el.addEventListener ("submit",disableSubmit,false);
    } else if (el.attachEvent) {
//      el.attachEvent ("onsubmit",disableSubmit);
    } else {
//      el.onsumbit = disableSubmit;
    }
  }
}
window.setTimeout("initForms()", 100);   

//Iterates through the form objects and disables the submit buttons
function disableSubmit() {
    objForms = document.forms;
    for(f=0;f<objForms.length;f++) {
  	  objElems = objForms[f].elements;
  	  for(i=0;i<objElems.length;i++){
  	    if(objElems[i].type == "submit" || objElems[i].type == "button") {
  		    objElems[i].disabled = true;
  	    }
  	  }
  	}
}

//Iterates through the form objects and disables the submit buttons
function enableSubmit() {
    objForms = document.forms;
    for(f=0;f<objForms.length;f++) {
  	  objElems = objForms[f].elements;
  	  for(i=0;i<objElems.length;i++){
  	    if(objElems[i].type == "submit" || objElems[i].type == "button") {
  		    objElems[i].disabled = false;
  	    }
  	  }
  	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}

///Validation functions
function validateCompleteForm (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 0);
};

function validateStandard (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 1);
};

/***************************************************************
** Internal functions
*****************************************************************/
function _validateInternal(form, strErrorClass, nErrorThrowType){
   var strErrorMessage = ""; var objFirstError = null;
   if (nErrorThrowType == 0){
    strErrorMessage = (form.err) ? form.err : _getLanguageText("err_form");
   };

   var fields = _GenerateFormFields(form);
   for (var i = 0; i < fields.length; ++i){
      var field = fields[i];
      if (!field.IsValid(fields)){
        field.SetClass(strErrorClass);
        if (nErrorThrowType == 1) {
            _throwError(field);
            enableSubmit();
            return false;
        }else{
            if (objFirstError == null){
               objFirstError = field;
            }
            strErrorMessage = _handleError (field, strErrorMessage);
            bError = true;
        }
      } else {
      	field.ResetClass();
      }
   };
   if (objFirstError != null) {
      alert(strErrorMessage);
      objFirstError.element.focus();
      enableSubmit();
      return false;
  };
  disableSubmit();
  return true;
 };
 
 function _getLanguageText(id){
    objTextsInternal = new _jsVal_Language();
    objTexts = null;
    try {
        objTexts = new jsVal_Language();
    } catch (ignored){};
    switch (id) {
        case "err_form": strResult = (!objTexts || !objTexts.err_form) ? objTextsInternal.err_form : objTexts.err_form; break;
        case "err_enter": strResult = (!objTexts || !objTexts.err_enter) ? objTextsInternal.err_enter : objTexts.err_enter; break;
        case "err_select": strResult = (!objTexts || !objTexts.err_select) ? objTextsInternal.err_select : objTexts.err_select; break;
    };
    return strResult;
 };

 function _GenerateFormFields(form){
   var arr = new Array();
   for (var i = 0; i < form.length; ++i){
      var element = form.elements[i];
      
      
      var index = _getElementIndex(arr,element);
      //if it doesn't already exist, add it to our array, else merge the change
      if (index == -1){
         arr[arr.length] = new Field(element, form);
      }else{
         arr[index].Merge(element)
      };
   };
   return arr;
};

function _getElementIndex(arr, element){
   if (element.name) {
       var elementName = element.name.toLowerCase();
       for (var i = 0; i < arr.length; ++i){
       	  if (arr[i].element.name) { 
			   if (arr[i].element.name.toLowerCase() == elementName){
               	  return i;
               }
          };
       };
   }
   return -1;
};

/***************************************************************
** Standard translation
*****************************************************************/
function _jsVal_Language() {
    this.err_form = "Please enter/select values for the following fields:\n\n";
    this.err_select = "Please select a valid \"%FIELDNAME%\"";
    this.err_enter = "Please enter a valid \"%FIELDNAME%\"";
};

/***************************************************************
** Field Class
*****************************************************************/
function Field(element, form){
   this.type = element.type;
   this.element = element;
   this.exclude = element.exclude || element.getAttribute('exclude');
   this.err = element.err || element.getAttribute('err') || element.getAttribute('error');
   this.required = _parseBoolean(element.required || element.getAttribute('required'));
   this.realname = element.realname || element.getAttribute('realname');
   this.elements = new Array();
   
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         this.value = element.value;
         this.minLength = element.minlength || element.getAttribute('minlength');
         this.maxLength = element.maxlength || element.getAttribute('maxlength');
         this.regexp = this._getRegEx(element);
         this.minValue = element.minvalue || element.getAttribute('minvalue');
         this.maxValue = element.maxvalue || element.getAttribute('maxvalue');
         this.equals = element.equals || element.getAttribute('equals');
         this.callback = element.callback || element.getAttribute('callback');
		 if(this.element.className != "error")
		 {this.element.oldClassName = this.element.className;}
         break;
      case "select-one":
      case "select-multiple":
         this.values = new Array();
         for (var i = 0; i < element.options.length; ++i){
            if (element.options[i].selected && (!this.exclude || element.options[i].value != this.exclude)){
               this.values[this.values.length] = element.options[i].value;
            }
         }
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         this.equals = element.equals || element.getAttribute('equals');
         break;
      case "checkbox":
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         //no break, let it fall through to radio
      case "radio":
          this.required = _parseBoolean(this.required || element.getAttribute('required'));
          this.values = new Array();
          if (element.checked){
             this.values[0] = element.value;
          }
   		         
          this.elements[0] = element;
          break;
   };
};
Field.prototype.Merge = function(element){
   //never negate a require field
   var required = _parseBoolean(element.getAttribute('required'));
   if (required){
      this.required = true;
   };
   //all other cases (except required) we only add if there isn't already a value (first come first served)
   if (!this.err){
      this.err = element.getAttribute('err');
   };
   if (!this.error){
      this.err = element.getAttribute('error');
   };
   if (!this.equals){
   	  this.equals = element.getAttribute('equals');
   };
   if (!this.callback){
   	  this.callback = element.getAttribute('callback');
   };
   if (!this.realname){
      this.realname = element.getAttribute('realname');
   };
   if (!this.max){
      this.max = element.getAttribute('max');
   };
   if (!this.min){
      this.min = element.getAttribute('min');
   };
   if (!this.regexp){
      this.regexp = this._getRegEx(element);
   };
   if (element.checked){
      this.values[this.values.length] = element.value;
   };
   this.elements[this.elements.length] = element;
};
Field.prototype.IsValid = function(arrFields){
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         return this._ValidateText(arrFields);
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         return this._ValidateGroup(arrFields);
      default:
         return true;
   };
};
Field.prototype.SetClass = function(newClassName){
   if ( (newClassName) && (newClassName != "") ) {
       if ( (this.elements) && (this.elements.length > 0)) {
          for (var i = 0; i < this.elements.length; ++i){
          	  if(this.elements[i].className != newClassName){
                this.elements[i].oldClassName = this.elements[i].className;
                this.elements[i].className = newClassName;
              }
          }
       }else{
       	  if(this.element.className != newClassName){
            this.element.oldClassName = this.element.className;
            this.element.className = newClassName;
          }
       };
   }
};
Field.prototype.ResetClass = function(){
	if ( (this.type != "button") && (this.type != "submit") && (this.type != "reset") &&this.type != "radio" ) {
   		if ( (this.elements) && (this.elements.length > 0)) {
      		for (var i = 0; i < this.elements.length; ++i){
      			if(this.elements[i].oldClassName){
         	 	  this.elements[i].className = this.elements[i].oldClassName;
         	 	}
         	 	else {
    	  	 	  this.element.className = "";
    	  		}
      		}
   		}else{
   			if(this.element.oldClassName){
    	  	  this.element.className = this.element.oldClassName;
    	  	}
    	  	else {
    	  	  this.element.className = "";
    	  	}
   		};
	};
};
Field.prototype._getRegEx = function(element){
   regex = element.regexp || element.getAttribute('regexp')
   if (regex == null) return null;
   retype = typeof(regex);
   if (retype.toUpperCase() == "FUNCTION")
       return regex;
   else if ( (retype.toUpperCase() == "STRING") && !(regex == "JSVAL_RX_EMAIL") && !(regex == "JSVAL_RX_TEL")
   				&& !(regex == "JSVAL_RX_PC") && !(regex == "JSVAL_RX_ZIP") && !(regex == "JSVAL_RX_MONEY") 
				&& !(regex == "JSVAL_RX_CREDITCARD") && !(regex == "JSVAL_RX_POSTALZIP") && !(regex == "JSVAL_RX_DATE") && !(regex == "JSVAL_ALPHA_NUMERIC") && !(regex == "JSVAL_NAME") && !(regex == "JSVAL_ALPHA_NUMERIC_STRICT") && !(regex == "JSVAL_FILE_JPG") && !(regex == "JSVAL_ALPHA_NUMERIC_LIMITED_CHARS") && !(regex == 'JSVAL_ALPHA_NUMERIC_LIMITED_CHARS_PLUS_AMP'))
   {
       nBegin = 0; nEnd = 0;
       if (regex.charAt(0) == "/") nBegin=1;
       if (regex.charAt(regex.length-1) == "/") nEnd=0;
	   
       return new RegExp(regex.slice(nBegin, nEnd));
   }
   else {
       return regex;
   };
};
Field.prototype._ValidateText = function(arrFields){
   if ( (this.required) && (this.callback) ) {
   	  nCurId = this.element.id ? this.element.id : "";
   	  nCurName = this.element.name ? this.element.name : "";
   	  
   	  eval("bResult = "+this.callback+"('"+nCurId+"', '"+nCurName+"', '"+this.value+"');"); 
   	  if (bResult == false) {
   	  	 return false;
   	  };
   } else {	
	   //required value is empty
	   if (this.required && !this.value){
	      return false;
	   };
	   //value less than minlength
	   if (this.value && (this.minLength && this.value.length < this.minLength)){
	      return false;
	   };
	   //value is more than maxlength
	   if (this.value && (this.maxLength && this.value.length > this.maxLength)){
	      return false;
	   };
	   //value fails regular expression
	   if (this.regexp){
	   	  if (!_checkRegExp(this.regexp, this.value))
	   	  {
	   	  	  //the field isn't required, but there is a value
		      if (!this.required && this.value){
		         return false;
		      }
		      if (this.required){
		         return false;
		      }
	   	  }
	   	  else
	   	  {
	   	  	return true;
	   	  };
	   };
	   
	   
	   
	   //check equality
	   if (this.equals){
	   	   for (var i = 0; i < arrFields.length; ++i){
	       	   var field = arrFields[i];
	       	   if ( (field.element.name == this.equals) || (field.element.id == this.equals) ) {
	       	   	  if (field.element.value != this.value) {
	       	   	  	 return false;
	       	   	  };
	       	   	  break;
	       	   };
	       };
	   };
	   
	   //check against minvalue and maxvalue
	   if (this.required){
	      var fValue = parseFloat(this.value);
	      if ((this.minValue || this.maxValue) && isNaN(fValue)){
	         return false;
	      };
	      if ( (this.minValue) && (fValue < this.minValue) ) {
	         return false;
	      };
	      if ( (this.maxValue) && (fValue > this.maxValue) ) {
	         return false
	      };
	   };
   }
   return true;
};
Field.prototype._ValidateGroup = function(arrFields){
   if (this.required && this.values.length == 0){
      return false;
   };
   if (this.required && this.min && this.min > this.values.length){
      return false;
   };
   if (this.required && this.max && this.max < this.values.length){
      return false;
   };
   return true;
};

function _handleError (field, strErrorMessage) {
   var obj = field.element;
   strNewMessage = strErrorMessage + ( (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name) ) + "\n";
   return strNewMessage;
};

function _throwError(field){
   var obj = field.element;
   switch (field.type){
      case "file":
	  	updateStatus("error");
	  case "text":
      case "password":
      case "textarea":
         alert(_getError(field, "err_enter"));
         try {
         	obj.focus();
         }
         catch (ignore) {}
         break;
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         alert(_getError(field, "err_select"));
         break;
      };
};

function _getError(field, str){
   var obj = field.element;
   strErrorTemp = (field.err) ? field.err : _getLanguageText(str);
   
   idx = strErrorTemp.indexOf( "\\n" );
   while ( idx > -1 ) {
   	strErrorTemp = strErrorTemp.replace( "\\n", "\n" );
    idx = strErrorTemp.indexOf( "\\n" );
   };
   
   return strErrorTemp.replace("%FIELDNAME%", (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name));
};

function _parseBoolean(value){
   return !(!value || value == 0 || value == "0" || value == "false");
};

function _checkRegExp(regx, value){
  switch (regx){
  case "JSVAL_RX_EMAIL":
    //return ((/^[a-zA-Z\d-]+([\.-_]?[a-zA-Z\d]+)*@[a-zA-Z\d-]+([\.-_]?[a-zA-Z\d]+)*(\.\w{2,5})+$/).test(value));
  	return ((/^[a-zA-Z0-9._\-]+([.][a-zA-Z0-9_\-]+)*[@][a-zA-Z0-9_\-]+([.][a-zA-Z0-9_\-]+)*[.][a-zA-Z]{2,4}$/).test(value));
  case "JSVAL_RX_TEL":
  	return ((/^[0-9\+ ()\-.]*$/).test(value));
    //return ((/^1?[\- ]?\(?\d{3}\)?[\- ]?\d{3}[\- ]?\d{4}$/).test(value));
  case "JSVAL_RX_PC":
    return ((/^[a-z]\d[a-z] ?\d[a-z]\d$/i).test(value));
  case "JSVAL_RX_ZIP":
  	return(/^[A-Za-z0-9 \-]*$/.test(value));
    //return ((/^\d{5}$/).test(value));
  case "JSVAL_RX_MONEY":
    return ((/^\d+([\.]\d\d)?$/).test(value));
  case "JSVAL_RX_CREDITCARD":
    return (!isNaN(value));
  case "JSVAL_RX_POSTALZIP":
    if(value.length == 6 || value.length == 7)
      return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
    if(value.length == 5 || value.length == 10)
      return((/^\d{5}(\-\d{4})?$/).test(value));
    break;
  case "JSVAL_FILE_JPG":
    return ((/[A-Za-z\\/ :\d_\-\.]*.((j|J)(p|P)(e|E)?(g|G))$/).test(value));
  case "JSVAL_RX_DATE":
    return((/^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/).test(value));
  case "JSVAL_ALPHA_NUMERIC":
    return(!(/[^A-Za-z0-9\- ']/).test(value));
  case "JSVAL_ALPHA_NUMERIC_STRICT":
    return(!(/[^A-Za-z0-9]/).test(value));
  case "JSVAL_NAME":
    return(!(/[^A-Za-z0-9\&\- ']/).test(value));
  case "JSVAL_ALPHA_NUMERIC_LIMITED_CHARS":
    return(!(/[^A-Za-z0-9\- ,']/).test(value));
  case "JSVAL_ALPHA_NUMERIC_LIMITED_CHARS_PLUS_AMP":
    return(!(/[^A-Za-z0-9\-\& ,']/).test(value));
  default:
    return (regx.test(value));

  };
};

function validatePassword(value) {
  return (value.length >= 1 && value.length <= 30 && !(/[^A-Za-z0-9]/).test(value));
};

function showVideoUpload(family_id, title) {
	if(title == "") {
		alert("Title is required");
		return;
	}
	document.getElementById('nextbutton').style.display='none';
	//document.getElementById('titlerow').style.display='none';
	document.getElementById('video_title').style.textAlign='left';
	document.getElementById('titlerow').disabled = true;
	//document.getElementById('uploadbutton').style.display='block';
	document.getElementById('uploadbutton').style.visibility='visible';
    mmSWFUpload.init({
      debug : false,
      //upload_backend : "/admin/video-upload.php?family_id="+family_id+"%26video_title="+title,
      upload_backend : "/admin/videos/?action=video-upload%26family_id="+family_id+"%26video_title="+title,
      target : "SWFUpload",
      //link_mode : "standalone",
      //link_text : "Upload",
      // css_class : "myCustomClass",
      allowed_filesize : "102400",
      allowed_filetypes : "*.mpg;*.mpeg;*.avi;*.wmv;*.flv;*.mov;*.mp4;*.3gp ;*.mpe;*.wmv9",
      upload_start_callback : 'uploadStart',
      upload_progress_callback : 'uploadProgress',
      upload_complete_callback : 'uploadComplete',
      upload_cancel_callback : 'uploadCancel',
      upload_queue_complete_callback : 'uploadQueueComplete'
      });	
}

function initVideoUpload(family_id) {
	//document.getElementById('nextbutton').style.display='none';
	//document.getElementById('titlerow').style.display='none';
	//document.getElementById('video_title').style.textAlign='left';
	//document.getElementById('titlerow').disabled = true;
	//document.getElementById('uploadbutton').style.display='block';
	//document.getElementById('uploadbutton').style.visibility='visible';
    mmSWFUpload.init({
      debug : false,
      ////upload_backend : "/admin/video-upload.php?family_id="+family_id+"%26video_title=temp",
      //upload_backend : "/admin/video-upload.php?family_id="+family_id,
      upload_backend : "/admin/videos/?action=video-upload&family_id="+family_id,
      target : "SWFUpload",
      //link_mode : "standalone",
      //link_text : "Upload",
      // css_class : "myCustomClass",
      allowed_filesize : "102400",
      allowed_filetypes : "*.mpg;*.mpeg;*.avi;*.wmv;*.flv;*.mov;*.mp4;*.3gp ;*.mpe;*.wmv9",
      upload_start_callback : 'uploadStart',
      upload_progress_callback : 'uploadProgress',
      upload_complete_callback : 'uploadComplete',
      upload_cancel_callback : 'uploadCancel',
      upload_queue_complete_callback : 'uploadQueueComplete',
      show_selected_name : 'showSelectedName',
      announce : 'announce'
      });	
}

function uploadVideoNow(title)
{
	newBackend = addVideoTitle(title);
	mmSWFUpload.editUploadBackend(newBackend);
	mmSWFUpload.startUpload();
}

function addVideoTitle(title)
{
	if(title == "") {
		alert("Title is required");
		return;
	}
	title = URLEncode(title);
	mmSWFUpload.settings["upload_backend"] = mmSWFUpload.settings["upload_backend"] + "&video_title="+title;
	//document.getElementById("videoSteps").src="./images/videoPostStep3.gif";
	document.getElementById("videoSteps").src="../shared/images/videoPostStep3.gif";
	return mmSWFUpload.settings["upload_backend"];
}

/*function $(id) {
	this.obj = document.getElementById(id);
	return this.obj;
}

$.prototype.ih = function() {
	
}*/

// Default upload start function.
var start = 0;
uploadStart = function(fileObj) {
	//document.getElementById('browsebutton').style.display='none';
	document.getElementById('browsebutton').disabled = true;
	document.getElementById('videouploadstatus').style.display='block';
	document.getElementById('filesDisplay').style.display='block';
	start = new Date().getTime();
	$("filesDisplay").style.display = "block";
		
	var li = document.createElement("li");
	li.style.fontSize="11pt";
	li.style.color="#333333";
	//var txt = document.createTextNode(fileObj.name);
	var txt = document.createTextNode("Uploading Progress");

	li.className = "uploading";
	li.id = fileObj.name;
	
	var prg = document.createElement("span");
	prg.id = fileObj.name + "progress";
	prg.className = "progressBar";
	//prg.style.marginTop="7px";
	prg.style.height="19px";
	prg.style.marginBottom="10px";

	var stat = document.createElement("span");
	stat.id = fileObj.name + "stat";
	
	li.appendChild(txt);
	li.appendChild(prg);
	li.appendChild(stat);

	$("mmUploadFileListing").appendChild(li);
}

uploadProgress = function(fileObj, bytesLoaded) {
	var progress = $(fileObj.name + "progress");
	var percent = Math.ceil((bytesLoaded / fileObj.size) * 300)
	//progress.style.background = "url(/admin/images/progressbar300.png) repeat-y -" + (300 - percent) + "px 0";
	progress.style.background = "url(../shared/images/progressbar300.png) repeat-y -" + (300 - percent) + "px 0";
	var stat = $(fileObj.name + "stat");
	stat.innerHTML = (Math.ceil(bytesLoaded / 1000)) + "/" +(Math.ceil(fileObj.size / 1000)) + " kb";
	if (bytesLoaded == fileObj.size) {
//		goOS('/admin/video-list.php','mac');
  	$(fileObj.name).className = "uploadDone";
  	var stat = $(fileObj.name + "stat");
  	stat.innerHTML = (Math.ceil(fileObj.size / 1000)) + " kb";
  	alert("Video file "+fileObj.name+" uploaded.");
		document.getElementById('spinner').style.display='block';
		window.setTimeout("goPreview()", 5000);
	}
	var duration = Math.ceil((new Date().getTime()) - start) / 1000;
	if (bytesLoaded > 0 && duration > 2) {
		duration = duration / bytesLoaded;
		duration = duration * (fileObj.size - bytesLoaded);
		var hours = Math.floor(duration / 3600);
		duration -= hours * 3600;
		var minutes = Math.floor(duration / 60);
		duration -= minutes * 60;
		var seconds = Math.ceil(duration);
		stat.innerHTML += "<hr/>Time Left:<br/> "+(hours < 10 ? "0" : "")+hours+" hours<br/> "+(minutes < 10 ? "0" : "")+minutes+" minutes<br/> "+(seconds < 10 ? "0" : "")+seconds+" seconds";
	}
}

function goPreview() {
  	//location.href = "/admin/videopreview.php";
  	location.href = "/admin/videos/?action=videopreview";	
}

uploadQueueComplete = function(fileObj) {
}

uploadComplete = function(fileObj) {
}


uploadCancel = function() {
	//location.href = "/admin/video-list.php";
	location.href = "/admin/videos/?action=video-list";
}

showSelectedName = function(name){
	document.getElementById('filename').innerHTML = "File for upload: " + "<span style='font-weight:bold'>" +name + "</span>";
}

announce = function(arg){
	//console.log("announce: " + arg);
}

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

	var plaintext = string;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// 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
};

/* Send the Aurigma upload error to the dev team for analysis */
function sendUploaderError(the_error)
{
	var url = '/admin/shared/M/alert-upload-error.php';
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('POST', url,true);
	xObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			//alert(the_error);
		}
	}
	xObj.send(the_error)
}

/* load thumbnail no-cache image after editing with PhotoEditor */
function loadNoCacheImage(img_path, div_id, props)
{
	var the_div = document.getElementById(div_id);
	the_div.innerHTML = '<img src="' + img_path + '?rand=' + Math.random() + '" border="0" ' + props + ' />';
}

/* WESTGATE/KK - check for new photos uploaded by barcode */
var vertical;
var reqPH;
var barcode = '';
var customer_code = '';
var t = '';
function loadPhotoupdateXMLDoc(the_barcode, uid)
{
	if(vertical == 'kiddiekandids')
	{
		customer_code = the_barcode;
		if(customer_code.length > 0)
		{
			reqPH = loadXMLFile('/API/photos/kk2album_kick/' + customer_code + '/' + uid + '?t=' + t, 'processPhotoupdateReqChange');
		}
	}
	else
	{
		barcode = the_barcode;
		if(barcode.length > 0)
		{
			reqPH = loadXMLFile('/API/photos/q2album_kick/' + barcode + '/' + uid, 'processPhotoupdateReqChange');
		}
	}
}

function processPhotoupdateReqChange()
{
	var the_status = reqPH.responseXML.getElementsByTagName("status")[0].firstChild.data;
	var the_msg = reqPH.responseXML.getElementsByTagName("msg")[0].firstChild.data;
	if(the_status == 'Failed')
	{
		alert(the_msg);
	}
	else if(the_status == 'OK')
	{
		//alert('Your photos have been processed!');
		loadPhotoprogressXMLDoc();
	}
	else
	{
		alert('An error occurred trying to process the photos.');
	}
}

function hidePhotoupdateReqChange()
{

}

var pr = '';
var reqPR;
var total_count = 0;
var from = '';
function loadPhotoprogressXMLDoc() {
	if(vertical == 'kiddiekandids')
	{
		if(customer_code.length > 0)
		{
			reqPR = loadXMLFile('/API/photos/kkcounter/' + customer_code + '?r=' + Math.random(), 'processPhotoprogressReqChange');
		}
		else
		{
			if(from == 'check_sitting')
			{
				loadSitepostThumbs();
			}
		}
	}
	else
	{
		if(barcode.length > 0)
		{
			reqPR = loadXMLFile('/API/photos/qcounter/' + barcode, 'processPhotoprogressReqChange');
		}
	}
}

function displayPleaseWait()
{
	tb_show('','/admin/dashboard/M/kiddiekandids_pleasewait.php?keepThis=true&amp;TB_iframe=true&amp;height=400&amp;width=650',null);
}

var please_wait_message_displayed = 0;
function processPhotoprogressReqChange()
{
	var total_count = 0;
	var the_total = reqPR.responseXML.getElementsByTagName("total")[0].firstChild.data;
	var the_processed = reqPR.responseXML.getElementsByTagName("processed")[0].firstChild.data;
	var the_percent = reqPR.responseXML.getElementsByTagName("percentage")[0].firstChild.data;
	var photocounter = returnObjById('photocounter');
	var remaining = reqPR.responseXML.getElementsByTagName("remaining")[0].firstChild.data;
	var is_downloading = getXMLTagInfo(reqPR, 'is_downloading', 0, '');
	if(photocounter)
	{
		photocounter.innerHTML = 'Processing ' + the_processed + ' of ' + the_total + ' photos...';
	}
	var progressbar = returnObjById('progressbar');
	if(progressbar)
	{
		progressbar.style.width = the_percent + '%';
	}
	total_count += the_total;

	// display downloading message
	if(vertical == 'kiddiekandids')
	{
		if(total_count > 0 && please_wait_message_displayed < 1)
		{
			//alert('please wait');
			//tb_show('','/admin/dashboard/M/kiddiekandids_pleasewait.php?keepThis=true&amp;TB_iframe=true&amp;height=540&amp;width=700',null);
			please_wait_message_displayed = 1;
			var t = setTimeout('displayPleaseWait()', 100);
		}
	}
	
	if(is_downloading == 0)
	{
		if(from == 'check_sitting')
		{
			loadSitepostThumbs();
		}
		else
		{	
			clearInterval(pr);
			var loadingdiv = returnObjById('checkingphotos');
			if(vertical == 'kiddiekandids')
			{
				//reloadPreviews();
				if(total_count > 0)
				{
					if(loadingdiv)
					{
						loadingdiv.innerHTML = 'Please wait while we process your photos...';
					}
					var reloadP = setTimeout('reloadPreviews()', 3000);
				}
				else
				{
					if(loadingdiv)
					{
						loadingdiv.style.display = 'none';
					}
				}
			}
			else if(total_count > 0)
			{
				if(loadingdiv)
				{
					loadingdiv.style.display = 'none';
				}
				if(confirm('New photos were found! Click OK to view the new album.'))
				{
					document.location.href = document.location.href + '?skipcheck=1';
				}
			}
		}
	}
}

var first_visit = false;
function reloadPreviews()
{
	/*var loadingdiv = returnObjById('checkingphotos');
	if(loadingdiv)
	{
		loadingdiv.innerHTML = 'Loading photos...';
		loadingdiv.style.display = 'none';
	}*/
	//previewTheme(document.dashboard_form.themeID.value);
	//window.location.href = window.location.href;
	
	// redisplay flash preview
	themeID = document.dashboard_form.themeID.value;
	previewTheme(themeID);
}

function checkProcessProgress()
{
	loadPhotoprogressXMLDoc();
	pr = setInterval('loadPhotoprogressXMLDoc()', 5000);
}

function checkPhotoProcessProgress()
{
	pr = setInterval('loadPhotoprogressXMLDoc()', 2000);
}

function confirmTipsDisplay(act)
{
	var url = '/admin/shared/M/set-tips.php?act=' + act;
	var xObj = false;
	
	if(act == 'show')
	{
		if(confirm('Are you sure you want to turn on helper tips?'))
		{
			xObj = getHTTPObject();
			xObj.open('GET', url,true);
			xObj.onreadystatechange=function() {
				if (xObj.readyState==4) {
					document.location.href = document.location.href;
				}
			}
			xObj.send(null);
		}
	}
	else
	{
		if(confirm('Are you sure you want to turn off helper tips?'))
		{
			xObj = getHTTPObject();
			xObj.open('GET', url,true);
			xObj.onreadystatechange=function() {
				if (xObj.readyState==4) {
					document.location.href = document.location.href;
				}
			}
			xObj.send(null);
		}
	}
}

function getHTTPObject()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
	try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
		xmlhttp = false;
	  }
	}
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	try {
	  xmlhttp = new XMLHttpRequest();
	} catch (e) {
	  xmlhttp = false;
	}
  }
  return xmlhttp;
}

function openTutorial(path,width,height)
{
	if(width == null) width = 640;
	if(height == null) height = 510;
	if(path == null) path = "/admin/tutorials/home/";
	tb_show('',path+'?keepThis=true&amp;TB_iframe=true&amp;height='+height+'&amp;width='+width,null,"Close this video, return to Qwik-Post");
}

function openAccountManagement()
{
	tb_show('','/ecomm/acctmgmts/main?keepThis=true&amp;TB_iframe=true&amp;height=375&amp;width=745',null);
}var first_load = 0;
var page_init = 0;
var current_theme_id;
var current_music_id;
var current_package_name;
var current_plan;
var current_currency;
var current_sample_site;
var current_preview_swf;
var theme_ids = new Array();
var music_ids = new Array();
var pass_family_check = false;
var level_info_array = new Array();
var mess;
var currency_symbol = '$';
//var cad_rate = 0.9019;
//var gbp_rate = 1.9993;
var password_click = 0;
var discount_obj = new Array();

var cad_rate = '';
var gbp_rate = '';
var mxn_rate = '';
var valide_barcode = true;
var storage_dir = '';
var vertical = '';
var vertical_name = '';
var family_name = '';
var site_url = '';

var music_btn_width = '';
var music_btn_height = '';

var employee_id = '';
var employee_discount = '';

var default_discount_code = '';

var promoHackApplies = false;
function optionalInit()
{
	if(vertical == "kiddiekandids")
	{
		var startDate = new Date();
		startDate.setMonth(1);
		startDate.setDate(8)
		startDate.setFullYear(2009);
		var endDate = new Date();
		endDate.setMonth(4);
		endDate.setDate(10);
		endDate.setFullYear(2020);
		var today = new Date();
		if(today.getTime() > startDate.getTime() && today.getTime() < endDate.getTime())
		{
			promoHackApplies = true;
		}
	}
}

/* ********** THEME AND MUSIC ********** */
function getThemes()
{
	var mess = '';
	var items = req.responseXML.getElementsByTagName("theme");
	var curr = 1;
	var prev_genre = '';
	for(var i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("theme")[i].getAttribute('themeID');
		var the_genre = req.responseXML.getElementsByTagName("theme")[i].getAttribute('genre');
		if(prev_genre == '')
		{
			prev_genre = the_genre;
		}
		if(prev_genre != the_genre)
		{
			curr++;
		}
		/* get mod num for css style */
		var the_mod = curr % 3;
		addThemeId(the_id, the_mod);
		prev_genre = the_genre;
	}
}

function getMusic()
{
	var mess = '';
	var items = req.responseXML.getElementsByTagName("clip");
	var curr = 1;
	var prev_genre = '';
	for(var i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("clip")[i].getAttribute('songID');
		var the_genre = req.responseXML.getElementsByTagName("clip")[i].getAttribute('genre');
		if(prev_genre == '')
		{
			prev_genre = the_genre;
		}
		if(prev_genre != the_genre)
		{
			curr++;
		}
		/* get mod num for css style */
		var the_mod = curr % 3;
		addMusicId(the_id, the_mod);
		prev_genre = the_genre;
	}
}

function setDropMenuStyle(style_name, div_id, id, type, curr)
{
	var the_type = type + '_id';
	if(document.cart_form[the_type].value != '' || document.cart_form[the_type].value != undefined)
	{
		var current_val = document.cart_form[the_type].value;
		if(current_val != id)
		{
			var the_div = returnObjById(div_id);
			the_div.className = style_name;
		}
	}
}

function addThemeId(id, curr)
{
	theme_ids.push({'id':id, 'curr':curr});
}

function addMusicId(id, curr)
{
	music_ids.push({'id':id, 'curr':curr});
}

/* set the style to 'selected' of the item clicked. also unselect previous selections */
function checkSelected(type)
{
	var the_type = type + '_id';
	if(document.cart_form[the_type].value != '' || document.cart_form[the_type].value != undefined)
	{
		var current_val = document.cart_form[the_type].value;
		var curr_array = the_type + 's';
		for(var i=0; i<eval(curr_array).length; i++)
		{
			var the_div = returnObjById(type + '_' + eval(curr_array)[i]['id']);
			if(eval(curr_array)[i]['id'] == current_val)
			{
				the_div.className = 'dropmenuitemselected';
			}
			else
			{
				the_div.className = 'dropmenuitem' + eval(curr_array)[i]['curr'];
			}
		}
	}
}

function handleThemeClick(id)
{
	var items = req.responseXML.getElementsByTagName("theme");
	for(i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("theme")[i].getAttribute('themeID');
		
		if(the_id == id)
		{
			/* set the previews */
			var the_name = req.responseXML.getElementsByTagName("theme")[i].getAttribute('productName');
			var the_thumb = req.responseXML.getElementsByTagName("theme")[i].getAttribute('thumbnail');
			current_sample_site = req.responseXML.getElementsByTagName("theme")[i].getAttribute('sampleSite');
			
			if(barcode.length > 0)
			{
				current_sample_site += '&barcode=' + barcode;
			}
			else if(customer_code.length > 0)
			{
				current_sample_site += '&customer_code=' + customer_code;
			}
			
			current_preview_swf = req.responseXML.getElementsByTagName("theme")[i].getAttribute('image');
			
			if(first_load < 1)
			{
				/* We've set a music_id from a post operation. Use that one first */
				var the_music = current_music_id;
			}
			else
			{
				/* get the recommended id */
				var the_music = req.responseXML.getElementsByTagName("theme")[i].getAttribute('recommendedSongID');
			}
			
			/* display the chosen selection */
			var my_theme = returnObjById('my_theme');
			if(my_theme)
			{
				my_theme.innerHTML = the_name;
			}
			var flash_theme_name = returnObjById('flash_theme_name');
			if(flash_theme_name)
			{
				flash_theme_name.innerHTML = the_name;
			}
			
			setCurrentValue('theme_id', id);
			setCurrentValue('theme_name', the_name);
			previewTheme(id);
			
			var musiclist = returnObjById('musiclist');
			if(musiclist)
			{
				handleMusicClick(the_music, '');
				scrollDivToAnchor('musiclist', 'music_' + the_music);
			}
			
			document.cart_form.thumb.value = the_thumb;
		}
	}
	checkSelected('theme');
	first_load++;
}

function handleMusicClick(id, src)
{
	var musiclist = returnObjById('musiclist');
	if(musiclist)
	{
		/* clean the string from hacking the No Music 999 id for rollover effects */
		var str = id + '';
		var clean_id = str.replace(/[^0-9]+/g,'');
		clean_id += '';
		var items = req.responseXML.getElementsByTagName("clip");
		for(i=0; i<items.length; i++)
		{
			var the_id = req.responseXML.getElementsByTagName("clip")[i].getAttribute('songID');
	
			if(the_id == clean_id)
			{
				var the_name = req.responseXML.getElementsByTagName("clip")[i].getAttribute('musicname');
				var the_src = req.responseXML.getElementsByTagName("clip")[i].getAttribute('src');
				
				/* display the chosen selection */
				setCurrentValue('music_id', clean_id);
				setCurrentValue('music_name', the_name);
				var my_div = returnObjById('my_music');
				if(my_div)
				{
					my_div.innerHTML = the_name;
				}
				
				var music_control = returnObjById('music_control');
				if(music_control)
				{
					previewMusic(the_src);
				}
			}
		}
		checkSelected('music');
		
		/* handle clicks for No Music */
		if(clean_id == 999)
		{
			scrollDivToAnchor('musiclist', 'music_999');
		}
	}
}

function getMusicSrc(id)
{
	var items = req.responseXML.getElementsByTagName("clip");
	for(i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("clip")[i].getAttribute('songID');
		var the_src = req.responseXML.getElementsByTagName("clip")[i].getAttribute('src');
		if(the_id == id)
		{
			return the_src;
		}
	}
}

function scrollDivToAnchor(scroll_div, div_id)
{
	var cur_div = returnObjById(scroll_div);
	var anchor_div = returnObjById(div_id);
	cur_div.scrollTop = anchor_div.offsetTop;
}

function setSelectedMenu(div_id)
{
	var cur_div = returnObjById(div_id);
	cur_div.className = 'dropmenuitemselected';
}

function previewTheme(id)
{
	var width = 295;
	var height = 219;

	if(typeof(flash_width) != "undefined")
	{
		width = flash_width;
	}
	if(typeof(flash_height) != "undefined")
	{
		height = flash_height;
	}

	if(barcode.length > 0 || customer_code.length > 0)
	{
		if(barcode.length > 0)
		{
			var pic_url = storage_dir + '/' + barcode;
		}
		else if(customer_code.length > 0)
		{
			var pic_url = storage_dir + '/' + customer_code;
		}
		var flashPreview = new SWFObject("/view/themes-tree/" + id + "/default.swf", "main", width, height, "7", "#FFFFFF");
		flashPreview.addParam("quality", "high");
		flashPreview.addParam("allowScriptAccess", "sameDomain");
		flashPreview.addParam('wmode', 'transparent');
		flashPreview.addParam('scale', 'noborder');
		if(family_name.length > 0)
		{
			flashPreview.addVariable("family_name", family_name);
		}
		else
		{
			flashPreview.addVariable("family_name", "The Gordons");
		}
		flashPreview.addVariable("music_src", "");
		flashPreview.addVariable("verticalName", vertical_name);
		flashPreview.addVariable("verticalSlogan", "");
		flashPreview.addVariable("slide1", pic_url + "/home_slide1.jpg");
		flashPreview.addVariable("slide2", pic_url + "/home_slide2.jpg");
		flashPreview.addVariable("slide3", pic_url + "/home_slide3.jpg");
		flashPreview.addVariable("kidspic", pic_url + "/home_kidspic.jpg");
		flashPreview.addVariable("calpic", pic_url + "/home_calpic.jpg");
		flashPreview.write("flash_preview");
	}
	else
	{
		if(vertical == 'kiddiekandids')
		{
			var flashPreview = new SWFObject(site_url + "/view/themes-tree/" + id + "/default.swf", "main", width, height, "7", "#FFFFFF");
			flashPreview.addParam("quality", "high");
			flashPreview.addParam("allowScriptAccess", "sameDomain");
			flashPreview.addParam('wmode', 'transparent');
			flashPreview.addParam('scale', 'noborder');
			if(family_name.length > 0)
			{
				flashPreview.addVariable("family_name", family_name);
			}
			else
			{
				flashPreview.addVariable("family_name", "The Gordons");
			}
			flashPreview.addVariable("music_src", "");
			flashPreview.addVariable("verticalName", vertical_name);
			flashPreview.addVariable("verticalSlogan", "");
			flashPreview.addVariable("slide1", site_url + "/storage-kiddiekandids/9670/home_slide1.jpg");
			flashPreview.addVariable("slide2", site_url + "/storage-kiddiekandids/9670/home_slide2.jpg");
			flashPreview.addVariable("slide3", site_url + "/storage-kiddiekandids/9670/home_slide3.jpg");
			flashPreview.addVariable("kidspic", site_url + "/storage-kiddiekandids/9670/home_kidspic.jpg");
			flashPreview.addVariable("calpic", site_url + "/storage-kiddiekandids/9670/home_calpic.jpg");
			flashPreview.write("flash_preview");
		}
		else if(vertical == 'familypost')
		{
			var flashPreview = new SWFObject(site_url + "/view/themes-tree/" + id + "/default.swf", "main", width, height, "7", "#FFFFFF");
			flashPreview.addParam("quality", "high");
			flashPreview.addParam("allowScriptAccess", "sameDomain");
			flashPreview.addParam('wmode', 'transparent');
			flashPreview.addParam('scale', 'noborder');
			if(family_name.length > 0)
			{
				flashPreview.addVariable("family_name", family_name);
			}
			else
			{
				flashPreview.addVariable("family_name", "The Gordons");
			}
			flashPreview.addVariable("music_src", "");
			flashPreview.addVariable("verticalName", vertical_name);
			flashPreview.addVariable("verticalSlogan", "");
			flashPreview.addVariable("slide1", site_url + "/storage/9670/home_slide1.jpg");
			flashPreview.addVariable("slide2", site_url + "/storage/9670/home_slide2.jpg");
			flashPreview.addVariable("slide3", site_url + "/storage/9670/home_slide3.jpg");
			flashPreview.addVariable("kidspic", site_url + "/storage/9670/home_kidspic.jpg");
			flashPreview.addVariable("calpic", site_url + "/storage/9670/home_calpic.jpg");
			flashPreview.write("flash_preview");
		}
		else if(vertical == 'familydrive')
		{
			var flashPreview = new SWFObject( "/view/themes-tree/" + id + "/default.swf", "main", width, height, "7", "#FFFFFF");
			flashPreview.addParam("quality", "high");
			flashPreview.addParam("allowScriptAccess", "sameDomain");
			flashPreview.addParam('wmode', 'transparent');
			flashPreview.addParam('scale', 'noborder');
			if(family_name.length > 0)
			{
				flashPreview.addVariable("family_name", family_name);
			}
			else
			{
				flashPreview.addVariable("family_name", "The Gordons");
			}
			flashPreview.addVariable("music_src", "");
			flashPreview.addVariable("verticalName", vertical_name);
			flashPreview.addVariable("verticalSlogan", "");
			flashPreview.addVariable("slide1",  "/storage-familydrive/9670/home_slide1.jpg?58439");
			flashPreview.addVariable("slide2", "/storage-familydrive/9670/home_slide2.jpg?77738");
			flashPreview.addVariable("slide3", "/storage-familydrive/9670/home_slide3.jpg?74691");
			flashPreview.addVariable("kidspic", "/storage-familydrive/9670/home_kidspic.jpg?34728");
			flashPreview.addVariable("calpic", "/storage-familydrive/9670/home_calpic.jpg?96938");
			flashPreview.write("flash_preview");
		}
		else
		{
			var flashPreview = new SWFObject("/cartV2/V/themeImages/" + current_preview_swf + "?noButton=true", "main", width, height, "7", "#FFFFFF");
			flashPreview.addParam("quality", "high");
			flashPreview.addParam("allowScriptAccess", "sameDomain");
			flashPreview.addParam('wmode', 'transparent');
			flashPreview.addParam('scale', 'noborder');
			flashPreview.addVariable("family_name", "The Gordons");
			flashPreview.addVariable("music_src", "");
			flashPreview.addVariable("verticalName", vertical_name);
			flashPreview.addVariable("verticalSlogan", "");
			flashPreview.write("flash_preview");
		}
	}
}

function previewMusic(src)
{
	var the_width = music_btn_width?music_btn_width:62;
	var the_height = music_btn_height?music_btn_height:22;
	var music_control = returnObjById('music_control');
	if(music_control)
	{
		var flashMusicPreview = new SWFObject("images/music_preview.swf", "music", the_width, the_height, "7", "#FFFFFF");
		flashMusicPreview.addParam("quality", "high");
		flashMusicPreview.addParam("allowScriptAccess", "sameDomain");
		flashMusicPreview.addParam('wmode', 'transparent');
		flashMusicPreview.addVariable("music_src", src);
		flashMusicPreview.write("music_control");
	}
}

function displayTheme()
{
	window.open(current_sample_site);
}

/* ********** PACKAGE LEVEL AND PLAN ********** */
function setPackage(id)
{
	var items = req.responseXML.getElementsByTagName("level");
	for(i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelID');
		var the_name = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelName');
		var the_photos = req.responseXML.getElementsByTagName("level")[i].getAttribute('photos');
		var the_videos = req.responseXML.getElementsByTagName("level")[i].getAttribute('videos');
		var premium_photos_videos = req.responseXML.getElementsByTagName("level")[i].getAttribute('photoMessageLong');
		if(the_id == id)
		{
			current_package_name = id;
			
			/* display the chosen selection */
			var my_div = returnObjById('my_package');
			if(my_div)
			{
				my_div.innerHTML = the_name;
			}
			
			var the_div = returnObjById('photos_videos');
			if(the_div)
			{
				if(current_package_name == 2)
				{
					the_div.innerHTML = premium_photos_videos;
				}
				else
				{
					the_videos = the_videos.replace(',', '');
					the_videos = the_videos/60;
					the_div.innerHTML = '<div id="numbers">Photos: <div id="photo_count" style="display: inline;" class="selectionstexthighlight">' + the_photos + '</div></div><div id="numbers2">Videos: <div id="video_count" style="display: inline; padding-right: 2px;" class="selectionstexthighlight">' + the_videos + '</div> <span class="selectionstexthighlight">Minutes</span></div>';
				}
			}
			
			/*
			var photo_div = returnObjById('photo_count');
			photo_div.innerHTML = the_photos;
			
			var video_div = returnObjById('video_count');
			video_div.innerHTML = the_videos;
			*/
		}
	}
}

function displayStepTwoPackage(id)
{
	var photo_amount = returnObjById('photo_amount');
	var video_amount = returnObjById('video_amount');
	if(photo_amount && video_amount)
	{
		var items = req.responseXML.getElementsByTagName("level");
		for(i=0; i<items.length; i++)
		{
			var the_id = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelID');
			var the_name = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelName');
			var the_photos = req.responseXML.getElementsByTagName("level")[i].getAttribute('photos');
			var the_videos = req.responseXML.getElementsByTagName("level")[i].getAttribute('videos');
			var premium_photos_videos = req.responseXML.getElementsByTagName("level")[i].getAttribute('photoMessage');
			if(the_id == id)
			{			
				/* display the chosen selection */
				if(id == 2)
				{
					photo_amount.innerHTML = premium_photos_videos;
				}
				else
				{
					photo_amount.innerHTML = the_photos + ' photos';
					video_amount.innerHTML = the_videos + ' minutes of video';
				}
			}
		}
	}
}

function displayStepTwoPricing()
{
	var steptwo_pricing = returnObjById('steptwo_pricing');
	if(steptwo_pricing)
	{
		setDiscountedPricing();
	}
}

function getLevelInfo()
{
	var items = req.responseXML.getElementsByTagName("level");
	for(i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelID');
		var the_name = req.responseXML.getElementsByTagName("level")[i].getAttribute('levelName');
		var monthly_price = req.responseXML.getElementsByTagName("level")[i].getAttribute('monthlyPrice');
		var yearly_price = req.responseXML.getElementsByTagName("level")[i].getAttribute('yearlyPrice');
		
		if(the_id >= 0)
		{
			level_info_array[the_id] = {'monthly':monthly_price, 'yearly':yearly_price};
		}
	}
	return level_info_array;
}


/* ********** PRICING ********** */
function displayCurrentPriceLine()
{
	getPricePlan();
	displayPrice();
	displayOriginalPrice();
	displayDiscount();
	writeCurrencySym();
}

function getPricePlan()
{
	var the_div = returnObjById('price_plan');
	var the_div2 = returnObjById('price_plan2');
	var the_div3 = returnObjById('price_plan3');
	var per_text = '';
	if(the_div)
	{
		if(document.cart_form.price.value == '0.00')
		{
			the_div.innerHTML = '';
		}
		else if(document.cart_form.plan.value.toLowerCase() == 'yearly')
		{
			per_text = '/Year';
		}
		else if(document.cart_form.plan.value.toLowerCase() == 'monthly')
		{
			per_text = '/Month';
		}
	
		the_div.innerHTML = per_text;
	}
	if(the_div2)
	{
		the_div2.innerHTML = per_text;
	}
	if(the_div3)
	{
		if(discount_obj.length > 0)
		{
			the_div3.innerHTML = per_text;
		}
	}
}

function displayPrice()
{
	var cur_div = returnObjById('price_info');
	if(cur_div)
	{
		if(document.cart_form.price.value == '0.00')
		{
			cur_div.innerHTML = 'FREE';
		}
		else
		{
			cur_div.innerHTML = document.cart_form.price.value + ' <span style="font-size: 10px; font-weight: normal;">(' + current_currency + ')</span>';
			//cur_div.innerHTML = document.cart_form.price.value;
		}
	}
}

function displayOriginalPrice()
{
	var original_amount = returnObjById('original_amount');
	if(original_amount)
	{
		var original_price = getPrice(current_package_name);
		original_amount.innerHTML = currency_symbol + original_price;
	}
}

function displayDiscount()
{
	var discounts_text = returnObjById('discounts_text');
	var discount_amount_div = returnObjById('discount_amount');
	if(discount_amount_div)
	{
		if(discount_obj.length > 0)
		{
			if(discounts_text)
			{
				var discountname = discount_obj[0]['discountname'];
				discounts_text.innerHTML = 'Discounts (' + discountname + ')';
			}
	
			if(discount_amount_div)
			{
				var original_price = getPrice(current_package_name);
				if(vertical == 'familydrive' && current_plan == 'Yearly')
				{
					var discountvalue = 16.67;
					var ispercent = 1;
				}
				else
				{
					var discountvalue = discount_obj[0]['discountvalue'];
					var ispercent = discount_obj[0]['ispercent'];
				}
				var discount_amount = calcDiscountAmount(original_price, ispercent, discountvalue);
				discount_amount_div.innerHTML = '-' + currency_symbol + discount_amount;
			}
		}
		else
		{
			if(discounts_text)
			{
				discounts_text.innerHTML = '';
			}
			
			if(discount_amount_div)
			{
				discount_amount_div.innerHTML = '';
			}
			
			var the_div3 = returnObjById('price_plan3');
			if(the_div3)
			{
				the_div3.innerHTML = '';
			}
		}
	}
}

function writeCurrencySym()
{
	var cur_div = returnObjById('csymbol');
	if(cur_div)
	{
		if(document.cart_form.price.value == '0.00')
		{
			cur_div.innerHTML = '';
		}
		else
		{
			getCalcRate();
			cur_div.innerHTML = currency_symbol;
		}
	}
}

/* get the price of the package */
function getPrice(package_id)
{
	var rate = getCalcRate();
	var the_plan = current_plan.toLowerCase();
	if(the_plan == 'yearly')
	{
		var the_price = level_info_array[package_id].yearly * (1/rate);
	}
	else
	{
		var the_price = level_info_array[package_id].monthly * (1/rate);
	}

	the_price = parseFloat(the_price);
	the_price = the_price.toFixed(2);
	return the_price;
}

function updatePricing()
{
	var discountvalue = '';
	var ispercent = '';
	if(discount_obj.length > 0)
	{
		if(vertical == 'familydrive' && current_plan == 'Yearly')
		{
			var discountvalue = 16.67;
			var ispercent = 1;
		}
		else
		{
			var discountvalue = discount_obj[0]['discountvalue'];
			var ispercent = discount_obj[0]['ispercent'];
		}
	}
	var the_price = getPrice(current_package_name);
	var discount_price = calcDiscount(the_price, ispercent, discountvalue,current_package_name);
	document.cart_form.price.value = discount_price;
}

function getCalcRate()
{
	if(typeof(current_currency) == "undefined" || current_currency == '')
	{
		current_currency = 'USA';
	}
	switch(current_currency)
	{
		case 'USA':
			var rate = 1;
			currency_symbol = '$';
			break;
		
		case 'CAN':
			var rate = cad_rate;
			currency_symbol = '$';
			break;
		
		case 'UK':
			var rate = gbp_rate;
			currency_symbol = '&pound;';
			break;
		
		case 'MEX':
			var rate = mxn_rate;
			currency_symbol = '$';
			break;
	}
	return rate;
}


function handleCurrencyChange(currency)
{
	setAllDiscounts();
	updatePricing();
}

function setXChangeRate(country_code, response_string)
{
	var the_rate_array = response_string.split('=');
	var the_rate = the_rate_array[1];
	switch(country_code)
	{
		case 'CAD':
			cad_rate = the_rate;
			document.cart_form.cad_rate.value = cad_rate;
			var cur_div = returnObjById('currency_can');
			if(cur_div)
			{
				cur_div.style.display = 'inline';
			}
			break;
		
		case 'GBP':
			gbp_rate = the_rate;
			document.cart_form.gbp_rate.value = gbp_rate;
			var cur_div = returnObjById('currency_uk');
			if(cur_div)
			{
				cur_div.style.display = 'inline';
			}
			break;
		
		case 'MXN':
			mxn_rate = the_rate;
			document.cart_form.mxn_rate.value = mxn_rate;
			var cur_div = returnObjById('currency_mx');
			if(cur_div)
			{
				cur_div.style.display = 'inline';
			}
			break;
	}
}

function getXChangeRate(country_code) {
	// temp hack
	if(country_code == 'MXN')
	{
		setXChangeRate('MXN', 'rate=0.098754');
	}
	else
	{
		var url = '/cartV2/M/getexrate.php?currency=' + country_code;
		var xObj = false;
		xObj = getHTTPObject();
		xObj.open('GET', url,true);
		xObj.onreadystatechange=function() {
			if (xObj.readyState==4) {
				setXChangeRate(country_code, xObj.responseText);
			}
		}
		xObj.send(null);
	}
}


/* ********** DISCOUNT ********** */
function getDiscountInfo(code, step_num)
{
	if(code.length > 0)
	{
		var url = '/API/discounts/checkIfDiscount/' + code + '/1';
		var xObj = false;
		xObj = getHTTPObject();
		xObj.open('GET', url,true);
		xObj.onreadystatechange=function() {
			if (xObj.readyState==4) {
				var discount_res = xObj.responseText;
				var parts = discount_res.split('|');
				var discountcode = parts[0];
				var discountvalue = parts[1];
				var ispercent = parts[2];
				var discountname = parts[3];
				discount_obj[0] = {'code':discountcode, 'ispercent':ispercent, 'discountvalue':discountvalue, 'discountname':discountname};

				if(step_num == 1)
				{
					initStepOne();
				}
				else if(step_num == 2)
				{
					initStepTwo();
				}
			}
		}
		xObj.send(null);
	}
	else
	{
		if(step_num == 1)
		{
			initStepOne();
		}
		else if(step_num == 2)
		{
			initStepTwo();
		}
	}
}

var reqK;
function checkDiscount()
{
	var code = document.cart_form.x_discount_code.value?document.cart_form.x_discount_code.value:default_discount_code;
	var url = '/API/discounts/checkIfDiscount/' + code + '/1';
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('GET', url,true);
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			var discount_res = xObj.responseText;
			var parts = discount_res.split('|');
			var discountcode = parts[0];
			var discountvalue = parts[1];
			var ispercent = parts[2];
			var discountname = parts[3];
			if(discountcode.length > 0)
			{
				discount_obj[0] = {'code':discountcode, 'ispercent':ispercent, 'discountvalue':discountvalue, 'discountname':discountname};
				setDiscount();
				//alert('Your promotion code has been applied!');
			}
			else
			{
				if(vertical == 'kiddiekandids')
				{
					reqK = loadXMLFile('/API/KkEmployees/is_valid/' + code, 'processKKEmp');
				}
				else
				{
					// use default_discount_code
					getDefaultDiscountValues();
				}
			}
		}
	}
	xObj.send(null);
}

function getDefaultDiscountValues()
{
	var code = default_discount_code;
	var url = '/API/discounts/checkIfDiscount/' + code + '/1';
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('GET', url,true);
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			var discount_res = xObj.responseText;
			var parts = discount_res.split('|');
			var discountcode = parts[0];
			var discountvalue = parts[1];
			var ispercent = parts[2];
			var discountname = parts[3];
			if(discountcode.length > 0)
			{
				discount_obj[0] = {'code':discountcode, 'ispercent':ispercent, 'discountvalue':discountvalue, 'discountname':discountname};
				setDiscount();
			}
		}
	}
	xObj.send(null);
}

function processKKEmp()
{
	var is_valid = getXMLTagInfo(reqK, 'is_valid', 0, '');
	if(is_valid == 1)
	{
		employee_id = document.cart_form.x_discount_code.value;
		document.cart_form.x_discount_code.value = 'emppro';
		checkDiscount();
		setDiscount();
	}
	else
	{
		getDefaultDiscountValues();
	}
}

function setDiscount()
{
	var package_id = document.cart_form.package_name.value?document.cart_form.package_name.value:current_package_name;
	var plan = document.cart_form.plan.value;
	var original_price = getPrice(package_id, plan);
	var code = '';
	var discountvalue = '';
	var ispercent = '';
	if(discount_obj.length > 0)
	{
		code = discount_obj[0]['code'];
		discountvalue = discount_obj[0]['discountvalue'];
		ispercent = discount_obj[0]['ispercent'];
	}
	
	var discount_price = calcDiscount(original_price, ispercent, discountvalue);
	document.cart_form.price.value = discount_price;
	updateSessionPromo(code);
	displayCurrentPriceLine();
	setAllDiscounts();
	setDiscountBox();
}

function calcDiscount(original_price, ispercent, discountvalue,level)
{
	var discount_price = '';
	
	//handle special price for 2/8/2009 to 4/12/2009
	if(vertical == 'kiddiekandids' && promoHackApplies == true)
	{	
		var package_id = level;//?level:document.cart_form.package_name.value?document.cart_form.package_name.value:current_package_name;
		package_id = parseInt(package_id);
		
		switch(package_id)
		{
			case 0:
				discountvalue = 10;
				break;
			case 1:
				discountvalue = 30.15;
				break;
			case 2:
				discountvalue = 50.179;
				break;
		}
		ispercent = 1;
	}
	
	
	if(ispercent == 1)
	{
		discount_price = original_price - (original_price * (discountvalue/100));
		/* fix rounding */
		/*
		discount_price = discount_price + '';
		var parts = discount_price.split('.');
		var dec = Math.floor(parts[1]);
		dec += '';
		dec = dec.substring(0,2);
		var dp = parts[0] + '.' + dec;
		dp = parseFloat(dp);
		discount_price = dp.toFixed(2);
		*/
		discount_price = discount_price.toFixed(2);
	}
	else if(discountvalue.length > 0)
	{
		discount_price = discountvalue;
	}
	else
	{
		discount_price = original_price;
	}

	return discount_price;
}

function calcDiscountAmount(original_price, ispercent, discountvalue)
{
	var discount_amount = '';
	
	//handle special price for 2/8/2009 to 4/12/2009
	if(vertical == 'kiddiekandids' && promoHackApplies == true)
	{
		//console.log("fsdfdfjlksdfj")
		var package_id = document.cart_form.package_name.value?document.cart_form.package_name.value:current_package_name;
		package_id = parseInt(package_id);
		switch(package_id)
		{
			case 0:
				discountvalue = 10;
				break;
			case 1:
				discountvalue = 30.15;
				break;
			case 2:
				discountvalue = 50.179;
				break;
		}
		ispercent = 1;
	}
	
	
	if(ispercent == 1)
	{
		discount_amount = original_price * (discountvalue/100);
		/* fix rounding */
		/*
		discount_amount = discount_amount + '';
		var parts = discount_amount.split('.');
		var dec = Math.floor(parts[1]);
		dec += '';
		dec = dec.substring(0,2);
		var dp = parts[0] + '.' + dec;
		dp = parseFloat(dp);
		discount_amount = dp.toFixed(2);
		*/
		discount_amount = discount_amount.toFixed(2);
	}
	else if(discountvalue.length > 0)
	{
		discount_amount = discountvalue;
	}

	return discount_amount;
}

function setAllDiscounts()
{
	var discountvalue = '';
	var ispercent = '';
	if(discount_obj.length > 0)
	{
		discountvalue = discount_obj[0]['discountvalue'];
		ispercent = discount_obj[0]['ispercent'];
	}
	
	for(var i=0; i<level_info_array.length; i++)
	{
		var the_price = getPrice(i);
		var orig_price_div = returnObjById('original_level_' + i);
		if(orig_price_div)
		{
			if(discount_obj.length > 0)
			{
				orig_price_div.innerHTML = currency_symbol + the_price;
			}
		}
		
		var the_div = returnObjById('level_' + i);
		
		var discount_price = calcDiscount(the_price, ispercent, discountvalue,i);
		if(discountvalue == 100)
		{
			the_div.innerHTML = '<div style="font-size: 11px; color: red;">FREE</div>';
		}
		else
		{
			if(promoHackApplies) the_div.innerHTML = '<div class="promo_price" style="font-weight: bold; font-size: 12px;">' + currency_symbol + discount_price + '*</div>';
			else the_div.innerHTML = '<div style="font-weight: bold; font-size: 11px;">' + currency_symbol + discount_price + '</div>';
			/*the_div.innerHTML = '<span style="text-decoration: line-through; font-size: 9px; color: red;">' + the_price + '</span> <span style="font-weight: bold; font-size: 11px;">' + currency_symbol + discount_price + '</span>';*/
		}
	}
}

function setDiscountBox()
{
	if(vertical == 'kiddiekandids')
	{
		if(discount_obj.length > 0)
		{
			var current_code = discount_obj[0]['code'];
			if(employee_id.length > 0 && current_code == 'emppro')
			{
				document.cart_form.x_discount_code.value = employee_id;
			}
			else
			{
				default_discount_code = getDefaultDiscount();
				if(current_code == default_discount_code)
				{
					document.cart_form.x_discount_code.value = '';
					document.cart_form.x_discount_code_hidden.value = default_discount_code;
				}
				else
				{
					document.cart_form.x_discount_code.value = current_code;
				}
			}
		}
	}
	else
	{
		if(discount_obj.length > 0)
		{
			document.cart_form.x_discount_code.value = discount_obj[0]['code'];
		}
	}
}

/* for displaying the discounted price in step two */
function setDiscountedPricing()
{
	var discountvalue = '';
	var ispercent = '';
	if(discount_obj.length > 0)
	{
		discountvalue = discount_obj[0]['discountvalue'];
		ispercent = discount_obj[0]['ispercent'];
	}
	for(var i=0; i<level_info_array.length; i++)
	{
		var the_price = getPrice(i);
		var orig_price_div = returnObjById('original_level_' + i);
		if(orig_price_div)
		{
			if(discount_obj.length > 0)
			{
				orig_price_div.innerHTML = currency_symbol + the_price;
			}
		}
		
		var the_div = returnObjById('level_' + i);
		var discount_price = calcDiscount(the_price, ispercent, discountvalue);
		if(discountvalue == 100)
		{
			the_div.innerHTML = '<span style="font-size: 11px; color: red;">FREE</span>';
		}
		else
		{
			the_div.innerHTML = '<span style="font-weight: bold; font-size: 11px;">' + currency_symbol + discount_price + '/month</span>';
			/*the_div.innerHTML = '<span style="text-decoration: line-through; font-size: 9px; color: red;">' + the_price + '</span> <span style="font-weight: bold; font-size: 11px;">' + currency_symbol + discount_price + '</span>';*/
		}
	}
}

function getDefaultDiscount()
{
	default_discount_code = getXMLTagInfo(req, 'defaultValues', 0, 'discount');
	return default_discount_code;
}


/* ********** MISC ********** */
function setCurrentValue(field_name, field_value)
{
	switch(field_name)
	{
		case 'theme_id':
			current_theme_id = field_value;
			document.cart_form.theme_id.value = field_value;
			break;
		
		case 'theme_name':
			var theme_name = returnObjById('theme_name');
			if(theme_name)
			{
				document.cart_form.theme_name.value = field_value;
			}
			break;
		
		case 'music_id':
			current_music_id = field_value;
			document.cart_form.music_id.value = field_value;
			break;
		
		case 'music_name':
			var music_name = returnObjById('music_name');
			if(music_name)
			{
				document.cart_form.music_name.value = field_value;
			}
			break;
		
		case 'package_name':
			current_package_name = field_value;
			if(pagename == 1)
			{
				var radio_id = 'service_level_' + field_value;
				var the_div = returnObjById(radio_id);
				if(the_div)
				{
					the_div.checked = true;
				}
			}
			break;
		
		case 'plan':
			current_plan = field_value;
			var my_div = returnObjById('my_plan');
			var plan_name = returnObjById('plan_name');
			if(my_div)
			{
				my_div.innerHTML = field_value;
			}
			if(plan_name)
			{
				plan_name.innerHTML = field_value;
			}
			if(pagename == 1)
			{
				var radio_id = 'plan_' + field_value.toLowerCase();
				var the_div = returnObjById(radio_id);
				if(the_div)
				{
					the_div.checked = true;
				}
			}
			document.cart_form.plan.value = field_value;
			break;
		
		case 'currency':
			current_currency = field_value;
			break;
		
		case 'discount':
			current_discount = field_value;
			if(vertical == 'kiddiekandids')
			{
				document.cart_form.x_discount_code_hidden.value = field_value;
			}
			else
			{
				document.cart_form.x_discount_code.value = field_value;
			}
			break;
		
		case 'cad_rate':
			if(field_value.length > 0)
			{
				cad_rate = field_value;
				document.cart_form.cad_rate.value = field_value;
				var cur_div = returnObjById('currency_can');
				if(cur_div)
				{
					cur_div.style.display = 'inline';
				}
			}
			break;
		
		case 'gbp_rate':
			if(field_value.length > 0)
			{
				gbp_rate = field_value;
				document.cart_form.gbp_rate.value = field_value;
				var cur_div = returnObjById('currency_uk');
				if(cur_div)
				{
					cur_div.style.display = 'inline';
				}
			}
			break;
		
		case 'mxn_rate':
			if(field_value.length > 0)
			{
				mxn_rate = field_value;
				document.cart_form.mxn_rate.value = field_value;
				var cur_div = returnObjById('currency_mx');
				if(cur_div)
				{
					cur_div.style.display = 'inline';
				}
			}
			break;
	}
}

function changeCart()
{
	document.cart_form.action = '/cartV2/?action=step1';
	document.cart_form.submit();
}

function checkFormItem(form_field)
{
	var the_var = 'current_' + form_field;
	for(var i=0; i<=document.cart_form[form_field].length; i++)
	{
		if(document.cart_form[form_field][i])
		{
			if(eval(the_var) == document.cart_form[form_field][i].value)
			{
				document.cart_form[form_field][i].checked = true;
			}
		}
	}
}

function validate_form(the_form)
{
	/*loop through the forms and highlight empty fields */
	var have_empty = false;
	for(i=0; i<document.cart_form.elements.length; i++)
	{
		if(document.cart_form.elements[i].type != 'hidden')
		{
			if(document.cart_form.elements[i].type == 'checkbox')
			{
				if(document.cart_form.elements[i].checked == false)
				{
					have_empty = true;
					var cur_div = returnObjById('terms_box');
					cur_div.className = 'formerrorhighlight';
					//cur_div.style.backgroundColor = '#FFFF00';
				}
				else
				{
					var cur_div = returnObjById('terms_box');
					cur_div.style.backgroundColor = '';
				}
			}
			else
			{
				if(document.cart_form.elements[i].value == '' && document.cart_form.elements[i].name != 'x_promo_code' && document.cart_form.elements[i].name != 'x_discount_code' && document.cart_form.elements[i].name != 'show_password' && document.cart_form.elements[i].name != 'partner_uid' && document.cart_form.elements[i].name != 'x_state_other')
				{
					/* westgate */
					var owner_id = returnObjById('owner_id');
					if(owner_id)
					{
						/* CC optional if have owner id */
						if(owner_id.value != '')
						{
							if(document.cart_form.elements[i].value == '' && document.cart_form.elements[i].name != 'cctype' && document.cart_form.elements[i].name != 'x_card_num_1' && document.cart_form.elements[i].name != 'x_card_num_2' && document.cart_form.elements[i].name != 'x_card_num_3' && document.cart_form.elements[i].name != 'x_card_num_4' && document.cart_form.elements[i].name != 'x_card_code' && document.cart_form.elements[i].name != 'x_exp_date_1' && document.cart_form.elements[i].name != 'x_exp_date_2')
							{
								have_empty = true;
								document.cart_form.elements[i].className = 'formerrorhighlight';
								//document.cart_form.elements[i].style.backgroundColor = '#FFFF00';
							}
							else
							{
								document.cart_form.elements[i].style.backgroundColor = '#FFFFFF';
							}
						}
						else
						{
							have_empty = true;
							document.cart_form.elements[i].className = 'formerrorhighlight';
							//document.cart_form.elements[i].style.backgroundColor = '#FFFF00';
						}
					}
					else
					{
						have_empty = true;
						document.cart_form.elements[i].className = 'formerrorhighlight';
						//document.cart_form.elements[i].style.backgroundColor = '#FFFF00';
					}
				}
				else
				{
					document.cart_form.elements[i].style.backgroundColor = '#FFFFFF';
				}
			}
		}
	}
	if(have_empty == true)
	{
		alert('Please fill in the required fields.');
		return false;
	}
	
	var x_password = returnObjById('adminpassbox2');
	if(x_password)
	{
		if(document.cart_form.x_password.value.length < 4)
		{
			alert('Your password must be at least 4 characters in length.');
			document.cart_form.x_password.focus();
			return false;
		}
	}
	
	if(the_form.theme_id.value == '' || the_form.package_name.value == '' || the_form.plan.value == '' || the_form.currency.value == '')
	{
		alert('Please return to step one and select your Theme, Package, Plan, and Currency values.');
		return false;
	}
	else
	{
		/* westgate */
		var owner_id = returnObjById('owner_id');
		if(owner_id)
		{
			if(owner_id.value != '')
			{
				document.cart_form.cctype.required = 'false';
				document.cart_form.x_card_num_1.required = 'false';
				document.cart_form.x_card_num_2.required = 'false';
				document.cart_form.x_card_num_3.required = 'false';
				if(document.cart_form.x_card_num_4)
				{
					document.cart_form.x_card_num_4.required = 'false';
				}
				document.cart_form.x_exp_date_1.required = 'false';
				document.cart_form.x_exp_date_2.required = 'false';
				if(document.cart_form.x_card_code)
				{
					document.cart_form.x_card_code.required = 'false';
				}
			}
			
		}

		//return validateStandard(the_form, 'error');
		// IE fix 
		var validated = validateStandard(the_form, 'error');
		if(validated == true)
		{
			if (document.cart_form.submit_form.value == 'gift')
			{
				document.cart_form.action = '/cartV2/?action=step-gift';
			}
			else 
			{
				document.cart_form.action = '/cartV2/?action=step2';
			}
			
			document.cart_form.submit_form.value = 1;
			return true;
		}
		else
		{
			return false;
		}
	}
}


function displayMessage()
{
	if(mess != undefined)
	{
		alert(mess);
	}
}

function printSelectedName(id, tag_name, id_att_name, att_name, div_name)
{
	var items = req.responseXML.getElementsByTagName(tag_name);
	for(i=0; i<items.length; i++)
	{
		var the_id = req.responseXML.getElementsByTagName(tag_name)[i].getAttribute(id_att_name);
		var the_name = req.responseXML.getElementsByTagName(tag_name)[i].getAttribute(att_name);
		
		if(the_id == id)
		{
			var cur_div = returnObjById(div_name);
			if(cur_div)
			{
				cur_div.innerHTML = the_name;
			}
		}
	}
}

function showPasswordBox()
{
	var passbox1 = returnObjById('passwordbox1');
	passbox1.style.display = 'none';
	var passbox2 = returnObjById('passwordbox2');
	passbox2.style.display = 'inline';
	
	document.login_form.password.value = '';
	document.login_form.password.focus();
}

function showCardNumInput(val)
{
	if(val == '')
	{
		val = 'VISA';
	}
	if(val == 'AMEX')
	{
		/* ccnum */
		var div_info = '<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_num_1" value="' + document.cart_form.cc1.value + '" class="formelement" style="width: 35px; margin-right: 5px;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="12" />' +
			'<input onKeyUp="return autoTab(this, 6, event);" type="text" name="x_card_num_2" value="' + document.cart_form.cc2.value + '" class="formelement" style="width: 55px; margin-right: 5px;" maxlength="6" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="13" />' +
			'<input onKeyUp="return autoTab(this, 5, event);" type="text" name="x_card_num_3" value="' + document.cart_form.cc3.value + '" class="formelement" style="width: 40px; margin-right: 5px;" maxlength="5" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="14" />';
		
		/* csc */
		//var csc_info = 'N/A';
		var csc_info = '<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_code" value="' + document.cart_form.csc.value + '" class="formelement" style="width: 35px; display: inline;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter a valid card security code." tabindex="16" />';
	}
	else
	{
		var div_info = '<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_num_1" value="' + document.cart_form.cc1.value + '" class="formelement" style="width: 35px; margin-right: 5px;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="12" />' +
			'<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_num_2" value="' + document.cart_form.cc2.value + '" class="formelement" style="width: 35px; margin-right: 5px;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="13" />' +
			'<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_num_3" value="' + document.cart_form.cc3.value + '" class="formelement" style="width: 35px; margin-right: 5px;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="14" />' +
			'<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_num_4" value="' + document.cart_form.cc4.value + '" class="formelement" style="width: 35px; margin-right: 5px;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter you credit card number (numbers only)." tabindex="15" />';
		
		/* csc */
		var csc_info = '<input onKeyUp="return autoTab(this, 4, event);" type="text" name="x_card_code" value="' + document.cart_form.csc.value + '" class="formelement" style="width: 35px; display: inline;" maxlength="4" onblur="this.style.backgroundColor=\'#FFFFFF\'" onfocus="this.className=\'formerrorhighlight\'" regexp="JSVAL_RX_CREDITCARD" required="true" err="Please enter a valid card security code." tabindex="16" />';
	}
	var cc_div = returnObjById('cc_nums');
	if(cc_div)
	{
		cc_div.innerHTML = div_info;
	}
	var csc_div = returnObjById('csc_nums');
	if(csc_div)
	{
		csc_div.innerHTML = csc_info;
	}
}

function handleAdminPass()
{
	var adminpassbox1 = returnObjById('adminpassbox1');
	var adminpassbox2 = returnObjById('adminpassbox2');

	if(adminpassbox1.style.display == 'inline')
	{
		adminpassbox1.style.display = 'none';
		adminpassbox2.style.display = 'inline';
	}
	else
	{
		adminpassbox1.style.display = 'inline';
		adminpassbox2.style.display = 'none';
		document.cart_form.show_password.focus();
	}
}

function copyPassValues()
{
	document.cart_form.x_password.value = document.cart_form.show_password.value;
}

function updateSessionPromo(discount) {
	var url = '/API/discounts/updateSessionDiscount/' + discount;
	var xObj = false;
	xObj = getHTTPObject();
	xObj.open('GET', url,true);
	xObj.onreadystatechange=function() {
		if (xObj.readyState==4) {
			/*alert('discount updated');*/
		}
	}
	xObj.send(null);
}

function showPopupLinks()
{
	var promo_code_pop = returnObjById('promo_code_pop');
	if(promo_code_pop)
	{
		promo_code_pop.style.display = 'inline';
	}
	
	var sec_code_pop = returnObjById('sec_code_pop');
	if(sec_code_pop)
	{
		sec_code_pop.style.display = 'inline';
	}
	
	var sec_info = returnObjById('sec_info');
	if(sec_info)
	{
		sec_info.style.display = 'inline';
	}
}

function submitStep2()
{
	//document.cart_form.submit_form.value = 1;
}

function initStepOne()
{
	getThemes();
	getMusic();

	if(barcode.length > 0 || customer_code.length > 0)
	{
		//handleThemeClick(current_theme_id);
		loadBarcodeXMLDoc();
	}
	else
	{
		handleThemeClick(current_theme_id);
	}

	setPackage(current_package_name);
	scrollDivToAnchor('themelist','theme_' + current_theme_id);
	level_info_array = getLevelInfo();
	setAllDiscounts();
	updatePricing();
	setDiscountBox();
	
	getDefaultDiscount();
}

function initStepTwo()
{
	var step2_theme_id = document.cart_form.theme_id.value;
	printSelectedName(step2_theme_id, 'theme', 'themeID', 'productName', 'theme_display_name');
	var step2_music_id = document.cart_form.music_id.value;
	printSelectedName(step2_music_id, 'clip', 'songID', 'musicname', 'music_display_name');
	var step2_package_id = document.cart_form.package_name.value;
	printSelectedName(step2_package_id, 'level', 'levelID', 'levelName', 'package_display_name');
	level_info_array = getLevelInfo();
	updatePricing();
	displayCurrentPriceLine();
	
	/* load order review data */
	var my_order_review_loading = returnObjById('my_order_review_loading');
	if(my_order_review_loading)
	{
		my_order_review_loading.style.display = 'none';
	}
	var my_order_review = returnObjById('my_order_review');
	if(my_order_review)
	{
		my_order_review.style.display = 'inline';
	}
	
	/* dogchannel */
	displayStepTwoPackage(current_package_name);
	
	/* Westgate */
	displayStepTwoPricing();
	
	/* employee */
	if(employee_id.length > 0 && vertical == 'kiddiekandids')
	{
		var stepsbilling = returnObjById('stepsbilling');
		stepsbilling.className = 'stepsbillinggrey';
	}
}


/* XML FUNCTIONS */
var req;
function loadCartXMLDoc() {
	req = loadXMLFile('/cartV2/M/cart_xml.php', 'processCartDoc');
}

function processCartDoc()
{
	/* set the default theme ID */
	if(document.location.href.indexOf('step1') != -1 || pagename == '1')
	{
		if(vertical == 'kiddiekandids')
		{
			if(document.cart_form.x_discount_code.value == '')
			{
				getDiscountInfo(document.cart_form.x_discount_code_hidden.value, 1);
			}
			else
			{
				getDiscountInfo(document.cart_form.x_discount_code.value, 1);
			}
		}
		else
		{
			getDiscountInfo(document.cart_form.x_discount_code.value, 1);
		}
	}
	else if(document.location.href.indexOf('step2') != -1)
	{
		getDiscountInfo(document.cart_form.x_discount_code.value, 2);
	}

	var country_select = returnObjById('country_select');
	if(country_select)
	{
		if(cad_rate.length < 1 && gbp_rate.length < 1)
		{
			getXChangeRate('CAD');
			getXChangeRate('GBP');
		}
		var mxn_rate_fld = returnObjById('mxn_rate');
		if(mxn_rate_fld)
		{
			getXChangeRate('MXN');
		}
	}
}


/* BARCODE XML */
var reqBC;
var t;
function loadBarcodeXMLDoc()
{
	if(barcode.length > 0)
	{
		reqBC = loadXMLFile('/API/photos/q2homepics/' + barcode, 'processBarcodeReqChange');
	}
	else if(customer_code.length > 0)
	{
		reqBC = loadXMLFile('/API/photos/kk2homepics/' + customer_code + '?t=' + t, 'processBarcodeReqChange');
	}
}

function processBarcodeReqChange()
{
	var the_status = getXMLTagInfo(reqBC, 'status', 0, '');
	var the_msg = getXMLTagInfo(reqBC, 'msg', 0, '');
	if(the_status == 'Failed')
	{
		alert(the_msg);
		barcode = '';
		document.cart_form.barcode.value = '';
		//handleThemeClick(current_theme_id);
	}
	else if(the_status == 'OK')
	{
		handleThemeClick(current_theme_id);
	}
	else
	{
		alert('An error occurred trying to retrieve the photos.');
		barcode = '';
		handleThemeClick(current_theme_id);
	}
}

var reqPH;
var barcode = '';
var customer_code = '';
var t;
function loadPhotoupdateXMLDoc(the_barcode, uid)
{
	if(vertical == 'kiddiekandids')
	{
		customer_code = the_barcode;
		reqPH = loadXMLFile('/API/photos/kk2album_kick/' + customer_code + '/' + uid + '?t=' + t, 'processPhotoupdateReqChange');
	}
	else
	{
		barcode = the_barcode;
		reqPH = loadXMLFile('/API/photos/q2album_kick/' + barcode + '/' + uid, 'processPhotoupdateReqChange');
	}
}

function processPhotoupdateReqChange()
{
	var the_status = getXMLTagInfo(reqPH, 'status', 0, '');
	var the_msg = getXMLTagInfo(reqPH, 'msg', 0, '');
	if(the_status == 'Failed')
	{
		alert(the_msg);
	}
	else if(the_status == 'OK')
	{
		//alert('Your photos have been processed!');
	}
	else
	{
		alert('An error occurred trying to process the photos.');
	}
}

var pr = '';
var reqPR;
function loadPhotoprogressXMLDoc()
{
	if(barcode.length > 0)
	{
		reqPR = loadXMLFile('/API/photos/qcounter/' + barcode + '?r=' + Math.random(), 'processPhotoprogressReqChange');
	}
	else if(customer_code.length > 0)
	{
		reqPR = loadXMLFile('/API/photos/kkcounter/' + customer_code + '?r=' + Math.random(), 'processPhotoprogressReqChange');
	}
}

function processPhotoprogressReqChange()
{
	var the_total = getXMLTagInfo(reqPR, 'total', 0, '');
	var the_processed = getXMLTagInfo(reqPR, 'processed', 0, '');
	var the_percent = getXMLTagInfo(reqPR, 'percentage', 0, '');
	var remaining = getXMLTagInfo(reqPR, 'remaining', 0, '');
	var is_downloading = getXMLTagInfo(reqPR, 'is_downloading', 0, '');
	var photocounter = returnObjById('photocounter');
	photocounter.innerHTML = 'Processing ' + the_processed + ' of ' + the_total + ' photos...';
	var progressbar = returnObjById('progressbar');
	progressbar.style.width = the_percent + '%';
	
	if(is_downloading == 0)
	{
		var loadingdiv = returnObjById('processingphotos');
		loadingdiv.style.display = 'none';
		var infodiv = returnObjById('newsiteinfo');
		infodiv.style.display = 'inline';
		
		clearInterval(pr);
		if(vertical == 'kiddiekandids')
		{
			var reqCLOSE = loadXMLFile('/API/photos/kkcounter/' + customer_code + '/yes', 'endProcessCheck');
		}
		else
		{
			var reqCLOSE = loadXMLFile('/API/photos/qcounter/' + barcode + '/yes', 'endProcessCheck');
		}
	}
}

function endProcessCheck()
{

}


/* AUTO TAB */
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
		found = true;
	else
		index++;
		return found;
	}
	
	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
		else i++;
		return index;
	}
	return true;
}

/* Westgate */
function displayOwnerMessage()
{
	var have_ownerid_text = returnObjById('have_ownerid_text');
	var owner_id = returnObjById('owner_id');
	if(owner_id.value != '')
	{
		/* check for 10 digit ID */
		var oval = owner_id.value;
		var olen = oval.length;
		if(olen < 10)
		{
			alert('Please enter a valid 10-digit Owner ID');
			have_ownerid_text.style.display = 'none';
			document.cart_form.partner_uid.value = '';
			document.cart_form.x_card_num_1.blur();
			document.cart_form.partner_uid.focus();
		}
		else
		{
			have_ownerid_text.style.display = 'inline';
			document.cart_form.new_username.focus();
		}
	}
	else
	{
		have_ownerid_text.style.display = 'none';
	}
}

function postBarcode()
{
	barcode = document.cart_form.barcode.value;
	loadBarcodeXMLDoc();
}

function processBarcodeImages(barcode, uid)
{
	loadPhotoupdateXMLDoc(barcode, uid);
}

function checkProcessProgress()
{
	loadPhotoprogressXMLDoc();
	pr = setInterval('loadPhotoprogressXMLDoc()', 5000);
}

/* STATES Handling */
function checkState()
{
	var other_state = returnObjById('other_state');
	if(other_state)
	{
		if(document.cart_form.x_state.value == 'Other')
		{
			other_state.style.display = 'block';
		}
		else
		{
			other_state.style.display = 'none';
		}
	}
}
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008/08/28 16:11:40 $
 * $Rev: 5685 $
 */
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "/scripts/thickbox/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$ = jQuery;

$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup,closeText) {//function called when the user clicks on a thickbox link
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			if(closeText) $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>"+closeText+"</a> or Esc Key</div>"); 		
			else $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>Close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						if(closeText) $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>"+closeText+"</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
						else $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>Close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						if(closeText) $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>"+closeText+"</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						else $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}
/*
function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}
*/
function tb_position() {
	if(jQuery.browser.msie)
	{
		$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
			/*$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); */
		}
		else {
			var scrolledDown = $(document).scrollTop()-200;
			/* $("#TB_window").css("margin-top", scrolledDown +"px");*/
		}
	}
	else
	{
		$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
			$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
		}
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}



