 
 /*

Cross-Browser XMLHttpRequest v1.1
=================================

Emulate Gecko 'XMLHttpRequest()' functionality in IE and Opera. Opera requires
the Sun Java Runtime Environment <http://www.java.com/>.

by Andrew Gregory
http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/

This work is licensed under the Creative Commons Attribution License. To view a
copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or send
a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305,
USA.

Not Supported in Opera
----------------------
* user/password authentication
* responseXML data member

Not Fully Supported in Opera
----------------------------
* async requests
* abort()
* getAllResponseHeaders(), getAllResponseHeader(header)

*/
// IE support
if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
  };
}
// Gecko support
/* ;-) */
// Opera support
if (window.opera && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    this.readyState = 0; // 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete
    this.status = 0; // HTTP status codes
    this.statusText = '';
    this._headers = [];
    this._aborted = false;
    this._async = true;
    this.abort = function() {
      this._aborted = true;
    };
    this.getAllResponseHeaders = function() {
      return this.getAllResponseHeader('*');
    };
    this.getAllResponseHeader = function(header) {
      var ret = '';
      for (var i = 0; i < this._headers.length; i++) {
        if (header == '*' || this._headers[i].h == header) {
          ret += this._headers[i].h + ': ' + this._headers[i].v + '\n';
        }
      }
      return ret;
    };
    this.setRequestHeader = function(header, value) {
      this._headers[this._headers.length] = {h:header, v:value};
    };
    this.open = function(method, url, async, user, password) {
      this.method = method;
      this.url = url;
      this._async = true;
      this._aborted = false;
      if (arguments.length >= 3) {
        this._async = async;
      }
      if (arguments.length > 3) {
        // user/password support requires a custom Authenticator class
        opera.postError('XMLHttpRequest.open() - user/password not supported');
      }
      this._headers = [];
      this.readyState = 1;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
    };
    this.send = function(data) {
      if (!navigator.javaEnabled()) {
        alert("XMLHttpRequest.send() - Java must be installed and enabled.");
        return;
      }
      if (this._async) {
        setTimeout(this._sendasync, 0, this, data);
        // this is not really asynchronous and won't execute until the current
        // execution context ends
      } else {
        this._sendsync(data);
      }
    }
    this._sendasync = function(req, data) {
      if (!req._aborted) {
        req._sendsync(data);
      }
    };
    this._sendsync = function(data) {
      this.readyState = 2;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
      // open connection
      var url = new java.net.URL(new java.net.URL(window.location.href), this.url);
      var conn = url.openConnection();
      for (var i = 0; i < this._headers.length; i++) {
        conn.setRequestProperty(this._headers[i].h, this._headers[i].v);
      }
      this._headers = [];
      if (this.method == 'POST') {
        // POST data
        conn.setDoOutput(true);
        var wr = new java.io.OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();
      }
      // read response headers
      // NOTE: the getHeaderField() methods always return nulls for me :(
      var gotContentEncoding = false;
      var gotContentLength = false;
      var gotContentType = false;
      var gotDate = false;
      var gotExpiration = false;
      var gotLastModified = false;
      for (var i = 0; ; i++) {
        var hdrName = conn.getHeaderFieldKey(i);
        var hdrValue = conn.getHeaderField(i);
        if (hdrName == null && hdrValue == null) {
          break;
        }
        if (hdrName != null) {
          this._headers[this._headers.length] = {h:hdrName, v:hdrValue};
          switch (hdrName.toLowerCase()) {
            case 'content-encoding': gotContentEncoding = true; break;
            case 'content-length'  : gotContentLength   = true; break;
            case 'content-type'    : gotContentType     = true; break;
            case 'date'            : gotDate            = true; break;
            case 'expires'         : gotExpiration      = true; break;
            case 'last-modified'   : gotLastModified    = true; break;
          }
        }
      }
      // try to fill in any missing header information
      var val;
      val = conn.getContentEncoding();
      if (val != null && !gotContentEncoding) this._headers[this._headers.length] = {h:'Content-encoding', v:val};
      val = conn.getContentLength();
      if (val != -1 && !gotContentLength) this._headers[this._headers.length] = {h:'Content-length', v:val};
      val = conn.getContentType();
      if (val != null && !gotContentType) this._headers[this._headers.length] = {h:'Content-type', v:val};
      val = conn.getDate();
      if (val != 0 && !gotDate) this._headers[this._headers.length] = {h:'Date', v:(new Date(val)).toUTCString()};
      val = conn.getExpiration();
      if (val != 0 && !gotExpiration) this._headers[this._headers.length] = {h:'Expires', v:(new Date(val)).toUTCString()};
      val = conn.getLastModified();
      if (val != 0 && !gotLastModified) this._headers[this._headers.length] = {h:'Last-modified', v:(new Date(val)).toUTCString()};
      // read response data
      var reqdata = '';
      var stream = conn.getInputStream();
      if (stream) {
        var reader = new java.io.BufferedReader(new java.io.InputStreamReader(stream));
        var line;
        while ((line = reader.readLine()) != null) {
          if (this.readyState == 2) {
            this.readyState = 3;
            if (this.onreadystatechange) {
              this.onreadystatechange();
            }
          }
          reqdata += line + '\n';
        }
        reader.close();
        this.status = 200;
        this.statusText = 'OK';
        this.responseText = reqdata;
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onload) {
          this.onload();
        }
      } else {
        // error
        this.status = 404;
        this.statusText = 'Not Found';
        this.responseText = '';
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onerror) {
          this.onerror();
        }
      }
    };
  };
}
// ActiveXObject emulation
if (!window.ActiveXObject && window.XMLHttpRequest) {
  window.ActiveXObject = function(type) {
    switch (type.toLowerCase()) {
      case 'microsoft.xmlhttp':
      case 'msxml2.xmlhttp':
        return new XMLHttpRequest();
    }
    return null;
  };
} 
 //=================================================================
// JavaScript IE5/Mozilla XML Wrapper
// Version 1.0
// by Nicholas C. Zakas, nicholas@nczonline.net
// Copyright (c) 2002 Nicholas C. Zakas.  All Rights Reserved.
//-----------------------------------------------------------------
// Browsers Supported:
//	* Mozilla 0.9.2+ (Netscape 6+)
//  * Internet Explorer 5.0+
//=================================================================
// History
//-----------------------------------------------------------------
// January 30, 2002 (Version 1.0)
//  - Works in Netscape 6.0+ and IE 5.0+  
//=================================================================
// Software License
// Copyright (c) 2002 Nicholas C. Zakas.  All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer. 
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// 3. The end-user documentation included with the redistribution,
//    if any, must include the following acknowledgment:  
//       "This product includes software developed by the
//        Nicholas C. Zakas (http://www.nczonline.net/)."
//    Alternately, this acknowledgment may appear in the software itself,
//    if and wherever such third-party acknowledgments normally appear.
//
// 4. Redistributions of any form are free for use in non-commercial
//    ventures. If intent is to use in a commercial product, contact
//    Nicholas C. Zakas at nicholas@nczonline.net for purchasing of
//    a commercial license.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.  IN NO EVENT SHALL NICHOLAS C. ZAKAS  BE LIABLE FOR ANY 
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------
// Any questions, comments, or suggestions should be e-mailed to 
// nicholas@nczonline.net.  For more information, please visit
// http://www.nczonline.net/. 
//=================================================================

//Possible prefixes ActiveX strings for DOM DOcument
var ARR_ACTIVEX = ["MSXML4.DOMDocument", "MSXML3.DOMDocument", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XmlDom"];

//When the proper prefix is found, store it here
var STR_ACTIVEX = "";

//browser detection
var isSafari = false;
var isMoz = false;
var isIE = false; 

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

var isSafari = BrowserDetect.browser == "Safari" || BrowserDetect.browser == "Konqueror"?true:false;
var isMoz = BrowserDetect.browser == "Mozilla" || BrowserDetect.browser == "Firefox" || BrowserDetect.browser == "Netscape"?true:false;
var isIE = BrowserDetect.browser == "Explorer"?true:false;

//End browser detection

//-----------------------------------------------------------------
// IE Initialization
//-----------------------------------------------------------------

//if this is IE, determine which string to use
if (isIE && !isMoz) {
    //define found flag
    var bFound = false;
   
    //iterate through strings to determine which one to use (NCZ, 1/30/02)
    for (var i=0; i < ARR_ACTIVEX.length && !bFound; i++) {
    
        //set up try...catch block for trial and error of strings (NCZ, 1/30/02)
        try {
        
            //try to create the object, it will cause an error if it doesn't work (NCZ, 1/30/02)
            var objXML = new ActiveXObject(ARR_ACTIVEX[i]);
            
            //if it gets to this point, the string worked, so save it and return
            //the DOM Document (NCZ, 1/30/02)
            STR_ACTIVEX = ARR_ACTIVEX[i];
            bFound = true                
        
        } catch (objException) { 
        } //End: try
    } //End: for

    //if we didn't find the string, send an error (NCZ, 1/30/02)
    if (!bFound)
       throw "No DOM DOcument found on your computer."

} //End: if

//-----------------------------------------------------------------
// Mozilla Initialization
//-----------------------------------------------------------------

if(!isSafari && isMoz){
    //add the loadXML() method to the Document class
    Document.prototype.loadXML = function(strXML) {   
        //change the readystate
        changeReadyState(this, 1);
        //create a DOMParser
        var objDOMParser = new DOMParser();
        
        //create new document from string
        var objDoc = objDOMParser.parseFromString(strXML, "text/xml");
        //make sure to remove all nodes from the document
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
            
        //add the nodes from the new document
        for (var i=0; i < objDoc.childNodes.length; i++) {
            
            //import the node
            var objImportedNode = this.importNode(objDoc.childNodes[i], true);
            
            //append the child to the current document
            this.appendChild(objImportedNode);
        
        } //End: for

        //we can't fire the onload event, so we fake it
        handleOnLoad(this);
        
    } //End: function
    //add the getter for the .xml attribute
    Node.prototype.__defineGetter__("xml", _Node_getXML);
    
    try{
		//add the readystate attribute for a Document
		Document.prototype.readyState = "0";
        }
	catch(e)
	{
	}
	
    //save a reference to the original load() method
    Document.prototype.__load__ = Document.prototype.load;

    //create our own load() method
    Document.prototype.load = _Document_load;
    
    //add the onreadystatechange attribute
    Document.prototype.onreadystatechange = null;
    
    //add the parseError attribute
    Document.prototype.parseError = 0;
    
}//End: if

//-----------------------------------------------------------------
// Factory jsXML
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 1/30/02
//
// Description
//  This factory will serve as the entry point for other XML-related
//  implementations.
//
// Parameters
//  (none)
//-----------------------------------------------------------------

function jsXML() { }

//-----------------------------------------------------------------
// Function jsXML.createDocument()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 1/30/02
//
// Description
//  This function creates a XML Document according to which browser
//  is being used.
//
// Parameters
//  strNamespaceURI (String) - the namespace for this document (optional).
//  strRootTagName (String) - the tag name for the documentElement (optional).
//
// Returns
//  The XML Document object that was created.
//-----------------------------------------------------------------
jsXML.createDOMDocument = function(strNamespaceURI, strRootTagName) {

    //variable for the created DOM Document
    var objDOM = null;
    
    //determine if this is a standards-compliant browser like Mozilla
    if (isMoz || isSafari) {
    
        //create the DOM Document the standards way
        objDOM = document.implementation.createDocument(strNamespaceURI, strRootTagName, null);    
    
        //add the event listener for the load event
        objDOM.addEventListener("load", _Document_onload, false);
        
    } else if (isIE) {
    
        //create the DOM Document the IE way
        objDOM = new ActiveXObject(STR_ACTIVEX);

        //if there is a root tag name, we need to preload the DOM
        if (strRootTagName) {
       
            //If there is both a namespace and root tag name, then
            //create an artifical namespace reference and load the XML.  
            if (strNamespaceURI) {
                objDOM.loadXML("<a0:" + strRootTagName + " xmlns:a0=\"" + strNamespaceURI + "\" />");
            } else {
                objDOM.loadXML("<" + strRootTagName + "/>");        
            }
        
        }
    }
    
    //return the object
    return objDOM;
}

//-----------------------------------------------------------------
// Functon _Node_getXML()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 2/23/02
//
// Description
//  This is the attribute getter for the .xml attribute.
//
// Parameters
//  (none)
//
// Returns
//  A string with the XML of the Node calling this function.
//-----------------------------------------------------------------
function _Node_getXML() {
    
    //create a new XMLSerializer
    var objXMLSerializer = new XMLSerializer;
    
    //get the XML string
    var strXML = objXMLSerializer.serializeToString(this);
    
    //return the XML string
    return strXML;
}


//-----------------------------------------------------------------
// Function _Document_load()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 2/24/02
//
// Description
//  This function replaces the native load() method to allow for
//  readyState changes.
//
// Parameters
//  strURL (String) - The XML file to load.
//
// Returns
//  (nothing)
//-----------------------------------------------------------------
function _Document_load(strURL) {

    //set the parseError to 0
    this.parseError = 0;

    //change the readyState
    changeReadyState(this, 1);
    
    //watch for errors
    try {
        //call the original load method
        this.__load__(strURL);
        
    } catch (objException) {
    
        //set the parseError attribute
        this.parseError = -9999999;
        
        //change the readystate
        changeReadyState(this, 4);

    } // End: try...catch
}

//-----------------------------------------------------------------
// Function _Document_onload()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 2/24/02
//
// Description
//  This function is the event handler for the load event.
//
// Parameters
//  (none)
//
// Returns
//  (nothing)
//-----------------------------------------------------------------
function _Document_onload() {

    //handle the onload event
    handleOnLoad(this);
}

//-----------------------------------------------------------------
// Function handleOnLoad()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 2/24/02
//
// Description
//  This function handles the load event on the Document object.
//
// Parameters
//  objDOMDocument (Document) - the DOM Document object that has been loaded.
//
// Returns
//  (nothing)
//-----------------------------------------------------------------
function handleOnLoad(objDOMDocument) {
    //check for a parsing error
    if (!objDOMDocument.documentElement || objDOMDocument.documentElement.tagName == "parsererror")
        objDOMDocument.parseError = -9999999;

    //change the readyState
    changeReadyState(objDOMDocument, 4);
}

//-----------------------------------------------------------------
// Function changeReadyState()
//-----------------------------------------------------------------
// Author(s)
//  Nicholas C. Zakas (NCZ), 2/24/02
//
// Description
//  This function changes the readyState of a Document to the desired
//  state and runs any event handler the user has assigned.
//
// Parameters
//  objDOMDocument (Document) - the DOM Document object that has been loaded.
//  iReadyState (int) - the readyState to set the DOM Document to.
//
// Returns
//  (nothing)
//-----------------------------------------------------------------
function changeReadyState(objDOMDocument, iReadyState) {
	try{
		//change the readyState
		objDOMDocument.readyState = iReadyState;
	    
		//if there is an onreadystatechange event handler, run it
		if (objDOMDocument.onreadystatechange != null && typeof objDOMDocument.onreadystatechange == "function")
			objDOMDocument.onreadystatechange();
    }
	catch(e)
	{
	}
}


	function JSObjectFromXML(str,bol){
		var XML = null;
//		var ie = (typeof window.ActiveXObject != 'undefined');
		if(isIE){
			XML = new ActiveXObject("Microsoft.XMLDOM");
			XML.async = false;
			while(XML.readyState != 4) {};
			if(bol){//use for url
				XML.load(str);
			}
			else{
				XML.loadXML(str);//use for string
			}
		}
		else{
			XML = document.implementation.createDocument("", "", null);
			if(bol){//use for url
				XML.load(str);
			}
			else{//use for string
				var doc = (new DOMParser()).parseFromString(str, "text/xml");
				while (XML.hasChildNodes())
					XML.removeChild(XML.lastChild);
				for (var i = 0; i < doc.childNodes.length; i++) {
				   XML.appendChild(XML.importNode(doc.childNodes[i], true));
				}
			}
		}
		for(var i=0;i<5;i++){
			if((null!=XML.childNodes)&&(XML.childNodes.length>0)){
				i = 6;
			}
			else{
				i = i;
			}
		}
		var js = new JSObject(XML.childNodes[0]);
		return js;
	}
	
	function XMLObject(str,bol){
		var XML = null;
//		var ie = (typeof window.ActiveXObject != 'undefined');
		if(isIE){
			XML = new ActiveXObject("Microsoft.XMLDOM");
			XML.async = false;
			while(XML.readyState != 4) {};
			if(bol){//use for url
				XML.load(str);
			}
			else{
				XML.loadXML(str);//use for string
			}
		}
		else{
			XML = document.implementation.createDocument("", "", null);
			if(bol){//use for url
				XML.load(str);
			}
			else{//use for string
				var doc = (new DOMParser()).parseFromString(str, "text/xml");
				while (XML.hasChildNodes())
					XML.removeChild(XML.lastChild);
				for (var i = 0; i < doc.childNodes.length; i++) {
				   XML.appendChild(XML.importNode(doc.childNodes[i], true));
				}
			}
		}
		for(var i=0;i<5;i++){
			if((null!=XML.childNodes)&&(XML.childNodes.length>0)){
				i = 6;
			}
			else{
				i = i;
			}
		}
		return XML;
	}

	function JSObject(xmlObj){
		if(null == xmlObj) return null;
		
		var arr = new Array();
		if((xmlObj.nodeType==1)&&(xmlObj.childNodes.length>0)){
			if((xmlObj.childNodes[0].nodeName+'s'==xmlObj.nodeName)||('ArrayOf'+xmlObj.childNodes[0].nodeName==xmlObj.nodeName)){//collection
				for(var i=0;i<xmlObj.childNodes.length;i++){
					if(null!=xmlObj.childNodes[i].childNodes){
						arr[arr.length] = new JSObject(xmlObj.childNodes[i]);
					}
				}
			}
			else{//not a collection
				for(var c=0;c<xmlObj.childNodes.length;c++){
					if((null!=xmlObj.childNodes[c].childNodes)&&(xmlObj.childNodes[c].childNodes.length>0)&&(xmlObj.childNodes[c].childNodes[0].nodeType==1)){
						arr[xmlObj.childNodes[c].nodeName] = new JSObject(xmlObj.childNodes[c]);
					}
					else if((null!=xmlObj.childNodes[c].childNodes)&&(xmlObj.childNodes[c].childNodes.length>0)&&(xmlObj.childNodes[c].childNodes[0].nodeType==3)){
						arr[xmlObj.childNodes[c].nodeName] = xmlObj.childNodes[c].childNodes[0].nodeValue;
					}
					else{
						arr[xmlObj.childNodes[c].nodeName] = "";
					}
				}
			}
		}
		//all objects should have type property defined.
		arr["Type"] = xmlObj.nodeName;
		return arr;
	} 
 function GetTranslation(Indef)
{
	try
	{
		if('undefined' != typeof(MessAdmin[Indef]))
		{
			return (MessAdmin[Indef]);
		}
		if('undefined' != typeof(arguments[1]))
		{
			return (arguments[1]);
		}
	}
	catch(e){}
	return (Indef);
}

function GetTranslationPaymentTypes(Indef)
{
if('undefined' != typeof(MessAdmin[Indef]))
	{
	return (MessAdmin[Indef]);
	}
var t = "" + Indef;
t=t.substring(13,t.length);
return (t);
}	 
 var gShoppingCartURL='Sales_Cart.aspx';
var gUpdateTotals = true;

function GetObjectByName(objName)
{
	var obj = null;
	switch(objName)
	{
		case "deliverymethodselect":
			if(gEBI('deliverymethodUniqueId')!=null)
			{
				obj = gEBI(gEBI('deliverymethodUniqueId').value);
				if(obj == null)
					obj = gEBN(gEBI('deliverymethodUniqueId').value)[0];
			}
			break;
		case "paymentmethodselect":
			if(gEBI('paymentmethodUniqueId')!=null)
			{
			obj = gEBI(gEBI('paymentmethodUniqueId').value);
			if(obj == null)
				obj = gEBN(gEBI('paymentmethodUniqueId').value)[0];
			}
			break;
	}
	
	return obj;
}

//----------------------:UpdateTotals-----------------------------------------
function updateTotals(){
	if(!gUpdateTotals)
		return;
	var oSelPaymentMethod = GetObjectByName("paymentmethodselect"); 
	var oSelDeliveryMethod = GetObjectByName("deliverymethodselect"); 
	
	if(null == oSelPaymentMethod || null == oSelDeliveryMethod)
		return; //return immediatetely if PayCart is not found

	//disable enable payment button
	$("#divProcOrder").hide();

	if(isWeb && aryPayTypes.length == 0){
		var selOption = oSelPaymentMethod.options[oSelPaymentMethod.selectedIndex];
		aryPayTypes[0] = new Object();
		aryPayTypes[0].PaymenttypesClientId = selOption.getAttribute('PaymenttypesClientId');
		aryPayTypes[0].initIndex = 0;
		aryPayTypes[0].Value = selOption.value;
	}
	
	if(null != gEBI("h_AccountBalance"))
		gEBI("h_AccountBalance").value = gEBI("h_AccountBalance").getAttribute("BaseAmount");
	
	arrTkPerf		= new Array();
	arrTickets		= new Array();
	arrSubscriptions= new Array();
	arrTkPerTypes  = new Array();
	arrItems		= new Array();
	
	var ttlTbaseTotal = 0; //stores total before any discounts or fees
	var ttlTBaseTotalTPS=0;    // store total for TPS
	var S = 0;
	if(gEBI('h_SubCounts'))
		S = Number(gEBI('h_SubCounts').value);
	
	var oTP; 

	if(arguments[0]!=null) oTP= arguments[0];
	else if(gEBI('trSubscription_0')!= null)oTP=gEBI('trSubscription_0').parentNode;
	if(oTP==null && gEBI('trSubscriptionColumns')!= null) oTP=gEBI('trSubscriptionColumns').parentNode;
	
	var oSubscriptionRowsArray = null;
	if(oTP!=null)
	{
		oSubscriptionRowsArray = getChildrenByPartialIdOrName(oTP, "trSubscription_");
	}
	
	var ttlS = 0;
	var sAmount=0;
	var Missed = 0;
	var sFound = 0;
	var pSeasonPackageId = ",";
	if(S>0 && oSubscriptionRowsArray!=null && oSubscriptionRowsArray.length>0){ //if we have any subscriptions
		for(var s=0;sFound<S;s++){
			if("undefined" != typeof(gEBI("trSubscription_"+s)) && gEBI("trSubscription_"+s) != null)
			{	
				sFound++;
				//keep track of seasonpackage ids for orderfees calcs
				if(gEBI('hSeasonPackage_' + s) != null)
					pSeasonPackageId += gEBI('hSeasonPackage_' + s).value + ","; 
				
				var oTicketTypeSelect = gEBI('SubscriptionTicketType_' + s);
				gEBI('txtSubscriptionPrice_' + s).value=parseFloat2(oTicketTypeSelect.options[oTicketTypeSelect.selectedIndex].getAttribute('Amount'));
				
				var subscriptionPrice = parseFloat2(gEBI('txtSubscriptionPrice_' + s).value);

				ttlTbaseTotal += subscriptionPrice;
				sAmount+=subscriptionPrice;
				
				var lSubscriptionGroup = new Group(1, subscriptionPrice);
				lSubscriptionGroup.SeasonTickets = new Array();
				arrSubscriptions[s]=lSubscriptionGroup;
				
				var oSubFee = gEBI('txtSubscriptionFee_' + s);
				if(null == oSubFee)
					continue;
				
				arrSubscriptions[s].calculateTicketDiscountsAndFees(oSubFee, "fee", oTicketTypeSelect, oSelDeliveryMethod, null);
				var ST = 0;
				var MissedST = 0;
				var seasonTicketPrice = 0;
				var oCountTix = getChildByIdOrName(gEBI('txtSubscriptionPrice_' + s).parentNode.parentNode, 'hCount_' + s, true);
				var oSeasonTicketPrice = getChildByIdOrName(gEBI('txtSubscriptionPrice_' + s).parentNode.parentNode, 'hSeasonTicketPrice_' + s, true);
				if(null != oCountTix)
					ST = Number(oCountTix.value);
				if(null != oSeasonTicketPrice)
					seasonTicketPrice = Number(oSeasonTicketPrice.value);
					
				//check if season ticket list price is not set properly
				if(seasonTicketPrice == 0 && subscriptionPrice != 0 && ST > 0)
					seasonTicketPrice = Number(Number(subscriptionPrice) /  Number(ST));
				else
					if(seasonTicketPrice != 0 && subscriptionPrice == 0 && ST > 0)
						seasonTicketPrice = 0;
						
				for(var st=0;st<ST;st++)
				{
					if(gEBI("hEventName_"+s+"_"+st)!=null)
					{
						var oSTFee = gEBI("hEventName_"+s+"_"+st);
						
						arrSubscriptions[s].SeasonTickets[st]=new Group(1, seasonTicketPrice);
						
						arrSubscriptions[s].SeasonTickets[st].calculateTicketDiscountsAndFees(oSTFee, "fee", null, oSelDeliveryMethod, gEBI('hSeasonPackage_' + s).value);
						arrSubscriptions[s].nCumulativeFeeAmount += arrSubscriptions[s].SeasonTickets[st].nCumulativeFeeAmount;
						arrSubscriptions[s].nFeeAmountPerTicketGroup += arrSubscriptions[s].SeasonTickets[st].nFeeAmountPerTicketGroup;
						oSTFee.parentNode.parentNode.title="Fee: $" +parseFloat2(arrSubscriptions[s].SeasonTickets[st].nCumulativeFeeAmount).toFixed(2);
					}
					else
					{
						MissedST++;
					}
				}

				var oDivGroupedSubFees = getChildByIdOrName(gEBI('txtSubscriptionPrice_' + s).parentNode.parentNode, "divGroupedSubscriptionTicketFees_"+s, true);
				arrSubscriptions[s].buildFeeGroup(oDivGroupedSubFees);

				//calculate final subscriptio. price

				oSeasonTicketPrice.value = (seasonTicketPrice+arrSubscriptions[s].nCumulativeHiddenFeeAmount).toFixed(2);
				gEBI('txtSubscriptionPrice_' + s).value = (subscriptionPrice+arrSubscriptions[s].nCumulativeHiddenFeeAmount).toFixed(2);			
								
				var nSubscriptionCount=1;
				
				if(gEBI("txtSTixQty"+s)!=null) 
					nSubscriptionCount= gEBI("txtSTixQty"+s).value;
					
				if(nSubscriptionCount<1) 
					nSubscriptionCount=1;
					
				var nSubscriptionFinalPrice = parseFloat2((subscriptionPrice + arrSubscriptions[s].nFeeAmountPerTicketGroup + arrSubscriptions[s].nCumulativeHiddenFeeAmount).toFixed(2))*nSubscriptionCount;
				ttlS += nSubscriptionFinalPrice;
				//alert(gEBI('txtSubscriptionFee_' + s));
				
				
				gEBI('txtSubscriptionFee_' + s).value = arrSubscriptions[s].nCumulativeFeeAmount.toFixed(2);
				gEBI('txtSubscriptionFinalPrice_' + s).value = nSubscriptionFinalPrice.toFixed(2);
			}
			else
			{
				Missed++;
			}	
		}
		gEBI('txtSubscriptionTotal').value = parseFloat2(ttlS).toFixed(2);
		ChangePriceAmmountInSession('Subscriptions',parseFloat2(ttlS).toFixed(2));
	}

	var T = 0;
	if(gEBI('h_TicketCounts'))
		T = Number(gEBI('h_TicketCounts').value);

	if(arguments[0]!=null) oTP= arguments[0];
	else if(gEBI('trTicket_0')!= null)oTP=gEBI('trTicket_0').parentNode;
	if(oTP==null && gEBI('trTicketColumns')!= null) oTP=gEBI('trTicketColumns').parentNode;
		
	var oTicketRowsArray = null;
	if(oTP!=null)
	{
		oTicketRowsArray = getChildrenByPartialIdOrName(oTP, "trTicket_");
	}
	
	var ttlT = 0;
	var tAmount=0;
	if(T>0 && oTicketRowsArray!=null && oTicketRowsArray.length>0){
	var lAllTixQty = 0;
	var Missed = 0;
	arrDiscountIDs = new Array();
	
	for(var t=0;t<T;t++)
	{ // for calculating discounts for tickettypes	
		var jsPerfId = $("#h_PerformanceID"+t);
		if(0 <= jsPerfId.length)
		{
			Missed++;
			continue;
		}
		
		var oTicketTypeSelect = getChildByIdOrName(oTicketRowsArray[t-Missed], "TicketType_"+t, true);
		var perfId = jsPerfId.val();
		
		if(null == oTicketTypeSelect)
			continue;
		if(oTicketTypeSelect.selectedIndex < 0)
			continue;
			
		var oOpt = oTicketTypeSelect.options[oTicketTypeSelect.selectedIndex];
		var currentlySelectedTicketType = $(oOpt).attr("TicketType");
		if(null == currentlySelectedTicketType || "" == currentlySelectedTicketType)
			continue;
		
		if(arrTkPerTypes[perfId+"tp_"+currentlySelectedTicketType]==null) 
			arrTkPerTypes[perfId+"tp_"+currentlySelectedTicketType]=1; 
		else
			arrTkPerTypes[perfId+"tp_"+currentlySelectedTicketType]++; 
	}
	
		
		Missed = 0;
		for(var t=0;t<T;t++){
			if("undefined" != typeof(gEBI("h_PerformanceID"+t)) && gEBI("h_PerformanceID"+t) != null)
			{
		    var perfId=gEBI("h_PerformanceID"+t).value;
		    var GA = gEBI("h_TicketGA"+t).value;
			var oTicketTypeSelect = getChildByIdOrName(oTicketRowsArray[t-Missed], "TicketType_"+t, true);
			var oTixQty = getChildByIdOrName(oTicketRowsArray[t-Missed], "txtTixQty"+t, true);
			var nTixQty = 1; //may be different for grouped GA tix
			if(null != oTixQty)
				nTixQty = Number(oTixQty.value);
			lAllTixQty += nTixQty;
            
			if (typeof( arrTkPerf[perfId]) =="undefined")
				arrTkPerf[perfId]=null; 
			if (null==arrTkPerf[perfId])
			{//create new entry nto Array
			    var tempObj = new Object()	
				tempObj.perfId=perfId;
				tempObj.cntTickets=nTixQty;
				arrTkPerf[perfId]=tempObj;
			}else
				arrTkPerf[perfId].cntTickets = parseInt(arrTkPerf[perfId].cntTickets)+nTixQty;
			
			var attrAmount = oTicketTypeSelect.options[oTicketTypeSelect.selectedIndex].getAttribute('Amount');
			var ticketPriceInput = getChildByIdOrName(oTicketRowsArray[t-Missed], "txtTicketPrice_"+t, true);
			
			var ticketPrice = parseFloat2(attrAmount);
			
			var lTicketGroup = new Group(nTixQty, ticketPrice);
			lTicketGroup.PerfId  = perfId;
			lTicketGroup.nPosition = t-Missed;
			arrTickets[t]=lTicketGroup;
			
			tAmount += (RoundTo(ticketPrice,.01,"Mathematical")*nTixQty);
			ttlTbaseTotal += (RoundTo(ticketPrice,.01,"Mathematical")*nTixQty);

			var oTkDiscount = getChildByIdOrName(oTicketRowsArray[t-Missed], "txtTicketDiscount_"+t, true);
			var oTkSingleTixDiscount = getChildByIdOrName(oTicketRowsArray[t-Missed], "hTicketDiscountNotGrouped_"+t, true);
			var oTkFee = getChildByIdOrName(oTicketRowsArray[t-Missed], "txtTicketFee_"+t, true);
			
			var oTkSingleTixFee = getChildByIdOrName(oTicketRowsArray[t-Missed], "hTicketFeeNotGrouped_"+t, true);
			if(null == oTkFee || null == oTkSingleTixFee || null == oTkDiscount || null == oTkSingleTixDiscount)
				continue;
			
			arrTickets[t].calculateTicketDiscountsAndFees(oTkDiscount, "discount", oTicketTypeSelect, oSelDeliveryMethod, null);
			arrTickets[t].calculateTicketExtra(t);
			arrTickets[t].calculateTicketDiscountsAndFees(oTkFee, "fee", oTicketTypeSelect, oSelDeliveryMethod, null);
			

			var oDivGroupedTkFees = getChildByIdOrName(oTicketRowsArray[t-Missed], "divGroupedTicketFees_"+t, true);
			var oDivGroupedTkDiscounts = getChildByIdOrName(oTicketRowsArray[t-Missed], "divGroupedTicketDiscounts_"+t, true);
			arrTickets[t].buildFeeGroup(oDivGroupedTkFees);
			arrTickets[t].buildDiscountGroup(oDivGroupedTkDiscounts);

			if(arrTickets[t].nCumulativeDiscountAmount > (ticketPrice + arrTickets[t].nCumulativeFeeAmount)*nTixQty )
				arrTickets[t].nCumulativeDiscountAmount = ticketPrice + arrTickets[t].nCumulativeFeeAmount;
			var nTicketFinalPrice=0;

			//calculate final ticket price
			ticketPriceInput.value = (ticketPrice+arrTickets[t].nCumulativeHiddenFeeAmount).toFixed(2);
			ticketPriceInput.setAttribute("Amount",ticketPrice.toFixed(2));
			nTicketFinalPrice = (ticketPrice + arrTickets[t].nCumulativeFeeAmount + arrTickets[t].nCumulativeHiddenFeeAmount);
			var nCumulativeTotalPrice = 0;
			$(arrTickets[t].Items).each(function (index, element) {
			    nCumulativeTotalPrice += RoundTo(ticketPrice + element.nFeeAmount, .01, "Mathematical");
			});
			nTicketFinalPrice = nCumulativeTotalPrice - arrTickets[t].nDiscountAmountPerTicketGroup; //multiply it by number of tix, for grouped GA
			
			if(nTicketFinalPrice < 0) nTicketFinalPrice = 0;
			nTicketFinalPrice = Number(nTicketFinalPrice.toFixed(2));
			ttlT += nTicketFinalPrice;

			oTkDiscount.value = (arrTickets[t].nCumulativeDiscountAmount).toFixed(2);
			oTkSingleTixDiscount.value = arrTickets[t].nCumulativeDiscountAmount.toFixed(2);
			oTkFee.value = (arrTickets[t].nCumulativeFeeAmount).toFixed(2);
			oTkSingleTixFee.value = arrTickets[t].nCumulativeFeeAmount.toFixed(2);
			
			getChildByIdOrName(oTicketRowsArray[t-Missed], "hTicketFinalPriceNotGrouped_"+t, true).value = (ticketPrice - arrTickets[t].nDiscountAmountPerTicketGroup + arrTickets[t].nCumulativeFeeAmount).toFixed(2);
			getChildByIdOrName(oTicketRowsArray[t-Missed], "txtTicketFinalPrice_"+t, true).value = nTicketFinalPrice.toFixed(2);
			}
			else
			{
			Missed++;
			}
		}
		gEBI('txtTicketTotal').value = parseFloat2(ttlT).toFixed(2);
		ChangePriceAmmountInSession('SingleTickets',parseFloat2(ttlT).toFixed(2));
	}

	if(arguments[0]!=null) oTP= arguments[0];
	else if(gEBI('trCouponOrder_0')!= null) oTP=gEBI('trCouponOrder_0').parentNode;
	if(oTP==null && gEBI('trOtherColumns')!= null) oTP=gEBI('trOtherColumns').parentNode;

	var oCouponsRowsArray = null;
	if(oTP!=null) oCouponsRowsArray = getChildrenByPartialIdOrName(oTP, "trCouponOrder_");
	
	var CPO = 0;
	var ttlOther = 0;
	if(gEBI('h_CouponOrderCounts'))
		CPO = Number(gEBI('h_CouponOrderCounts').value);

    if (CPO>0 && oCouponsRowsArray != null && oCouponsRowsArray.length>0)      
	{	
	var Missed = 0;
		for(var cpo=0;cpo<CPO;cpo++){
			if("undefined" != typeof(gEBI("hCouponOrder_"+cpo)) && gEBI("hCouponOrder_"+cpo) != null)
			{
			var price = gEBN('hCouponOrder')[cpo-Missed].getAttribute('ListPrice');
			var quantity = gEBN('hCouponOrder')[cpo-Missed].getAttribute('Quantity');
			var total = parseFloat2(price) * parseInt(quantity);
			gEBI('txtCouponOrderFinalPrice_' + cpo).value = parseFloat2(total).toFixed(2);
			ttlOther += total;
			ttlTbaseTotal += total;
			}
			else
			{
			Missed++;
			}
		}
	}

	if(arguments[0]!=null) oTP= arguments[0];
	else if(gEBI('trCouponPackageOrder_0')!= null) oTP=gEBI('trCouponPackageOrder_0').parentNode;
	if(oTP==null && gEBI('trOtherColumns')!= null) oTP=gEBI('trOtherColumns').parentNode;

	var oCouponPackagesRowsArray = null;
	if(oTP!=null) oCouponPackagesRowsArray = getChildrenByPartialIdOrName(oTP, "trCouponPackageOrder_");

	var CPKO = 0;
	if(gEBI('h_CouponPackageOrderCounts'))
		CPKO = Number(gEBI('h_CouponPackageOrderCounts').value);
		
    if (CPKO>0 && oCouponPackagesRowsArray != null && oCouponPackagesRowsArray.length>0)      
	{	
		var Missed = 0;
		for(var cpko=0;cpko<CPKO;cpko++){
			if("undefined" != typeof(gEBI("hCouponPackageOrder_"+cpko)) && gEBI("hCouponPackageOrder_"+cpko) != null)
			{
			var price = gEBN('hCouponPackageOrder')[cpko-Missed].getAttribute('ListPrice');
			var quantity = gEBN('hCouponPackageOrder')[cpko-Missed].getAttribute('Quantity');
			var total = parseFloat2(price) * parseInt(quantity);
			gEBI('txtCouponPackageOrderFinalPrice_' + cpko).value = parseFloat2(total).toFixed(2);
			ttlOther += total;
			ttlTbaseTotal += total;
			}
			else
			{
			Missed++;
			}
		}
	}
	
	if(arguments[0]!=null) oTP= arguments[0];
	if(gEBI('OtherItemsSpan')!= null) oTP=gEBI('OtherItemsSpan');

	var oItemsRowsArray = null;
	if(oTP!=null) oItemsRowsArray = getChildrenByPartialIdOrName(oTP, "trItemOrder_",true);
	var IO = 0;
	if(gEBI('h_ItemOrderCounts'))
		IO = Number(gEBI('h_ItemOrderCounts').value);
	
	var ttlDonations = 0;
	
    if (IO>0 && oItemsRowsArray != null && oItemsRowsArray.length>0)      
	{
	  var Missed = 0;
	  var iTotalPoints=0; 
	  for(var i=0;i<IO;i++)	
	  {
	  	if("undefined" != typeof(gEBI("hItemOrder_"+i)) && gEBI("hItemOrder_"+i) != null)
			{
			if(oItemsRowsArray[i-Missed].getAttribute("type")!=null && oItemsRowsArray[i-Missed].getAttribute("type")=="donation")
			{
					var total = parseFloat2(gEBI('txtItemOrderPrice_' + i).value);
					ttlDonations += total;
					ttlTbaseTotal += total;				
			}
			else
			{
				 var oItDiscount = getChildByIdOrName(oItemsRowsArray[i-Missed], "txtItemOrderDiscount_"+i, true);
				 var oItem=getChildByIdOrName(oItemsRowsArray[i-Missed], "hItemOrder_"+i, true);
	 			 var itemID = gEBN('hItemOrder')[i-Missed].getAttribute('ItemId');
				 if (gEBN('hItemOrder')[i-Missed].getAttribute('CanSellWithPoints')=='true' && gEBN('hItemOrder')[i-Missed].getAttribute('AddedToTPSTransaction')=='true' )
					   ttlTBaseTotalTPS+=gEBN('hItemOrder')[i-Missed].getAttribute('Points')*parseInt(gEBN('hItemOrder')[i-Missed].getAttribute('Quantity'));
				
				var lItemGroup = new Group( parseInt(gEBN('hItemOrder')[i-Missed].getAttribute('Quantity')), parseFloat2(gEBN('hItemOrder')[i-Missed].getAttribute('ListPrice')));
				lItemGroup.nPosition = i-Missed;
				arrItems[i]=lItemGroup;
				
				var oItemFee = getChildByIdOrName(oItemsRowsArray[i-Missed], "txtItemOrderFee_"+i, true);
				
				if(oItemFee != null)
				{	
					arrItems[i].calculateTicketDiscountsAndFees(oItemFee, "fee", null, null, null);
					oItemFee.value = (arrItems[i].nCumulativeFeeAmount).toFixed(2);
				}
			
				var total = (parseFloat2(gEBN('hItemOrder')[i-Missed].getAttribute('ListPrice')) * parseInt(gEBN('hItemOrder')[i-Missed].getAttribute('Quantity')))-TotalDiscounts(oItDiscount,i)+arrItems[i].nCumulativeFeeAmount* parseInt(gEBN('hItemOrder')[i-Missed].getAttribute('Quantity'))+ arrItems[i].nCumulativeHiddenFeeAmount* parseInt(gEBN('hItemOrder')[i-Missed].getAttribute('Quantity'));
					
				if (null!=gEBI('txtItemOrderFinalPrice_' + i))
						gEBI('txtItemOrderFinalPrice_' + i).value = parseFloat2(total).toFixed(2);
				if (gEBN('hItemOrder')[i-Missed].getAttribute('AddedToTPSTransaction')=='false' ){
					   ttlOther += total;
					   ttlTbaseTotal += total;}
			 }
			}
			else
			{
			Missed++;
			}
	   }
	 }
	 if ( null!=gEBI('txtOtherTotalTPS')){
	     gEBI('txtOtherTotalTPS').value=ttlTBaseTotalTPS; 
	  }
	if(gEBI('txtOtherTotal'))
		gEBI('txtOtherTotal').value = parseFloat2(ttlOther).toFixed(2);
	
	ChangePriceAmmountInSession('Items',parseFloat2(ttlOther).toFixed(2));  
	
	if(gEBI('txtDonationsTotal'))
		gEBI('txtDonationsTotal').value = parseFloat2(ttlDonations).toFixed(2);

	var TOTAL = ttlS + ttlT + ttlOther+ttlDonations;
	
	gEBI("txtSubTotal").value = parseFloat2(TOTAL).toFixed(2);
	
	//order discounts and fees
	var oOrderDollarDiscount = document.getElementById("h_OrderDollarDiscount");
	var oOrderPercentageDiscount = document.getElementById("h_OrderPercentageDiscount");
    
	var nOrderDollarFees = 0;
	var nOrderPercentageFees = 0;
	var nOrderDollarFees_AboveAllOtherFees = 0;
	var nOrderPercentageFees_AboveAllOtherFees = 0;
	
	var nOrderHiddenDollarFees = 0;
	var nOrderHiddenPercentageFees = 0;
	var nOrderHiddenDollarFees_AboveAllOtherFees = 0;
	var nOrderHiddenPercentageFees_AboveAllOtherFees = 0;
	
	var arrOrderFees = gEBN("h_OrderFees");
	var arrOrderCodeDiscounts = gEBN("h_OrderCodeDiscounts");
	
	var sEventIds = "";
	var sOrderFeeIds = "";
	var sDeliveryMethodId = "0";
	var sPaymentMethodIds = ",";
	var arrGroups = new Array();
	
	if(null == pSeasonPackageId) 
		pSeasonPackageId = "";
	
	sDeliveryMethodId = oSelDeliveryMethod.value;

	for(var i=0; i<aryPayTypes.length; i++)
		sPaymentMethodIds += aryPayTypes[i].PaymenttypesClientId+",";

	if(null != gEBI("h_EventIds"))
		sEventIds = gEBI("h_EventIds").value;
	var lHTMLOrderExtraFees = "<table><tr><td style='BACKGROUND-COLOR: #20577F' align='right'><B onclick=\"gEBI('divOrderExtraFees').style.display='none';\" style='WIDTH: 15px; CURSOR: pointer; COLOR: red'>X</B></td></tr>";
	
	var OrderCodePercentageDiscount=0;
	var OrderCodeDollarDiscount=0;
	if(arrOrderCodeDiscounts!=null && arrOrderCodeDiscounts.length>0)
	{
		gEBI("lblDiscountActivationCode").style.display="block";
		gEBI("inpDiscountActivationCode").style.display="block";
		for(var i=0; i<arrOrderCodeDiscounts.length; i++)
		{
			var oDiscount = arrOrderCodeDiscounts[i];
			if(gEBI("txtDiscountActivationCode").value !="" && gEBI("txtDiscountActivationCode").value.toUpperCase()==oDiscount.getAttribute("ActivationCode").toUpperCase())
			{
				if(oDiscount.getAttribute("dollaramount")!=null) OrderCodeDollarDiscount+=Number(oDiscount.getAttribute("dollaramount"));
				if(oDiscount.getAttribute("percentageamount")!=null) OrderCodePercentageDiscount+=Number(oDiscount.getAttribute("percentageamount"));
			}
		}
	}	
	for(var i=0; i<arrOrderFees.length; i++)
	{
		var nOrderDollarFee = 0;
		var nOrderPercentageFee = 0;
		var nOrderDollarFee_AboveAllOtherFees = 0;
		var nOrderPercentageFee_AboveAllOtherFees = 0;
				
		var oFee = arrOrderFees[i];
		if(	(Number(oFee.getAttribute("DeliveryMethodId")) == 0 || oFee.getAttribute("DeliveryMethodId") == sDeliveryMethodId) && 
			(Number(oFee.getAttribute("PaymenttypesClientId")) == 0 || sPaymentMethodIds.indexOf(","+oFee.getAttribute("PaymenttypesClientId")+",") != -1) &&
			((oFee.getAttribute("AppliesTo") == "OrderWithSeasonPackage" && null != gEBI("trSubscriptionHeader"))||
			(oFee.getAttribute("AppliesTo") == "OrderWithCoupons" && null != gEBI("trOtherHeader"))||
			oFee.getAttribute("AppliesTo") == "Order" || oFee.getAttribute("AppliesTo") == "OrderBalanceFee" )
		)
		{
			if(0 == Number(oFee.getAttribute("priceceiling"))||( Number(oFee.getAttribute("pricefloor")) < ttlTbaseTotal && ttlTbaseTotal <= Number(oFee.getAttribute("priceceiling"))))
			{
				if(oFee.getAttribute("Extra")!="true")
				{
					if(oFee.getAttribute("Global")!="false" || /*oFee.getAttribute("AppliesTo") == "OrderWithSeasonPackage" || */oFee.getAttribute("AppliesTo") == "OrderWithCoupons")//OrderWithSeasonPackage was already Checked
					{
						sOrderFeeIds +=oFee.getAttribute("feeID")+",";
						if(null != oFee.getAttribute("dollaramount"))
						{
							if(oFee.getAttribute("AboveAllOtherFees") != null && oFee.getAttribute("AboveAllOtherFees").toLowerCase() !="true")
							{
								nOrderDollarFee += Number(oFee.getAttribute("dollaramount"));
							}
							else
							{
								nOrderDollarFee_AboveAllOtherFees += Number(oFee.getAttribute("dollaramount"));
							}
						}
						if(null != oFee.getAttribute("percentageamount"))
						{
							var nFeeCap = oFee.getAttribute("cap");
							if(null == nFeeCap || "" == nFeeCap) nFeeCap="0";
							
							nFeeCap = Number(nFeeCap);
							if(0 != Number(nFeeCap) && ( (oFee.getAttribute("CalculateAfterDiscounts") != "true" && (Number(oFee.getAttribute("percentageamount"))*ttlTbaseTotal/100) > nFeeCap) || (oFee.getAttribute("CalculateAfterDiscounts") == "true" && (Number(oFee.getAttribute("percentageamount"))*TOTAL/100) > nFeeCap) ))
							{
								
								nOrderDollarFee += nFeeCap;
							}
							else
							{
								if(oFee.getAttribute("AboveAllOtherFees") != null && oFee.getAttribute("AboveAllOtherFees").toLowerCase() !="true")
								{
									nOrderPercentageFee += Number(oFee.getAttribute("percentageamount"));
								}
								else
								{
									nOrderPercentageFee_AboveAllOtherFees += Number(oFee.getAttribute("percentageamount"));
								}
							}
						}
						
						if(null == arrGroups[oFee.getAttribute("FeeGroupId")])
						{
							arrGroups[oFee.getAttribute("FeeGroupId")] = new Object();
							arrGroups[oFee.getAttribute("FeeGroupId")].Name = oFee.getAttribute("FeeGroupName");
							if("" == arrGroups[oFee.getAttribute("FeeGroupId")].Name)
								arrGroups[oFee.getAttribute("FeeGroupId")].Name = "Other";
							arrGroups[oFee.getAttribute("FeeGroupId")].Amount = 0;
							arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee = 0;
							arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee_AboveAllOtherFees = 0;
							arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee = 0;
							arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee_AboveAllOtherFees = 0;
						}
						//Add Fee Amount to Group
						arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee += nOrderDollarFee;
						arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee_AboveAllOtherFees += nOrderDollarFee_AboveAllOtherFees;
						arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee += nOrderPercentageFee;
						arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee_AboveAllOtherFees += nOrderPercentageFee_AboveAllOtherFees;
					}
					else
					{
						var lAddEvt = oFee.getAttribute("AddEvt");
						lAddEvt = lAddEvt.replace(/,True/g,"").replace(/,False/g,"");
						var lArrEvts = lAddEvt.split(";");
						for(var j=0; j<lArrEvts.length-1;j++)
						{
							if( (sEventIds.indexOf(","+lArrEvts[j] + ",") != -1) ||  (pSeasonPackageId != "" && pSeasonPackageId.indexOf(","+lArrEvts[j] + ",") != -1))
							{
								sOrderFeeIds +=oFee.getAttribute("feeID")+",";
								if(null != oFee.getAttribute("dollaramount"))
								{
									if(oFee.getAttribute("AboveAllOtherFees")!="true")
									{
										nOrderDollarFee += Number(oFee.getAttribute("dollaramount"));
									}
									else
									{
										nOrderDollarFee_AboveAllOtherFees += Number(oFee.getAttribute("dollaramount"));
									}

								}
								if(null != oFee.getAttribute("percentageamount"))
								{
									var nFeeCap = oFee.getAttribute("cap");
									if(null == nFeeCap || "" == nFeeCap) nFeeCap="0";

									nFeeCap = Number(nFeeCap);
									if(0 != Number(nFeeCap) && (Number(oFee.getAttribute("percentageamount"))*ttlTbaseTotal/100) > nFeeCap)
										nOrderDollarFee += nFeeCap;
									else
									{
										if(oFee.getAttribute("AboveAllOtherFees")!="true")
											nOrderPercentageFee += Number(oFee.getAttribute("percentageamount"));
										else
											nOrderPercentageFee_AboveAllOtherFees += Number(oFee.getAttribute("percentageamount"));
									}
								}
								
								if(null == arrGroups[oFee.getAttribute("FeeGroupId")])
								{
									arrGroups[oFee.getAttribute("FeeGroupId")] = new Object();
									arrGroups[oFee.getAttribute("FeeGroupId")].Name = oFee.getAttribute("FeeGroupName");
									if("" == arrGroups[oFee.getAttribute("FeeGroupId")].Name)
										arrGroups[oFee.getAttribute("FeeGroupId")].Name = "Other";
									arrGroups[oFee.getAttribute("FeeGroupId")].Amount = 0;
									arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee = 0;
									arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee_AboveAllOtherFees = 0;
									arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee = 0;
									arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee_AboveAllOtherFees = 0;
								}
								//Add Fee Amount to Group
								arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee += nOrderDollarFee;
								arrGroups[oFee.getAttribute("FeeGroupId")].nOrderDollarFee_AboveAllOtherFees += nOrderDollarFee_AboveAllOtherFees;
								arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee += nOrderPercentageFee;
								arrGroups[oFee.getAttribute("FeeGroupId")].nOrderPercentageFee_AboveAllOtherFees += nOrderPercentageFee_AboveAllOtherFees;
								break;
							}

						}
					}
				}
				
				else
				{//build OrderExtraFees table
					var lODF = 0;
					var lOPF = 0;

					if(null != oFee.getAttribute("dollaramount"))
						lODF = Number(oFee.getAttribute("dollaramount"));
					
					if(null != oFee.getAttribute("percentageamount"))
						lOPF = Number(oFee.getAttribute("percentageamount"));
					lODF = (lOPF*ttlTbaseTotal/100) + lODF;
					
					if (oFee.getAttribute("AppliesTo") != "OrderBalanceFee")
					{
						lHTMLOrderExtraFees+="<tr><td style='CURSOR: pointer;' onmouseover='this.bgColor=\"#FCE37E\"' onmouseout='this.bgColor=\"\"' onclick='AddOrderExtraFee("+lODF+","+oFee.getAttribute("feeID")+");updateTotals();'>"+oFee.getAttribute("feeName")+"</td></tr>";
					}

					if (oFee.getAttribute("AppliesTo")=="OrderBalanceFee" && null!=gEBI("btnBalanceOrderFee") )
					{
					   gEBI("btnBalanceOrderFee").style.display = "inline";
					   gEBI("btnBalanceOrderFee").setAttribute("feeID", oFee.getAttribute("feeID"));
					}

				}
				
			}
		}
			/*get rounding info.  if none exists default to mathematical to the nearest .01*/
			var sRoundingType = oFee.getAttribute("roundingtype");
			if("" == sRoundingType || null == sRoundingType)
				sRoundingType = "Mathematical";
			var nRoundTo = parseFloat2(oFee.getAttribute("roundto"));
			if("" == nRoundTo || null == nRoundTo || isNaN(nRoundTo))
				nRoundTo = .01;
			nRoundTo = Number(nRoundTo).toFixed(2);

		if(oFee.getAttribute("Hidden")!="true")
		{
			nOrderDollarFees += nOrderDollarFee;
			nOrderPercentageFees += RoundTo((nOrderPercentageFee*TOTAL/100), nRoundTo, sRoundingType);
			nOrderDollarFees_AboveAllOtherFees += nOrderDollarFee_AboveAllOtherFees;
			nOrderPercentageFees_AboveAllOtherFees += nOrderPercentageFee_AboveAllOtherFees;
		}	
		else
		{
			nOrderHiddenDollarFees += nOrderDollarFee;
			nOrderHiddenPercentageFees += nOrderPercentageFee;
			nOrderHiddenDollarFees_AboveAllOtherFees += nOrderDollarFee_AboveAllOtherFees;
			nOrderHiddenPercentageFees_AboveAllOtherFees += nOrderPercentageFee_AboveAllOtherFees;
		}
	}
	lHTMLOrderExtraFees += "</table>";
	
	if(null != gEBI("divOrderExtraFees"))
		gEBI("divOrderExtraFees").innerHTML = lHTMLOrderExtraFees;
		
	gEBI("h_OrderDollarFee").value = nOrderDollarFees;
	gEBI("h_OrderPercentageFee").value = nOrderPercentageFees;
	var nTotalFees = nOrderPercentageFees + nOrderDollarFees;
	var nTotalHiddenFees = RoundTo((nOrderHiddenPercentageFees*TOTAL/100), nRoundTo, sRoundingType) + nOrderHiddenDollarFees;
	
	var nTotalDiscounts = ((Number(oOrderPercentageDiscount.value)+OrderCodePercentageDiscount)*TOTAL/100) + Number(oOrderDollarDiscount.value)+OrderCodeDollarDiscount;
	if(nTotalDiscounts > TOTAL)
		nTotalDiscounts = TOTAL;
	var nTotalExtraFees = 0;
	if(null != gEBI("txtExtraOrderFees"))
		nTotalExtraFees = Number(gEBI('txtExtraOrderFees').getAttribute('ExtraFeeAmount'));

	if(null != gEBI("txtExtraOrderFees"))
		gEBI('txtExtraOrderFees').value = parseFloat2(nTotalExtraFees).toFixed(2);

	for(xx in arrGroups)
		if(null != arrGroups[xx].Name)
		{
			arrGroups[xx].Amount += RoundTo((arrGroups[xx].nOrderPercentageFee*TOTAL/100), nRoundTo, sRoundingType) + arrGroups[xx].nOrderDollarFee;
		}

	TOTAL += nTotalFees;
	TOTAL += nTotalExtraFees;
	TOTAL += nTotalHiddenFees;

	if(nTotalDiscounts > 0)
	{
		TOTAL -= nTotalDiscounts;
		gEBI('txtOrderDiscounts').value = parseFloat2(nTotalDiscounts).toFixed(2);
		gEBI('txtOrderDiscounts').parentNode.parentNode.style.display = "";
	}
	else
		gEBI('txtOrderDiscounts').value="0.00";
	var nTotalFees_AboveAllOtherFees = RoundTo((nOrderPercentageFees_AboveAllOtherFees*TOTAL/100), nRoundTo, sRoundingType);
	var nTotalHiddenFees_AboveAllOtherFees = RoundTo((nOrderHiddenPercentageFees_AboveAllOtherFees*TOTAL/100), nRoundTo, sRoundingType) +nOrderHiddenDollarFees_AboveAllOtherFees;
	
		for(xx in arrGroups)
		if(null != arrGroups[xx].Name)
		{
			arrGroups[xx].Amount += RoundTo((arrGroups[xx].nOrderPercentageFee_AboveAllOtherFees*TOTAL/100), nRoundTo, sRoundingType) + arrGroups[xx].nOrderDollarFee_AboveAllOtherFees;
		}

	TOTAL += nTotalFees_AboveAllOtherFees;
	TOTAL += nTotalHiddenFees_AboveAllOtherFees;
	nTotalFees += nTotalFees_AboveAllOtherFees;
	
	//Fill pDiv
	var strTbl = "<TABLE>";
	for(xx in arrGroups)
		if(null != arrGroups[xx].Name && 0 != arrGroups[xx].Amount)
			strTbl += "<TR><TD nowrap>"+arrGroups[xx].Name+"</TD><TD>"+parseFloat2(arrGroups[xx].Amount).toFixed(2)+"</TD></TR>";
	strTbl += "</TABLE>";
	gEBI("divGroupedOrderFees").innerHTML = strTbl;
	
	var nTotalBalanceFees = 0;
	var nOldTotalBalanceFees = 0;
	if(null != gEBI("txtBalanceOrderFee"))
	{
		nTotalBalanceFees = Number(gEBI('txtBalanceOrderFee').getAttribute('BalanceFeeAmount'));
		nOldTotalBalanceFees = Number(gEBI('txtBalanceOrderFee').getAttribute('OldBalanceFeeAmount'));
	}

	TOTAL += nTotalBalanceFees;
	TOTAL += nOldTotalBalanceFees;
	//update fees field
	gEBI('txtOrderFees').value = parseFloat2(nTotalFees).toFixed(2);
	gEBI('txtOrderFees').setAttribute("OrderFeeIds", sOrderFeeIds);
	gEBI('txtOrderFees').parentNode.parentNode.style.display = "";
	
	if(null != gEBI("txtBalanceOrderFee"))
		gEBI('txtBalanceOrderFee').value = parseFloat2(nTotalBalanceFees+nOldTotalBalanceFees).toFixed(2);

	if(gEBI('h_sumSubTotal'))
		TOTAL += parseFloat2(gEBI('h_sumSubTotal').value);
	if(gEBI('txtWasPaid'))
		TOTAL -= parseFloat2(gEBI('txtWasPaid').value);
	gOrderTotal = TOTAL;
	gOrderTotalTPS=ttlTBaseTotalTPS;
	
	if ( null!=gEBI('displayOrderBalanceTotalTPS')){
	    gEBI('displayOrderBalanceTotalTPS').value=ttlTBaseTotalTPS.toFixed(2); 
	 }
	gEBI('txtTotal').value = parseFloat2(TOTAL).toFixed(2);
	if(null != gEBI('txtTotalTPS'))gEBI('txtTotalTPS').value=ttlTBaseTotalTPS.toFixed(2);
	gEBI('txtTotal').onchange();
	updateTotalItems(lAllTixQty,tAmount,S,sAmount);
	
	EnableDisableTransaction();
	CheckTransactionTotals(null, false);

	

	if(null!=gEBI("lbTPSBalance"))
	{
		gEBI("lbTPSBalance").innerHTML = ReturnAvailableTPS();
	}



    var jqTxtBalanceOrderFee = $("#txtBalanceOrderFee");
    var jqBtnBalanceOrderFee = $("#btnBalanceOrderFee");

    if (jqTxtBalanceOrderFee.length > 0 && jqBtnBalanceOrderFee.length > 0) {

        var nBalanceFeeAmt = Number(jqTxtBalanceOrderFee.attr("BalanceFeeAmount"));
        var nTxtTotal = Number(gEBI("txtTotal").value);

        var lAddBalanceValue = Number(nBalanceFeeAmt - nTxtTotal);
		if(lAddBalanceValue < 0) lAddBalanceValue = 0;
		lAddBalanceValue = lAddBalanceValue - nBalanceFeeAmt;
		
		var lSign = "";
		if (lAddBalanceValue > 0) lSign = "+";

		if (jqBtnBalanceOrderFee.length > 0) {
		    jqBtnBalanceOrderFee.attr("title", lSign + String(parseFloat2(lAddBalanceValue).toFixed(2)));

		    if (nTxtTotal == 0 || (nTotalBalanceFees == 0 && nTxtTotal > 0))
		        jqBtnBalanceOrderFee.show();
		}
    }

    //finally enable payment button
    $("#divProcOrder").show();

}
//------------------------------------------------------------------------------------------------

//---------------------------------:OrderPay------------------------------------------------------
function GenerateOrderXML(ContainPrintAtHome)
{
	try
	{
	var strOrderXML = "";
	strTransXML = "";
	//build order xml
	dt = new Date();
	var nAmount = 0;
	var nBaseOrderAmount = 0;

	nBaseOrderAmount += parseFloat2( $("#txtSubscriptionTotal").val() );
	nBaseOrderAmount += parseFloat2( $("#txtTicketTotal").val() );
	nBaseOrderAmount += parseFloat2( $("#txtOtherTotal").val() );
	nBaseOrderAmount += parseFloat2( $("#txtDonationsTotal").val() );
	nBaseOrderAmount = RoundTo(nBaseOrderAmount);
	
	var transactionTypeId = 0;
	for(var i=0; i<aryPayTypes.length;i++)
	{
		var oPayField = gEBI(String('pay_' + aryPayTypes[i].initIndex + '_total'));
		if(null == oPayField)
		{
			aryPayTypes.splice(i,1);
			continue;
		}
		nAmount += parseFloat2(oPayField.value);
		
		/*switch(String(aryPayTypes[i].Value).toLowerCase())
		{
			case "paypal":
				transactionTypeId = 10;
				gOrderCompleted = 2;
				break;
			case "wire":
				transactionTypeId = 11;
				gOrderCompleted = 2;
				break;
			case "webmoney":
				transactionTypeId = 12;
				gOrderCompleted = 2; //pending payment
				break;
			case "clicknbuy":
				transactionTypeId = 37;
				gOrderCompleted = 2; //pending payment
				break;
			case "ceca":
				transactionTypeId = 38;
				gOrderCompleted = 2; //pending payment
				break;
		}*/
	}

    if (gEBI('txtWasPaid') && !isNaN(gEBI('txtWasPaid').value) )
        nAmount += parseFloat2(gEBI('txtWasPaid').value);

	var strCommentXML = $("#textOrderComments").val();
	if("undefined" == typeof(strCommentXML))
		strCommentXML = "";		
	if(Trim(strCommentXML) != "")
		strCommentXML = "<OrderComments><OrderComment><Comment><![CDATA[" + Trim(strCommentXML) + "]]></Comment></OrderComment></OrderComments>";
		
	strOrderXML = "<Order>";
	strOrderXML +=	"<ID>" + oParentIDHolder["gEditOrderId"] + "</ID>";
	strOrderXML +=	"<Client><ID>" + gClientId + "</ID></Client><Completed>" + gOrderCompleted +"</Completed>";
	if(null != gEBI("txtExtraOrderFees"))
		strOrderXML +=	"<ExtraFeeIDs>"+gEBI("txtExtraOrderFees").getAttribute("ExtraFeeIDs") + "</ExtraFeeIDs>";
	
	if(null != gEBI("txtBalanceOrderFee"))
		strOrderXML +=	"<BalanceFeeAmount>"+gEBI("txtBalanceOrderFee").getAttribute("BalanceFeeAmount") + "</BalanceFeeAmount>";
		
	strOrderXML +=	"<OrderFeeIDs>"+gEBI('txtOrderFees').getAttribute("OrderFeeIds") + "</OrderFeeIDs>";

	if(isWeb)
		strOrderXML +=	"<BATCHID>1</BATCHID>";
	else
		strOrderXML +=	"<BATCHID>0</BATCHID>";
	strOrderXML +=  OrderBuildBillingAddressXML();
	if(!isNaN(nAmount))
		strOrderXML +=	"<AmountPaid>" + nAmount + "</AmountPaid>";	
	else
		strOrderXML +=	"<AmountPaid>0</AmountPaid>";	
	strOrderXML +=	"<BaseAmount>" + nBaseOrderAmount + "</BaseAmount>";
	
		var lOrderDollarFee = 0;
	if(null != gEBI('txtOrderFees'))
		lOrderDollarFee +=	parseFloat2(gEBI('txtOrderFees').value);
		
	if(null != gEBI('txtExtraOrderFees'))
		lOrderDollarFee += parseFloat2(gEBI('txtExtraOrderFees').value);

	strOrderXML +=	"<OrderDollarFee>" + lOrderDollarFee + "</OrderDollarFee>";
	
	if(null != gEBI('txtOrderDiscounts'))
		strOrderXML +=	"<OrderDollarDiscount>" + parseFloat2(gEBI('txtOrderDiscounts').value) + "</OrderDollarDiscount>";
	
	strOrderXML +=	"<OrderDateString>" + dt.toLocaleDateString() + "</OrderDateString>";

	var oSelDeliveryMethod = GetObjectByName("deliverymethodselect"); 
	if(null != oSelDeliveryMethod)  
	{
		var sDelivMethodName = "";
		if(oSelDeliveryMethod.selectedIndex >= 0)
			sDelivMethodName = oSelDeliveryMethod[oSelDeliveryMethod.selectedIndex].innerHTML; 
		strOrderXML +=	"<DeliveryMethod><ID>" + oSelDeliveryMethod.value + "</ID><Name>" + sDelivMethodName + "</Name></DeliveryMethod>";
	}
	else 
		strOrderXML +=	"<DeliveryMethod><ID>137</ID></DeliveryMethod>";
	//add transaction information for order
	var strTransactionsXML = "";

	strTransactionsXML = OrderBuildTransactionsXML();
	if( strTransactionsXML == false )
			return false;
	//strTransactionsXML = "";

	strOrderXML += strTransactionsXML;
	strOrderXML += strCommentXML;
	var arrOrderCodeDiscounts = gEBN("h_OrderCodeDiscounts");
	var OrderCodePercentageDiscount=0;
	var OrderCodeDollarDiscount=0;
	var DiscountsXML = gEBI('h_OrderDiscountsXML').value;
	if(arrOrderCodeDiscounts!=null && arrOrderCodeDiscounts.length>0)
	{
		gEBI("lblDiscountActivationCode").style.display="block";
		gEBI("inpDiscountActivationCode").style.display="block";
		var CodeDiscountsXML="";
		for(var i=0; i<arrOrderCodeDiscounts.length; i++)
		{
			var oDiscount = arrOrderCodeDiscounts[i];
			if(gEBI("txtDiscountActivationCode").value!="" && gEBI("txtDiscountActivationCode").value.toUpperCase()==oDiscount.getAttribute("ActivationCode").toUpperCase())
			{
				if(oDiscount.getAttribute("dollaramount")!=null) OrderCodeDollarDiscount+=Number(oDiscount.getAttribute("dollaramount"));
				if(oDiscount.getAttribute("percentageamount")!=null) OrderCodePercentageDiscount+=Number(oDiscount.getAttribute("percentageamount"));
				CodeDiscountsXML+="<OrderDiscount>";
				CodeDiscountsXML+="<Discount>";
				CodeDiscountsXML+="<ID>"+oDiscount.getAttribute("discountID")+"</ID>";
				CodeDiscountsXML+="<ModifierCode>"+encoder(oDiscount.getAttribute("modifierCode"))+"</ModifierCode>";
				CodeDiscountsXML+="<Units>"+oDiscount.getAttribute("Units")+"</Units>";
				CodeDiscountsXML+="<Amount>"+oDiscount.getAttribute("Amount")+"</Amount>";
				CodeDiscountsXML+="<ActivationCode>"+gEBI("txtDiscountActivationCode").value+"</ActivationCode>";				
				CodeDiscountsXML+="</Discount>";
				CodeDiscountsXML+="<ModifierCode>"+encoder(oDiscount.getAttribute("modifierCode"))+"</ModifierCode>";
				CodeDiscountsXML+="<Amount>"+oDiscount.getAttribute("Amount")+"</Amount>";
				CodeDiscountsXML+="</OrderDiscount>";
			}
		}
		CodeDiscountsXML+="</OrderDiscounts>";
		if(DiscountsXML!="") DiscountsXML = DiscountsXML.replace("</OrderDiscounts>",CodeDiscountsXML);
		else DiscountsXML="<OrderDiscounts>"+CodeDiscountsXML;
	}
	strOrderXML += DiscountsXML;
	strOrderXML += "<OrderDollarDiscount>" + String(Number(gEBI('h_OrderDollarDiscount').value)+OrderCodeDollarDiscount) + "</OrderDollarDiscount>";
	strOrderXML += "<OrderPercentageDiscount>" +  String(Number(gEBI('h_OrderPercentageDiscount').value)+OrderCodePercentageDiscount) + "</OrderPercentageDiscount>";
	
	var lIncPs = 0;
	if(null != gEBI("h_AccountBalance"))
		lIncPs = parseInt(parseInt(gEBI("h_AccountBalance").value) - parseInt(gEBI("h_AccountBalance").getAttribute("BaseAmount")));
	
	if(!isNaN(lIncPs))
		strOrderXML += "<OrderIncomingPoints>" + lIncPs + "</OrderIncomingPoints>";
	
	strOrderXML += "<OrderDollarFee>" + gEBI('h_OrderDollarFee').value + "</OrderDollarFee>";
	strOrderXML += "<OrderPercentageFee>" + gEBI('h_OrderPercentageFee').value + "</OrderPercentageFee>";
	strOrderXML += "<TransactionTypeId>" + transactionTypeId + "</TransactionTypeId>";
	strOrderXML += "</Order>";
	
	//add 'new' ticket type & prices information into tickets xml
	//strTicketXML = "<ArrayOfTicket>";
	
	
	var strTicketsXML = "<Tickets>";
	var ticketquantity = parseInt(gEBI('h_TicketCounts').value);
	for (t=0; t<ticketquantity; t++)
	{
	if(gEBI("txtTicketPrice_" + t)!=null)
	{
		var strTicketXML = ""//"<Ticket GA='" + String(gEBI("h_TicketGA" + t).value) + "'>";
		strTicketXML += "<ID>" + String(gEBI("h_TicketId" + t).value) + "</ID>";
		strTicketXML += "<TicketPrice><PriceAmount>" + String(gEBI("txtTicketPrice_" + t).getAttribute("Amount")) + "</PriceAmount></TicketPrice>";

		strTicketXML +=	"<TicketType>";
		strTicketXML +=		"<ID>" + gEBI("TicketType_" + t).options[gEBI("TicketType_" + t).selectedIndex].getAttribute("TicketType") + "</ID>";
		strTicketXML +=		"<Name>" + gEBI("TicketType_" + t).options[gEBI("TicketType_" + t).selectedIndex].innerHTML + "</Name>";
		strTicketXML +=	"</TicketType>";

		strTicketXML +=	"<Performance>";
		strTicketXML +=		"<ID>" + gEBI("h_PerformanceID" + t).value + "</ID>";
		strTicketXML +=		"<DateTime>" + gEBI("h_PerformanceDateTime" + t).value + "</DateTime>";
		strTicketXML +=		"<Name>" + encoder(gEBI("h_EventName" + t).value) + "</Name>";
		strTicketXML +=	"</Performance>";

		//add ticket custom text
		var oCustomTextInput = gEBI("TicketCustomTicketText_" + t);
		if(oCustomTextInput != null)
			strTicketXML +=	"<CustomText>" + oCustomTextInput.value + "</CustomText>";
			
		var lTicketGA = String(gEBI("h_TicketGA" + t).value);
		var lTicketGroup = arrTickets[t];

		strTicketXML +=	"<FeeAmount>" + lTicketGroup.nCumulativeFeeAmount + "</FeeAmount>";
		for(var xx=0;xx<lTicketGroup.nTixQty;xx++)
		{
		
			var lFeesXML = "";
				lFeesXML +=	"<Fees>";
				for(var i=0; i< lTicketGroup.Items[xx].Fees.length; i++)
				{
					var lFee = lTicketGroup.Items[xx].Fees[i];
					lFeesXML +=		"<Fee><ID>" + lFee.ID + "</ID><Amount>" + lFee.Amount + "</Amount></Fee>";
				}
				lFeesXML +=	"</Fees>";
				
			var lDiscsXML = "";
				lDiscsXML +=	"<Discounts>";
				for(var i=0; i< lTicketGroup.Items[xx].Discounts.length; i++)
				{
					var lDiscount = lTicketGroup.Items[xx].Discounts[i];
					lDiscsXML +=		"<Discount><ID>" + lDiscount.ID + "</ID><ActivationCode>"+lDiscount.ActivationCode+"</ActivationCode><ModifierCode>" + encoder(lDiscount.modifierCode) + "</ModifierCode><Amount>" + lDiscount.Amount + "</Amount></Discount>";
				}
				lDiscsXML +=	"</Discounts>";
			strTicketsXML += "<Ticket GA='" + lTicketGA + "'>"+strTicketXML+lDiscsXML+lFeesXML+"</Ticket>";
		}
	}
	}
	//strTicketXML += "</ArrayOfTicket>";
	strTicketsXML += "</Tickets>";
	gOrder["TicketsXML"] = strTicketsXML; 
	
		//build patron address XML
		var strPatronXML = "<Patron>";
		if(Trim(gEBI("patron_id").value) != "")
			strPatronXML += "<ID>" + String(gEBI("patron_id").value) + "</ID>";
			
		if (null!=gEBI("txtLoginPassword") && Trim(gEBI("txtLoginPassword").value) != "")
			strPatronXML+="<LoginPassword><![CDATA["+String(gEBI("txtLoginPassword").value) +"]]></LoginPassword>";  
		if (null!=gEBI("txtLoginEmail") && Trim(gEBI("txtLoginEmail").value) != "")
			strPatronXML+="<LoginEmail><![CDATA["+String(gEBI("txtLoginEmail").value) +"]]></LoginEmail>";  
			
		if(null!=gEBI("patron_updateaddress"))
		strPatronXML += "<UpdatePatronAddress>"+gEBI("patron_updateaddress").checked+"</UpdatePatronAddress>";
		//patronemail
		
		
		var strPhoneType = $("#patron_phonetype option:selected").val();
		var strEmailType = $("#patron_emailtype option:selected").val();
		if(strEmailType != "" && typeof(strEmailType) != "undefined")
		{
			strPatronXML += "<EmailType>";
			strPatronXML +=		"<ID>" + strEmailType + "</ID>";
			strPatronXML += "</EmailType>";
		}
		
		if("0" != buildCustomXML(gEBI("patron_email"),"EmailAddress"))
		{
			strPatronXML += "<Email>";
			strPatronXML +=	"<ID>0</ID>"+buildCustomXML(gEBI("patron_email"),"EmailAddress");
			strPatronXML += "</Email>";
		}
		else return false;
		
		//patronphone
		if(strPhoneType != "" && typeof(strPhoneType) != "undefined")
		{
			strPatronXML += "<PhoneType>";
			strPatronXML +=		"<ID>" + strPhoneType + "</ID>";
			strPatronXML += "</PhoneType>";
		}
	
		var inpPhones		= gEBN("AdditionalPhones");
		var selPhoneTypes	= gEBN("AdditionalPhoneTypes");

		for(var i = 0; i < inpPhones.length; i++)
		{
			if(inpPhones[i].getAttribute('PatronPhoneId') == 0 && inpPhones[i].getAttribute('PhoneId') == '-1')
				continue;
			strPatronXML += "<PatronPhones>";
			strPatronXML +=		"<PatronPhone><ID>"+inpPhones[i].getAttribute('PatronPhoneId')+"</ID>";
			strPatronXML +=		"<Phone><ID>"+inpPhones[i].getAttribute('PhoneId')+"</ID><PhoneNumber>"+inpPhones[i].value+"</PhoneNumber></Phone>";
			if(selPhoneTypes.length != 0)
				strPatronXML +=		"<PhoneType><ID>"+selPhoneTypes[i].value+"</ID></PhoneType>";
			else
				strPatronXML +=		"<PhoneType><ID>0</ID></PhoneType>";
			strPatronXML +=		"</PatronPhone>";
			strPatronXML += "</PatronPhones>"
		
		}
		if("0" != buildCustomXML(gEBI("patron_phone"),"PhoneNumber")) 
		{
			strPatronXML += "<Phone>";
			strPatronXML +=	"<ID>0</ID>"+buildCustomXML(gEBI("patron_phone"),"PhoneNumber");
			strPatronXML += "</Phone>";
		}
		else return false;
		//BILLING ADDRESS
		//strPatronXML += "<PatronAddress>";
		var strAddressXML = "";
		strAddressXML += "<Address>";
		strAddressXML +=		"<ID>" + gEBI('patron_billingaddressid').value + "</ID>";
		
		//NEVER require salutation
		strAddressXML +=	buildCustomXML(gEBI("patron_salutation1"),"Salutation");
		
		var fieldArray = new Array
			(
				{name : "patron_firstname1", title : "FirstName"}, 
				{name : "patron_lastname1", title : "Name"}, 
				{name : "patron_salutation2", title : "PartnerSalutation"}, 
				{name : "patron_firstname2", title : "PartnerFirstName"}, 
				{name : "patron_lastname2", title : "PartnerLastName"}, 
				
				{name : "patron_company", title : "Company"}, 
				{name : "patron_address", title : "Street"}, 
				{name : "patron_address2", title : "Street2"}, 
				{name : "patron_city", title : "City"}, 
				{name : "patron_state", title : "State"}, 
				{name : "patron_zip", title : "ZIP"}, 
				{name : "patron_country", title : "Country"}, 
				{name : "patron_region", title : "Region"}, 
				
				{name : "patron_custom1", title : "Custom1"}, 
				{name : "patron_custom2", title : "Custom2"}, 
				{name : "patron_custom3", title : "Custom3"}, 
				{name : "patron_custom4", title : "Custom4"}, 
				{name : "patron_custom5", title : "Custom5"}, 
				{name : "patron_custom6", title : "Custom6"}, 
				{name : "patron_custom7", title : "Custom7"}, 
				
				{name : "patron_phone", title : "Phone"}, 
				{name : "patron_email", title : "EMail"}
			);

		for(var xxx=0;xxx<fieldArray.length;xxx++)
		{
			var obj = fieldArray[xxx];
			
			var strXMLPart = buildCustomXML(gEBI(obj.name), obj.title);
			if("0" == strXMLPart)
				return false;
			
			strAddressXML += strXMLPart;
		}

		strAddressXML +=		"<AddressType><ID>2</ID></AddressType>";

		//variables defined higher
		if(strPhoneType != "" && typeof(strPhoneType) != "undefined")
			strAddressXML +=		"<PhoneType>" + strPhoneType + "</PhoneType>";
		if(strEmailType != "" && typeof(strEmailType) != "undefined")
			strAddressXML +=		"<EmailType>" + strEmailType + "</EmailType>";
		strAddressXML += "</Address>";
		
		
		strPatronXML += strAddressXML;
		strPatronXML += "<AddressType><ID>2</ID></AddressType>";//fix
		//strPatronXML += "</PatronAddress>";
		//SHIPPING ADDRESS
		var strShippXML = "";
		if(null == gEBI("chSippAddress") || !gEBI("chSippAddress").checked)
		{
			strShippXML += "<PatronAddress>" + strAddressXML;
			strShippXML += "<AddressType><ID>1</ID></AddressType>";
			strShippXML += "</PatronAddress>";
		}
		else
		{
			if(false == SetShippAddress()) 
				return false;
				
			var lSelShippDetails = gEBI("selShippDetails");
			if(null != lSelShippDetails)
			{
				for(var i=0;i<lSelShippDetails.options.length; i++)
					if(null != lSelShippDetails.options[i].getAttribute('ShippXML'))
						strShippXML += String(lSelShippDetails.options[i].getAttribute('ShippXML'));
			}
		}

	strPatronXML += "<PatronAddresss>"+ strShippXML +"</PatronAddresss>"; 
	strPatronXML += "</Patron>";
	//gCurrentOrdersXML = strOrderXML;
	gCurrentOrderXML = strOrderXML;
	gCurrentPatronXML = strPatronXML;

	if((null!=gEBI('h_SubCounts'))||(Number(gEBI('h_SubCounts').value)>0)){
		var intRows = Number(gEBI('h_SubCounts').value);
	
	var strSubscriptionsXML = "<Subscriptions>";		
	var subRow = 0;
		for(var s=0;s<intRows;s++){		 
			while(null == gEBI('SubscriptionTicketType_' + subRow))
				subRow++;
			var oSelTT = gEBI('SubscriptionTicketType_' + subRow);
			
			var oCurrentTTOption = oSelTT.options[oSelTT.selectedIndex];
			
			//replace comma to dot as decimal separator
			var strAmount = parseFloat2(oCurrentTTOption.getAttribute('Amount'));
			strAmount = String(strAmount.toFixed(2));
			strAmount = strAmount.replace(",", ".");
			var subsCount=1;
			if(gEBI("txtSTixQty"+subRow)!=null)
			{
				subsCount= gEBI("txtSTixQty"+subRow).value ;
			}	
			for(var sc=0;sc<subsCount;sc++){	
			var  strSubscriptionXML = "<Subscription><ID>" + gEBI('hSubscriptionID_' + subRow).value + "</ID>";
			strSubscriptionXML += "<SeasonPackage><ID>" + gEBI('hSeasonPackage_' + subRow).value + "</ID><HasPriceDistributions>" + gEBI('hSeasonPackageDistro_' + subRow).value + "</HasPriceDistributions><DecrementSingleReturn>" + gEBI('hSeasonPackageDecrement_' + subRow).value + "</DecrementSingleReturn></SeasonPackage>";
			strSubscriptionXML += "<SeasonTicketPrice><ID>" + oSelTT.value + "</ID>";
			strSubscriptionXML += "<TicketType><ID>" + oCurrentTTOption.getAttribute('TicketType') + "</ID></TicketType>";
			strSubscriptionXML += "<Amount>" + strAmount + "</Amount>";
			strSubscriptionXML += "</SeasonTicketPrice>";
				
			strSubscriptionXML += "<SeasonTickets>";
			
			var seasonTicketPrice = 0;
			var oSeasonTicketPrice = getChildByIdOrName(gEBI('txtSubscriptionPrice_' + subRow).parentNode.parentNode, 'hSeasonTicketPrice_' + subRow, true);
			if(null != oSeasonTicketPrice)
				seasonTicketPrice = Number(oSeasonTicketPrice.value);
			
			var oParentTable = gEBI('tableSeasonTickets_'+subRow);
			for(var t=0;t<Number(gEBI('hCount_' + subRow).value);t++){
				var oSTFee = gEBI("hEventName_"+subRow+"_"+t);
				var lSeasonTicketGroup = arrSubscriptions[subRow].SeasonTickets[t];
				if(lSeasonTicketGroup!=null)
				{
					for(var xx=0;xx<lSeasonTicketGroup.nTixQty;xx++)
					{
						var lFeesXML = "";
							lFeesXML +=	"<Fees>";
							for(var i=0; i< lSeasonTicketGroup.Items[xx].Fees.length; i++)
							{
								var lFee = lSeasonTicketGroup.Items[xx].Fees[i];
								lFeesXML +=		"<Fee><ID>" + lFee.ID + "</ID><Amount>" + lFee.Amount + "</Amount></Fee>";
							}
							lFeesXML +=	"</Fees>";
						strSubscriptionXML += "<SeasonTicket><ID>" + gEBI('hSeasonTicket_' + subRow + '_' + t).value + "</ID>";
						strSubscriptionXML += "<Ticket GA='" + isGA(gEBI("h_SeasonTicketGA_" + subRow + '_' + t)) + "'><ID>" + gEBI('hTicket_' + subRow + '_' + t).value + "</ID><Seat><ID>" + gEBI('hSeatID_' + subRow + '_' + t).value + "</ID><Name>" + gEBI('hSeatName_' + subRow + '_' + t).value + "</Name></Seat><Event><ID>" + gEBI('hEventID_' + subRow + '_' + t).value + "</ID><Name>" + encoder(gEBI('hEventName_' + subRow + '_' + t).value) + "</Name></Event><TicketType><ID>" + gEBI('SubscriptionTicketType_' + subRow).options[gEBI('SubscriptionTicketType_' + subRow).selectedIndex].getAttribute('TicketType') + "</ID></TicketType>";
						strSubscriptionXML +=	"<Performance>";
						strSubscriptionXML +=		"<DateTime>" + gEBI('hDateTime_' + subRow + '_' + t).value + "</DateTime>";
						strSubscriptionXML +=		"<ID>" + getChildByIdOrName(oParentTable, "h_EventName_"+subRow+'_'+t, true).getAttribute("prfid") + "</ID>";
						strSubscriptionXML +=	"</Performance>";
						strSubscriptionXML +=   lFeesXML;
						strSubscriptionXML += "</Ticket></SeasonTicket>";
					}
				}
			}
			strSubscriptionXML += "</SeasonTickets>";
			if(gSeasonRunId != null)
				strSubscriptionXML += "<SeasonRun><ID>" + gSeasonRunId + "</ID></SeasonRun>";
			if(parseFloat2(gEBI('txtSubscriptionFee_' + subRow).value)>0 || (arrSubscriptions[subRow]!=null && arrSubscriptions[subRow].nCumulativeHiddenFeeAmount>0)){
				var oSTP = gEBI('trSubscription_'+subRow);
				var oSTicketTypeSelect = getChildByIdOrName(oSTP, "SubscriptionTicketType_"+subRow, true);
				var ticketPrice = parseFloat2(oSTicketTypeSelect.options[oSTicketTypeSelect.selectedIndex].getAttribute('Amount'));//parseFloat2(gEBI('txtTicketPrice_' + t).value);
				var oSTkFee = getChildByIdOrName(oSTP, "txtSubscriptionFee_"+subRow, true);
				
				if(ticketPrice == null)
					ticketPrice = 0;
					
					
					var lSubscriptionGroup = arrSubscriptions[subRow];

				for(var xx=0;xx<lSubscriptionGroup.nTixQty;xx++)
				{
				
					var lFeesXML = "";
						lFeesXML +=	"<Fees>";
						for(var i=0; i< lSubscriptionGroup.Items[xx].Fees.length; i++)
						{
							var lFee = lSubscriptionGroup.Items[xx].Fees[i];
							lFeesXML +=		"<Fee><ID>" + lFee.ID + "</ID><Amount>" + lFee.Amount + "</Amount></Fee>";
						}
						lFeesXML +=	"</Fees>";
					strSubscriptionXML += lFeesXML;
				}
			}
			strSubscriptionsXML += strSubscriptionXML + "</Subscription>";
			}
			subRow++;
			
		}
	}

	strSubscriptionsXML += "</Subscriptions>";
	gOrder["SubscriptionsXML"] = strSubscriptionsXML;

	var strCouponOrderXML = "<CouponOrders>";
	if(gEBN('hCouponOrder')&&(gEBN('hCouponOrder').length>0)){
		for(var i=0;i<gEBN('hCouponOrder').length;i++){
			var sListPrice = gEBN('hCouponOrder')[i].getAttribute('ListPrice');
			var sCouponVal = gEBN('hCouponOrder')[i].getAttribute('CouponValue');
			
			sListPrice = sListPrice.replace(",", ".");
			sCouponVal = sCouponVal.replace(",", ".");

			if(gEBN('hCouponOrder')[i].getAttribute('isGroupable').toLowerCase() == "true")
				strCouponOrderXML += '<CouponOrder><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponOrderId') + '</ID><Coupon><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponId') + '</ID><IsShortCode>' + gEBN('hCouponOrder')[i].getAttribute('IsShortCode') + '</IsShortCode><CouponName>' + gEBN('hCouponOrder')[i].getAttribute('CouponName') + '</CouponName><ListPrice>' + sListPrice + '</ListPrice><CouponValue>' + sCouponVal + '</CouponValue><CouponType><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponTypeId') + '</ID></CouponType></Coupon><Quantity>' + gEBN('hCouponOrder')[i].getAttribute('Quantity') + '</Quantity><RedeemedQuantity>' + gEBN('hCouponOrder')[i].getAttribute('RedeemedQuantity') + '</RedeemedQuantity></CouponOrder>';
			else
				{
					for(var qtyIter = parseInt(gEBN('hCouponOrder')[i].getAttribute('Quantity')); qtyIter > 0; qtyIter--)
					{
						strCouponOrderXML += '<CouponOrder><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponOrderId') + '</ID><Coupon><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponId') + '</ID><IsShortCode>' + gEBN('hCouponOrder')[i].getAttribute('IsShortCode') + '</IsShortCode><CouponName>' + gEBN('hCouponOrder')[i].getAttribute('CouponName') + '</CouponName><ListPrice>' + sListPrice + '</ListPrice><CouponValue>' + sCouponVal + '</CouponValue><CouponType><ID>' + gEBN('hCouponOrder')[i].getAttribute('CouponTypeId') + '</ID></CouponType></Coupon><Quantity>1</Quantity><RedeemedQuantity>' + gEBN('hCouponOrder')[i].getAttribute('RedeemedQuantity') + '</RedeemedQuantity></CouponOrder>';
					}
				}
		}
	}
	strCouponOrderXML += "</CouponOrders>";

	var strCouponPackageOrderXML = "<CouponPackageOrders>";
	if(gEBN('hCouponPackageOrder')&&(gEBN('hCouponPackageOrder').length>0)){
		for(var i=0;i<gEBN('hCouponPackageOrder').length;i++){
			strCouponPackageOrderXML += '<CouponPackageOrder><ID>' + gEBN('hCouponPackageOrder')[i].getAttribute('CouponPackageOrderId') + '</ID><CouponPackage><ID>' + gEBN('hCouponPackageOrder')[i].getAttribute('CouponPackageId') + '</ID><CouponPackageName>' + gEBN('hCouponPackageOrder')[i].getAttribute('CouponPackageName') + '</CouponPackageName><PackagePrice>' + gEBN('hCouponPackageOrder')[i].getAttribute('ListPrice') + '</PackagePrice></CouponPackage><Quantity>' + gEBN('hCouponPackageOrder')[i].getAttribute('Quantity') + '</Quantity></CouponPackageOrder>';
		}
	}
	strCouponPackageOrderXML += "</CouponPackageOrders>";
	var strItemOrderXML = "<ItemOrders>";
	if(gEBN('hItemOrder')&&(gEBN('hItemOrder').length>0)){
		for(var i=0;i<gEBN('hItemOrder').length;i++){
			
			var oIO = gEBN('hItemOrder')[i];

			strItemOrderXML += '<ItemOrder><ID>' + oIO.getAttribute('ItemOrderId') + '</ID><Item><ID>' + gEBN('hItemOrder')[i].getAttribute('ItemId') + '</ID><Name>' + gEBN('hItemOrder')[i].getAttribute('ItemName') + '</Name><ListPrice>' + gEBN('hItemOrder')[i].getAttribute('ListPrice') + '</ListPrice><Points>' + gEBN('hItemOrder')[i].getAttribute('Points') + '</Points><IsMembership>' + gEBN('hItemOrder')[i].getAttribute('IsMembership') + '</IsMembership>'
			if (oIO.getAttribute('OriginalPrice') != null && oIO.getAttribute('OriginalPrice') != "") {
			    strItemOrderXML += ' <PurchasePrice>' + oIO.getAttribute('OriginalPrice') + '</PurchasePrice>';
			}
			else {
			    strItemOrderXML += ' <PurchasePrice>' + oIO.getAttribute('ListPrice') + '</PurchasePrice>';
			}
			strItemOrderXML += '</Item><Quantity>' + gEBN('hItemOrder')[i].getAttribute('Quantity') + '</Quantity>';
			if(oIO.getAttribute('discountID')!=null)
			  {
				strItemOrderXML+= ' <Discount><ID>'+oIO.getAttribute('discountID')+'</ID>';
				if (gEBN('hItemOrder')[i].getAttribute('DiscountAmount')!=null)
				    strItemOrderXML+= ' <Amount>'+oIO.getAttribute('DiscountAmount')+'</Amount>';
				if (gEBN('hItemOrder')[i].getAttribute('Limit')!=null)
				    strItemOrderXML+= ' <Limit>'+oIO.getAttribute('Limit')+'</Limit>'
				 strItemOrderXML+= '</Discount>';
		      }
			if (oIO.getAttribute('Pledge')!=null && oIO.getAttribute('Pledge') != "")
			{
				strItemOrderXML+=' <PledgeAmount>'+oIO.getAttribute('Pledge')+'</PledgeAmount>';
			}
			if (oIO.getAttribute('DonationLevelID')!=null && oIO.getAttribute('DonationLevelID') != "")
			{
				strItemOrderXML+=' <DonationLevel><ID>'+oIO.getAttribute('DonationLevelID')+'</ID></DonationLevel>';
			}
            if (oIO.getAttribute('OriginalQty') != null && oIO.getAttribute('OriginalQty') != "") {
                strItemOrderXML += ' <QuantityF>' + oIO.getAttribute('OriginalQty') + '</QuantityF>';
            }
		    
		    if (null!=oIO.getAttribute('AddedToTPSTransaction') )
		       if (oIO.getAttribute('AddedToTPSTransaction')=='false')
				     strItemOrderXML+= ' <PaidWith>money</PaidWith>' ;
				else
			         strItemOrderXML+= ' <PaidWith>TPS</PaidWith>' ; 
			
			var lItemGroup = arrItems[i];
			var lnCumulativeFeeAmount = 0
			
			if(lItemGroup != null)
				lnCumulativeFeeAmount = lItemGroup.nCumulativeFeeAmount
			else
				lnCumulativeFeeAmount = 0;

			strItemOrderXML +=	"<FeeAmount>" + lnCumulativeFeeAmount + "</FeeAmount>";
			
			
			var lFeesXML = "";
			lFeesXML +=	"<Fees>";
		
			if(lItemGroup != null)
			for(var xx=0; xx< lItemGroup.Items[0].Fees.length; xx++)
			{
				var lFee = lItemGroup.Items[0].Fees[xx];
				lFeesXML +=		"<Fee><ID>" + lFee.ID + "</ID><Amount>" + lFee.Amount + "</Amount></Fee>";
			}
			lFeesXML +=	"</Fees>";
						
			strItemOrderXML += lFeesXML;
			
			strItemOrderXML+='</ItemOrder>';
		}
	}
	strItemOrderXML += "</ItemOrders>";
	//strOrderXML += gOrder["SubscriptionsXML"] + gOrder["TicketsXML"] + "</Order>";
		
	gOrder["CouponOrdersXML"] = strCouponOrderXML;
	gOrder["CouponPackageOrdersXML"] = strCouponPackageOrderXML;
	gOrder["ItemOrdersXML"] = strItemOrderXML;
	var strContainPrintAtHomeXml = "<ContainPrintAtHome>"+ContainPrintAtHome+"</ContainPrintAtHome>";
	strOrderXML = strOrderXML.replace('</Order>',strPatronXML+strCouponOrderXML+strCouponPackageOrderXML+strItemOrderXML+strTicketsXML+strSubscriptionsXML+strContainPrintAtHomeXml+'</Order>');
	
	}
	catch(e)
	{
		var errMess = "Error during generating XML for CommitOrderWeb\n\r";
		errMess+= "Error Name: "+e.name + "\n\r";
		errMess+= "Error Message: "+e.message + "\n\r";
		SendErrorToServer(errMess,"Shopping Cart");
		return false;
	}
	
	return strOrderXML;
}

//------------------------------------------------------------------------------------------------

function ClearExtraFees()
{
	var lOrderFees = gEBI("txtExtraOrderFees");
	if(null == lOrderFees) return;
	lOrderFees.setAttribute("ExtraFeeIDs", "");
	lOrderFees.setAttribute("ExtraFeeAmount", 0.00);
}
//------------------------------------------------------------------------------------------------

function isGA(oInput)
{
	if(oInput!=null) return String(oInput.value);
	return "false"; 
}

//---------------------------------:PackageSales---------------------------------------------------
function DeleteSubscription(oImg,SubscriptionId)
{ 
	 var oTable=oImg.parentNode.parentNode.parentNode;
	 oTable.removeChild(oImg.parentNode.parentNode);
	 if(gEBI('h_SubCounts'))
		gEBI('h_SubCounts').value = Number(gEBI('h_SubCounts').value) - 1;
	 updateTotals(oTable);
	 DeleteSubscriptionFromSession(SubscriptionId);
}

function DeleteSubscriptionFromSession(SubscriptionId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveSubscription\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Subscription\">"+
		"<Subscription>"+
			"<ID>" + SubscriptionId + "</ID>"+
		"</Subscription></param>"+
		"</command></body></envelope>";	

	$.post(gSOAPListenerURL, strRequestXML);

	//if(gEBI('h_SubCounts') != null) 
	//	gEBI('h_SubCounts').value = Number(gEBI('h_SubCounts').value) - 1;
}

function DeleteSeasonTicket(oImg,SubscriptionId,SeasonTicketId,DecrementSingleReturn)
{ 
	 var oTable=oImg.parentNode.parentNode.parentNode;
	 var oTr = oTable.parentNode.parentNode.parentNode;
	 if(DecrementSingleReturn) 
	 {
		 var oSubscriptionPriceInputArray = getChildrenByPartialIdOrName(oTr.cells[2], "SubscriptionTicketType_");		 
		 var SingleAmount=DeleteSeasonTicketFromSessionSync(SubscriptionId,SeasonTicketId);
		 for(var i=0;i<oSubscriptionPriceInputArray[0].options.length;i++)
		 {
			oSubscriptionPriceInputArray[0].options[i].setAttribute('Amount',oSubscriptionPriceInputArray[0].options[i].getAttribute('Amount')-SingleAmount);
		 }
	 }
	 else
	 {
	 	 DeleteSeasonTicketFromSession(SubscriptionId,SeasonTicketId);
	 }
	 oTable.removeChild(oImg.parentNode.parentNode);
	 updateTotals(getParentByPartialIdOrName(oTable, "trSubscription_", true).parentNode);
}

function DeleteSeasonTicketFromSession(SubscriptionId,SeasonTicketId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveSeasonTicket\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Subscription\">"+
		"<Subscription>"+
			"<ID>" + SubscriptionId + "</ID>"+
		"</Subscription></param>"+
		"<param type=\"SeasonTicket\">"+
		"<SeasonTicket>"+
			"<ID>" + SeasonTicketId + "</ID>"+
		"</SeasonTicket></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteSeasonTicketFromSessionSync(SubscriptionId,SeasonTicketId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveSeasonTicket\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Subscription\">"+
		"<Subscription>"+
			"<ID>" + SubscriptionId + "</ID>"+
		"</Subscription></param>"+
		"<param type=\"SeasonTicket\">"+
		"<SeasonTicket>"+
			"<ID>" + SeasonTicketId + "</ID>"+
		"</SeasonTicket></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}

function AddGASeasonsToSession(pTextBox)
{
	if(parseFloat2(pTextBox.value)>parseFloat2(pTextBox.getAttribute("GaLimit")))
	{
		pTextBox.value=pTextBox.getAttribute("GaLimit");
	}
	var strRequestXML = "<envelope><body><command name=\"TryAddGASeasons\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Subscription\">"+//pTicket
		"<Subscription>"+
			"<ID>" + pTextBox.getAttribute("SubscriptionId") + "</ID>"+
			"<Quantity>"+pTextBox.value+ "</Quantity>"+
		"</Subscription></param>"+
		"</command></body></envelope>";
	
	$.post(gSOAPListenerURL, strRequestXML);
}
//---------------------------------------------------------------------------

//---------------------------------:ItemSAles---------------------------------
function itemUpdate(itemID,obj)
{
	aryPayTypes = new Array(); //reset payment details
	if (obj.value==0)
	{
		DeleteItemOrder(obj,itemID);
	}
	else
	{
		UpdateItemOrdersFromSession(itemID,obj.value);
		updateTotals();
	}
}

function UpdateItemOrdersFromSession(ItemId,ItemCount)
{
	var strRequestXML = "<envelope><body><command name=\"TryUpdateItemOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Item\">"+
		"<Item>"+
			"<ID>" + ItemId + "</ID>"+
		"</Item></param>"+
		"<param type=\"System.Int32\"><int>"+ItemCount+"</int></param>"+
		"</command></body></envelope>";	
	
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteItemOrder(oImg,ItemId)
{  
	 var oTable=oImg.parentNode.parentNode.parentNode;
	 oTable.removeChild(oImg.parentNode.parentNode);
	 updateTotals(); //run full update totals, problem with donations
	 DeleteItemOrdersFromSession(ItemId);
}

function DeleteItemOrdersFromSession(ItemId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveItemOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Item\">"+
		"<Item>"+
			"<ID>" + ItemId + "</ID>"+
		"</Item></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}
//------------------------------------------------------------------------

//---------------------------------:CouponSales---------------------------------
function CouponUpdate(CouponID,obj)
{
	aryPayTypes = new Array(); //reset payment details
	if (obj.value==0)
	{
		DeleteCouponOrder(obj,CouponID);
	}
	else
	{
		UpdateCouponOrdersFromSession(CouponID,obj.value);
		updateTotals();
	}
}

function UpdateCouponOrdersFromSession(CouponId,CouponCount)
{
	var strRequestXML = "<envelope><body><command name=\"TryUpdateCouponOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Coupon\">"+
		"<Coupon>"+
			"<ID>" + CouponId + "</ID>"+
		"</Coupon></param>"+
		"<param type=\"System.Int32\"><int>"+CouponCount+"</int></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteCouponOrder(oImg,CouponId)
{  
	 var oTable=oImg.parentNode.parentNode.parentNode;
	 oTable.removeChild(oImg.parentNode.parentNode);
	 updateTotals(oTable);
	 DeleteCouponOrdersFromSession(CouponId);
}

function DeleteCouponOrdersFromSession(CouponId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveCouponOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Coupon\">"+
		"<Coupon>"+
			"<ID>" + CouponId + "</ID>"+
		"</Coupon></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}
//------------------------------------------------------------------------

//---------------------------------:CouponPackageSales---------------------------------
function CouponPackageUpdate(CouponPackageID,obj)
{
	aryPayTypes = new Array(); //reset payment details
	if (obj.value==0)
	{
		DeleteCouponPackageOrder(obj,CouponPackageID);
	}
	else
	{
		UpdateCouponPackageOrdersFromSession(CouponPackageID,obj.value);
		updateTotals();
	}
}

function UpdateCouponPackageOrdersFromSession(CouponPackageId,CouponPackageCount)
{
	var strRequestXML = "<envelope><body><command name=\"TryUpdateCouponPackageOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"CouponPackage\">"+
		"<CouponPackage>"+
			"<ID>" + CouponPackageId + "</ID>"+
		"</CouponPackage></param>"+
		"<param type=\"System.Int32\"><int>"+CouponPackageCount+"</int></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteCouponPackageOrder(oImg,CouponPackageId)
{  
	 var oTable=oImg.parentNode.parentNode.parentNode;
	 oTable.removeChild(oImg.parentNode.parentNode);
	 updateTotals(oTable);
	 DeleteCouponPackageOrdersFromSession(CouponPackageId);
}

function DeleteCouponPackageOrdersFromSession(CouponPackageId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveCouponPackageOrder\"><class name=\"CartProcessor\"/>"+
		"<param type=\"CouponPackage\">"+
		"<CouponPackage>"+
			"<ID>" + CouponPackageId + "</ID>"+
		"</CouponPackage></param>"+
		"</command></body></envelope>";	
		
	$.post(gSOAPListenerURL, strRequestXML);
}
//------------------------------------------------------------------------

//---------------------------------:SingleSales---------------------------------
function AddGATicketsToSession(pTextBox)
{
	var strRequestXML = "<envelope><body><command name=\"TryAddGATickets\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Ticket\">"+//pTicket
		"<Ticket QuantityF='"+pTextBox.getAttribute("QuantityF")+"'>"+
			"<ID>" + pTextBox.getAttribute("TicketId") + "</ID>"+
			"<Performance><ID>" + pTextBox.getAttribute("PerformanceID") + "</ID></Performance>"+
			"<TicketType><ID>"+pTextBox.getAttribute("TicketTypeID")+"</ID></TicketType>"+
			"<POLevel><ID>"+pTextBox.getAttribute("POLevelID")+"</ID></POLevel>"+
		"</Ticket></param>"+
		"<param type=\"System.Int32\"><int>"+pTextBox.value+"</int></param>"+//pCountTix
		"</command></body></envelope>";
	pTextBox.setAttribute("QuantityF",pTextBox.value);
	
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteGATicketsToSession(pTextBox)
{
	var strRequestXML = "<envelope><body><command name=\"TryAddGATickets\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Ticket\">"+//pTicket
		"<Ticket QuantityF='"+pTextBox.getAttribute("QuantityF")+"'>"+
			"<ID>" + pTextBox.getAttribute("TicketId") + "</ID>"+
			"<Performance><ID>" + pTextBox.getAttribute("PerformanceID") + "</ID></Performance>"+
			"<TicketType><ID>"+pTextBox.getAttribute("TicketTypeID")+"</ID></TicketType>"+
			"<POLevel><ID>"+pTextBox.getAttribute("POLevelID")+"</ID></POLevel>"+
		"</Ticket></param>"+
		"<param type=\"System.Int32\"><int>"+0+"</int></param>"+//pCountTix
		"</command></body></envelope>";
	
	$.post(gSOAPListenerURL, strRequestXML);
}

function DeleteTicketsFromSession(TicketId)
{
	var strRequestXML = "<envelope><body><command name=\"TryRemoveTicket\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Ticket\">"+//pTicket
		"<Ticket>"+
			"<ID>" + TicketId + "</ID>"+
		"</Ticket></param>"+
		//"<param type=\"System.Int32\"><int>"+TicketId+"</int></param>"+//Ticket ID
		"</command></body></envelope>";
		
	$.post(gSOAPListenerURL, strRequestXML);
}

function ChangeTicketTypeInSession(TicketId,pSelect)
{
	var strRequestXML = "<envelope><body><command name=\"TryChangeTicketType\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Ticket\">"+//pTicket
		"<Ticket>"+
			"<ID>" + TicketId + "</ID>"+
			"<GA>" + pSelect.getAttribute('IsGA') + "</GA>"+
			"<TicketType><ID>" + pSelect.options[pSelect.selectedIndex].getAttribute('TicketType') + "</ID></TicketType>"+	
			"<POLevel><ID>" + pSelect.getAttribute('PolID') + "</ID>"+		
			"<TicketPrices><TicketPrice><TicketType><ID>" + pSelect.getAttribute('prevtt') + "</ID></TicketType></TicketPrice></TicketPrices></POLevel>"+		
		"</Ticket></param>"+
		"</command></body></envelope>";
	
	$.post(gSOAPListenerURL, strRequestXML);
	
	pSelect.setAttribute('prevtt',pSelect.options[pSelect.selectedIndex].getAttribute('TicketType'));
}

function ChangeExtraInSession(TicketId,IsGA,TicketType,PolID,pSelect)
{
	var tagname=(pSelect.options[pSelect.selectedIndex].getAttribute('extraType')=='discount'?'ExtraDiscountId':'FeeId');
	var commandname=(pSelect.options[pSelect.selectedIndex].getAttribute('extraType')=='discount'?'Discount':'Fee');	
	var strRequestXML = "<envelope><body><command name=\"TryChangeTicketExtra"+commandname+"\"><class name=\"CartProcessor\"/>"+
		"<param type=\"Ticket\">"+
		"<Ticket>"+
			"<ID>" + TicketId + "</ID>"+
			"<GA>" + IsGA + "</GA>"+
			"<TicketType><ID>" + TicketType + "</ID></TicketType>"+	
			"<POLevel><ID>" + PolID + "</ID></POLevel>"+	
			"<"+tagname+">" + pSelect.value + "</"+tagname+">"+					
		"</Ticket></param>"+
		"</command></body></envelope>";
	
	$.post(gSOAPListenerURL, strRequestXML);
}

function Delete(strObject,rownum)
{
	var ItemID=0;
	if("undefined" != typeof(arguments[2]))
	 {   ItemID=arguments[2];
     for (i=0;i<arrItems.length;i++)
         {
            if (typeof(arrItems[i])!="undefined")
             {  
               if (arrItems[i]!=null)
               if (arrItems[i]["ID"]==ItemID)
                 { // arrItems.splice(i,1);
                  arrItems[i]=null;
                 }
              }
         }
     }
     
    if("undefined" != typeof(arguments[4]))
	{
		if($("#h_TicketGA"+rownum).val().toLowerCase() == 'false') 
			DeleteTicketsFromSession(arguments[4]);
		else 
			DeleteGATicketsToSession(gEBI("txtTixQty"+rownum))
	}
     
    if("undefined" != typeof(arguments[3]))
	{   
		oImg=arguments[3];
		var oTable=oImg.parentNode.parentNode.parentNode;
		oTable.removeChild(oImg.parentNode.parentNode);
		if(strObject=='Ticket'){
			$("input[id*=txtTicketDiscount_]").each(function(index) {
				$(this).attr("cntTicketsPerEvent",Number($(this).attr("cntTicketsPerEvent"))-1);
				$(this).attr("cntTicketsPerPerformance",Number($(this).attr("cntTicketsPerPerformance"))-1);
			  });
		}
		updateTotals(oTable);
	}
}

function ChangePriceAmmountInSession(AmmountObject,Ammount)
{
	var strRequestXML = "<envelope><body><command name=\"TryChange"+AmmountObject+"Ammount\"><class name=\"CartProcessor\"/>"+
		"<param type=\"System.Decimal\"><decimal>"+Ammount+"</decimal></param>"+
		"</command></body></envelope>";
		
	$.post(gSOAPListenerURL, strRequestXML);
}
//------------------------------------------------------------------------------
 
 //----------------------:XMLHTTP Utility functions -----------------------------------------------
var gFunctionXmlHttpRequestAnisochronousComplite = null;
var gSOAPListenerURL = "UserControls/ObjectFactory.aspx";

function sendXmlHttpRequest(strURL, strRequest)
{
	var xmlHttp = null;
	xmlHttp = new XMLHttpRequest(); //XMLHttpRequest.js

	if(null == xmlHttp)
	{
		alert("Failed to create XmlHttp object!");
		return "";
	}

	//if no request body is specified, then we change method from POST to GET 
	var strMethod = "POST";
	
	if("" == strRequest || null == strRequest || 'object' == typeof(strRequest) || 'undefined' == typeof(strRequest))
	{
		strMethod = "GET";
		strRequest = null;
	}
	else
		if(!isSafari)
		{	
			var xmlDoc = jsXML.createDOMDocument("", "root");
			//strRequest=strRequest.replace(/&/," &amp; ");
			xmlDoc.loadXML(strRequest);
			if(0 != xmlDoc.parseError.errorCode && 0 != xmlDoc.parseError)
			{
				msgDetails		=	stackOfCaller(sendXmlHttpRequest,0);
				window.location	=	"MessageCenter.aspx?msgSrc="+window.location+"&msgCode="+500+"&msgDetails=Bad XML format detected in " + msgDetails;
				return "Error : Bad XML Format";
			}
		}
	
	xmlHttp.open(strMethod, strURL, false);
	xmlHttp.send(strRequest);
	
	//alert("readyState=" + xmlHttp.readyState + "strURL=" + strURL + "\nxmlHttp.status=" + xmlHttp.status + " xmlHttp.responseText=" + xmlHttp.responseText);
	
	if(207 == xmlHttp.status) //response from additional charge of page
	{
		window.location="Login.aspx";
		return "";
	}
	if(500 == xmlHttp.status)
	{
	
		var msgSrc = xmlHttp.statusText;			//page where error originated
		var msgCode = xmlHttp.status;				//error code
		var msgDetails = xmlHttp.responseText+".";
		msgDetails += " Call detected in "+stackOfCaller(sendXmlHttpRequest,0);
		window.location="MessageCenter.aspx?msgSrc="+msgSrc+"&msgCode="+msgCode+"&msgDetails="+msgDetails;
		return "Error 500";
	}
	if(400 == xmlHttp.status)
	{
		alert(xmlHttp.statusText);
		return "";
	}
	if(200 == xmlHttp.status)
		return xmlHttp.responseText;
		
	return "";
}
function sendXmlHttpRequestAnisochronous(strURL, strRequest)
{

	var xmlHttp = null;
	xmlHttp = new XMLHttpRequest(); //XMLHttpRequest.js

	if(null == xmlHttp)
	{
		alert("Failed to create XmlHttp object!");
		return "";
	}

	//if no request body is specified, then we change method from POST to GET 
	var strMethod = "POST";
	
	if("" == strRequest || null == strRequest || 'object' == typeof(strRequest) || 'undefined' == typeof(strRequest))
	{
		strMethod = "GET";
		strRequest = null;
	}
	else
		if(!isSafari)
		{
			var xmlDoc = jsXML.createDOMDocument("", "root");
			xmlDoc.loadXML(strRequest);
			if(0 != xmlDoc.parseError.errorCode && 0 != xmlDoc.parseError)
			{
				msgDetails		=	stackOfCaller(sendXmlHttpRequest,0);
				window.location	=	"MessageCenter.aspx?msgSrc="+window.location+"&msgCode="+500+"&msgDetails=Bad XML format detected in " + msgDetails;
				return "Error : Bad XML Format";
			}
		}
	
	
	// Set up the post
	xmlHttp.onreadystatechange = function(){

	    // a readyState of 4 means we're ready to use the data returned by XMLHTTP
	    if (xmlHttp.readyState == 4)
	    {

			if(207 == xmlHttp.status) //response from additional charge of page
			{
				window.location="Login.aspx";
				return "";
			}
			if(500 == xmlHttp.status)
			{
			
				var msgSrc = xmlHttp.statusText;			//page where error originated
				var msgCode = xmlHttp.status;				//error code
				var msgDetails = xmlHttp.responseText;
				
				window.location="MessageCenter.aspx?msgSrc="+msgSrc+"&msgCode="+msgCode+"&msgDetails="+msgDetails;
				return "Error 500";
			}
			if(400 == xmlHttp.status)
			{
				alert(xmlHttp.statusText);
				return "";
			}
			if(200 == xmlHttp.status)
			{
				var strResponse = xmlHttp.responseText;
				if(null != gFunctionXmlHttpRequestAnisochronousComplite)
					gFunctionXmlHttpRequestAnisochronousComplite(strResponse);
			}
	    }
	}
	xmlHttp.open(strMethod, strURL, true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(strRequest);
}

function embedHTTPPage(strURL, strSoapMessage, strTargetObjectID, successFunc)
{
	var oTargetObj = $("#" + strTargetObjectID);
	if(oTargetObj.length != 1)
	{
		//failed to get the target DIV
		//alert("Error getting target object");
		return;
	}
	
	//requesting a page
	$.ajax({
			type: "POST",
			url: strURL,
			data: strSoapMessage,
			async: false, 
			contentType: "text/xml; charset=utf-8",
			dataType: "text",
			success: function(data, textStatus){
				oTargetObj.html(data);
				
				if(typeof(successFunc) == "function")
					successFunc();
				
				return false;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("error = " + XMLHttpRequest.responseText);
				return false;
			}
		});
}
//---------------------------------------------------------------------------

//----------------------:Utils-----------------------------------------------

/*handles reorder of options in select box on keyboard arrow being pressed*/
function onSelectBoxKeyDown(oSelect, e)
{
	if(!e) e = window.event; 
	if(e.keyCode==38) //up arrow
	{
		 $('#' + oSelect.id + ' option:selected').each(function(){
		   $(this).insertBefore($(this).prev());
		});
	}
	else if(e.keyCode==40) //down arrow
	{
		$('#' + oSelect.id + ' option:selected').each(function(){
			$(this).insertAfter($(this).next());
		 });
	}
	return true; 
}

function NavOut(strURL)
{
	window.location = strURL; 
	if(event)
		event.returnValue = false;
	return false;
}
  
function SetCookie(name, value) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
 document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}

function DeleteCookie(name) {
  var argv = DeleteCookie.arguments;
  var argc = DeleteCookie.arguments.length;
  var exp = new Date();
  exp.setTime (exp.getTime() - 1);  // This cookie is history
  var cval = GetCookie (name,'/');
  var path = (argc > 1) ? argv[1] : null;
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString()+ ((path == null) ? "" : ("; path=" + path));
} 

function GetCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
} 

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));

}

function ChangeSelectByValue(oSelect, sValue)
{
	var bDisplay = (arguments[2] == null)?false:arguments[2];

	if(!bDisplay)
	{
		if($(oSelect).find("option[value=" + sValue + "]").length > 0)
		{
			if(oSelect.multiple)
				$(oSelect).find("option").removeAttr("selected"); //remove any selected items
				
			$(oSelect).find("option[value=" + sValue + "]").attr("selected", "selected"); //select by value
		}
	}
	else
	{
		$(oSelect).find("option").each(function()
		{
			if($(this).text() == sValue)
			{
				if(oSelect.multiple)
					$(oSelect).find("option").removeAttr("selected"); //remove any selected items
			
				$(this).attr("selected", "selected");
			}
		});
	}
}

function stackOfCaller(caller,cnt)
{
	if(null == caller.caller || cnt==15)
		return caller.toString().substr(0,caller.toString().indexOf("{"))
	else return stackOfCaller(caller.caller,cnt+1)+" in "+caller.toString().substr(0,caller.toString().indexOf("{"))
}

//encode strings
function encoder(str, pFlagASCII){
	var chars = "&'\"#<>/";
	var lHTMLChars = new Array("&amp;","'","\"","#","&lt;","&gt;","/");
	var retstr = "";
	for(var e=0;e<str.length;e++){
		var s = "";
		if(chars.indexOf(str.charAt(e))>-1)
		{
			if(true == pFlagASCII)
				retstr += escape(str.charAt(e));
			else // HTML CODE
			{
				retstr +=lHTMLChars[chars.indexOf(str.charAt(e))];
			}
		}
		else{
			retstr += str.charAt(e);
		}
	}
	return retstr;
}

function checkInt(obj){
	if(isNaN(parseInt(obj.value))){
		obj.value = 0;
		obj.select();
		return false;
	}
	return true;
}

function getParentNodeByTagName(obj,searchParentNodeName)
{
// function searches and returns parent nodes node with "searchParentNodeName" TAG NAME
// if node not found returns NULL
	if (!obj) return obj;
	searchParentNodeName = searchParentNodeName.toUpperCase();
	var oParent = obj;
	var found = false;
	
	while(oParent.nodeName.toUpperCase() != 'BODY' || oParent.nodeName.toUpperCase() != searchParentNodeName)
	{
		if(!oParent.parentNode) return null;
		oParent = oParent.parentNode;
		if(oParent.nodeName.toUpperCase() == searchParentNodeName) {found = true; break;}
	}
	
	if(found)
		return oParent;
	else
		return null;
}

function ValidateNumericInput(oTextBox, e)
{
	if(e != null)
	{	
		var key = getKey(e);
		if(key==9) return;
			oTextBox.value = oTextBox.value.match(/[\d]+/);

		if(oTextBox.value == 'null') oTextBox.value = '1';
	}  

	if(oTextBox.value == 0)	oTextBox.value = '1';
	var lLimit = oTextBox.getAttribute("Limit");
	if("" != lLimit && null != lLimit)
	{
		try{
			if(parseInt(oTextBox.value) > parseInt(lLimit))
			{
				oTextBox.value = lLimit;
			}
		}catch(e)
		{
		}
	}	
}

function gEBI(str){//shortcut for document.getElementById(strID)
	if((str!="")&&(str!=null)) return document.getElementById(str);
	else		return null;
}

function gEBN(str){//shortcut for document.getElementsByName(strID)
	return document.getElementsByName(str);
}

function gEBT(str){//shortcut for document.getElementsByTagName(strID)
	return document.getElementsByTagName(str);
}

function getKey(e)
{
if (window.event)
	return e.keyCode;
  // return window.event.keyCode;
else if (e)
   return e.which;
else
   return null;
}
  
function checkPartialMatch(str1, str2, bAnyPartialMatch)
{
	if(bAnyPartialMatch == null)
		bAnyPartialMatch = false;
		
	//if either is null return false
	if(null == str1 || null == str2)
		return false;
	if(0 == str1.length || 0 == str2.length )
		return false;
	
	//determine shorter and longer strings
	var tempShorter = str1.length > str2.length?str2:str1;
	var tempLonger = str1.length > str2.length?str1:str2;
	
	if(bAnyPartialMatch)
	{
		if(tempLonger.indexOf(tempShorter) >= 0)
			return true;
		else
			return false;
	}
	else
	{
		if(tempShorter == tempLonger.substr(0, tempShorter.length))
			return true;
		else
			return false;
	}
}

function getNameAttribute(Node)
{
	var nattr = Node.getAttribute("name");
	if("" == nattr)
		return Node.getAttribute("oname"); //Opera support: bug with name attribute
	else
		return nattr;
}

function Trim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function getValueFromXMLNode(strXML, Node, i)
{
	if(strXML == "") return "";
	//isolate Node[i]'s subNodes
	var current = Node[i];
	if("item_ID" == current)
		current = "ID";
		
	//var regex = new RegExp('<' + current + '[(\\s)((^<>)*>)]');
	var regex = new RegExp('<' + current + '(>|\\s[^<>]*>)');
//	var x = strXML.indexOf('<' + current + '>');
	if(strXML.match(regex) == null)
		return "";
	var x = strXML.match(regex).index + strXML.match(regex)[0].length;
	if(x == -1) return ""; //not found
//	x = x + 2 + current.length;
	strXML = strXML.substr(x);
	x = strXML.indexOf('</' + current + '>');
	strXML = strXML.slice(0, x) //cut end off

	//if not at last node recursively get next nodes subNodes
	if (Node[i+1] != null)
		strXML = getValueFromXMLNode(strXML, Node, i+1);
	
	return strXML
}

function getChildByIdOrName(parentNode, strId, bDeep)
{
	for(var i=0;i<parentNode.childNodes.length;i++)
	{
		var current = parentNode.childNodes[i];
		if(current.nodeType != 1) //if not element
			continue;
		
		if(strId == current.id)
			return current;
		
		if(strId == getNameAttribute(current))
			return current;
		
		//if deep child was requested then make a recursive call
		if(bDeep  && current.tagName.toUpperCase() != "SELECT")
		{
			var oNode = getChildByIdOrName(current, strId, bDeep);
			if(null != oNode)
				return oNode;
		}
	}
	return null;
}

function returnBlank(val, num)
{
	if (testNull(val)){
		return val;
	}else{
		if (num){ return 0;}else{
		return "";
		}
	}
}

function testNull(str){

		str = String(str);
		// Takes a string and tells whether it's null, blank, or undefined.
		str=str.replace(/\s/g,"");
		if (str == "null"){
			return false;
		}else if (str == "undefined"){
			return false;
		}else if (str.replace(/\s/g,"") == ""){
			return false;
		}else{
			return true;
		}
  }
//---------------------------------------------------------------------------

//---------------------------------:Progress_bar---------------------------------

/*flag
null - toggle
0 - show
1 - hide
*/
function ShowProgressbar(flag)
{
	var jsPG = $("#DarkConfirmationDiv");
	
	if(0 == flag)
		ShowProgressbarDark();
	else if(1 == flag)
		HideProgressbarDark();
	else if(!jsPG.dialog( 'isOpen' ))
		ShowProgressbarDark();
	else
		HideProgressbarDark();
	
	return false;
}

function ShowProgressbarDark()
{
	var jsPG = $("#DarkConfirmationDiv");
	
	jsPG.html('<img src="images/progress2.gif"/>');
	jsPG.show();
	jsPG.dialog('option', 'autoOpen', false);
	jsPG.dialog("open");
	return false;
}

function HideProgressbarDark()
{	
	//use timeout to delay to ensure all events from dialog initliazation are finished.
	
	window.setTimeout(function(){$("#DarkConfirmationDiv").dialog("close");}, 100);
	$("#DarkConfirmationDiv").hide();
	
	return false;
}

function IsProgressbarActive() {
    return $("#DarkConfirmationDiv").is(":visible");
}
//----------------------------------------------------------------------------------

/*
* 
*
* DOM Utility functions 
*
*/ 

/*
* 
*
* Shows one child node of a particular ID and hides others
*
*/ 
function ShowOneChildByPartialIdOrName(oParent, strPartialId, strLinkId)
{
	//determine the individual id portion of the parent object
	strParentIndividualId = strLinkId;
	
	var oChildren = getChildrenByPartialIdOrName(oParent, strPartialId)
	//loop through children
	for(var i=0;i<oChildren.length;i++)
	{
		//determine this object's id
		var strId = oChildren[i].id;
		if(0 == strId.length)
			strId = getNameAttribute(oChildren[i]);
			
		//determine the individual portion of this object's id
		var strIndividualId = getNumericId(strId);
		if("" == strIndividualId) //no individual id
			continue;
			
		if(strParentIndividualId == strIndividualId) //this is the object we have to show
		{
			InvertObjectVisibility(oChildren[i], "");
			//oChildren[i].className = "IsVisible";
			break;
		}
	}
}

/*
* 
*
* returns first childNode that matches specified nodeName 
	strTagName - comma delimited list of tags to search, i.e "INPUT,SELECT"
*
*/ 
function getChildByTagName(parentNode, strTagName, bDeep)
{
	var arrTagNames = strTagName.split(",");
	
	for(var i=0;i<parentNode.childNodes.length;i++)
	{
		var current = parentNode.childNodes[i];
		if(current.nodeType != 1) //if not element
			continue;
		
		for(var j=0;j<arrTagNames.length;j++)
			if(arrTagNames[j].toUpperCase() == current.nodeName.toUpperCase())
				return current;
			
		//if deep child was requested then make a recursive call (skip selects to avoid searching huge lists)
		if(bDeep && current.tagName.toUpperCase() != "SELECT")
		{
			var oNode = getChildByTagName(current, strTagName, bDeep);
			if(null != oNode)
				return oNode;
		}
	}
	return null;
}

/*
* 
*
* Returns all children of a node when the childs tagName matches with requested (INPUT or SELECT)
* 
*/ 
function getAllChildrenByTagName(parentNode, retArray)
{
	//loop through all children
	for(var i=0;i<parentNode.childNodes.length;i++)
	{
		var current = parentNode.childNodes[i];
		if(current.nodeType != 1) //if not element
			continue;
		
		//if ids partially match, add object to return array
		if(current.childNodes.length > 0)
			getAllChildrenByTagName(current, retArray);
		
		if("INPUT" == current.tagName ||
			"SELECT" == current.tagName)
		{
			retArray[retArray.length] = current;
		}
	}
	
	return retArray;
}

/*
* 
*
* Returns all children of a node when the children id's partially match with requested
* e.g. both id=client74 and id=client75, will be returned if "client" is requested
*/ 
function getChildrenByPartialIdOrName(parentNode, strId)
{
	var bDeep = arguments[2];
	var bAnyPartialMatch = arguments[3];
	if(null == bAnyPartialMatch)
		bAnyPartialMatch = false;
	var retArray = new Array();
	var cnt = 0;
	
	if(null == parentNode)
		return retArray; //if parent is null, there is no need to start recursion
	
	//loop through all children
	for(var i=0;i<parentNode.childNodes.length;i++)
	{
		var current = parentNode.childNodes[i];
		if(current.nodeType != 1) //if not element
			continue;
		var bFoundInId = false;
		//if ids partially match, add object to return array
		if(checkPartialMatch(strId, current.id, bAnyPartialMatch))
		{
			bFoundInId = true;
			retArray[cnt] = current;
			cnt++;
		}
		
		if(!bFoundInId && checkPartialMatch(strId, getNameAttribute(current), bAnyPartialMatch))
		{
			retArray[cnt] = current;
			cnt++;
		}
		if(bDeep)
		{
			var nodes = getChildrenByPartialIdOrName(current, strId, bDeep, bAnyPartialMatch);
			if((null != nodes)&&(nodes.length>0))
				retArray = retArray.concat(nodes);
		}
	}
	
	return retArray;
}

/*
* Returns first sibling where id or name is the exact match
* Node - current node
* strId - id of sibling
* dir - direction of search. true=forward(nextSibling), false=backwards(previousSibling)
*/ 
function getSiblingByIdOrName(Node, strId)
{
	var dir = null==arguments[2]?true:false;
	while(null != (Node = dir?Node.nextSibling:Node.previousSibling))
	{
		if(Node.nodeType != 1) //if not element
			continue;

		if(strId == Node.id)
			return Node;
			
		if(strId == getNameAttribute(Node))
			return Node;
	}
	return null;
}

/*
* Returns first or previous element sibling (not textnode)
* Node - current node
* dir - direction of search. true=forward(nextSibling), false=backwards(previousSibling)
*/ 
function getSibling(Node, dir)
{
	if (Node!=null)
	while(null != (Node = dir?Node.nextSibling:Node.previousSibling))
	{
		if(Node.nodeType != 1) //if not element
			continue;
			
		return Node;
	}
	return null;
}
function getNextSibling(Node)
{
	return getSibling(Node, true);
}
function getPreviousSibling(Node)
{
	return getSibling(Node, false);
}

/*
* 
*
* Returns all siblings of a node when the siblings' id's partially match with requested
* e.g. both id=client74 and id=client75, will be returned if "client" is requested
*/       
function getSiblingsByPartialIdOrName(Node, strId, bAnyPartialMatch)
{
	
	var retArray = new Array();
	var cnt = 0;
	if(bAnyPartialMatch == null)
		bAnyPartialMatch = false;
		
	while(null != (Node = Node.nextSibling))
	{
		if(Node.nodeType != 1) //if not element
			continue;
			
		if(checkPartialMatch(strId, Node.id, bAnyPartialMatch))
		{
			retArray[cnt] = Node;
			cnt++;
		}
		
		if(checkPartialMatch(strId, getNameAttribute(Node), bAnyPartialMatch))
		{
			retArray[cnt] = Node;
			cnt++;
		}
	}
	
	return retArray;
}

/*
* 
*
* Returns form by the form name
*/   
function getFormByName(strFormName)
{
	for(var i=0;i<document.forms.length;i++)
	{
		if(document.forms[i].name == strFormName)
			return document.forms[i];
	}
	return null;
}

//returns index of element in Form.elements array
//return -1 if element not found
function getFormElementIndex(oForm, oInput)
{
	for(var i=0; i<oForm.elements.length; i++)
	{
		if(oForm.elements[i] == oInput)
			break;
	}
	
	//return -1 if not found
	if(i == oForm.elements.length)
		return -1;
	
	return i;
}

//returns next element in form, null if not found or at end of form
function getNextFormElement(oInput)
{
	var i = getFormElementIndex(oInput.form, oInput);
	
	if(i == -1 || ((i +1) == oInput.form.length))
		return null;
		
	return oInput.form.elements[i+1];
}

function getFormElementsByTagName(oForm, sTagName)
{
	var retArray = new Array();
	
	for(var i=0; i<oForm.elements.length;i++)
		if(oForm.elements[i].tagName == sTagName)
			retArray.push(oForm.elements[i]);
			
	return retArray;
}

function getFormElementsByPartialIdOrName(oForm, sName)
{
	var retArray = new Array();
	
	for(var i=0; i<oForm.elements.length;i++)
		if(oForm.elements[i].id.indexOf(sName) >= 0 || oForm.elements[i].name.indexOf(sName) >= 0)
			retArray.push(oForm.elements[i]);
			
	return retArray;
}
/*
* 
*
* Returns all immediate children of a node by tag name 
* when a different tagName found exit
*/       
function getChildrenByTagName(parentNode, strTagName)
{
	var retArray = new Array();
	var cnt = 0;
	if(null == parentNode)
	{
		//alert("no parent");
		return retArray;
	}
	var Node = parentNode.firstChild;
	if(null == Node)
	{
		//alert("no children");
		return retArray;
	}
	
	do
	{
		if(Node.nodeType != 1) //if not element
			continue;
		
		if(Node.tagName.toUpperCase() == strTagName.toUpperCase())
			retArray[cnt++] = Node;
		else //different tagName found
			continue; 
	}while(null != (Node = Node.nextSibling))
	
	return retArray;
}

//gets a parent by a partial id
function getParentByPartialId(obj, str)
{
	while(obj.parentNode)
		if(obj.parentNode.id != null)
			if(obj.parentNode.id.search(str) != -1)
				return obj.parentNode;
			else
				obj = obj.parentNode;
	
	alert("Parent Not Found [getParentByPartialId]");
	return null;
}

//gets a parent by a partial id
function getParentByPartialIdOrName(obj, str)
{
	while(obj.parentNode)
		if(obj.parentNode.id != null)
		{
			if(obj.parentNode.id.search(str) != -1)
				return obj.parentNode;
			else
			{
				if(obj.parentNode.name != null)
					if(obj.parentNode.name.search(str) != -1)
						return obj.parentNode;
			}
			
				obj = obj.parentNode;
		}
		else
		{
			//alert("Parent Not Found [getParentByPartialId]");
			return null;
		}
	
	//alert("Parent Not Found [getParentByPartialId]");
	return null;
}


/*
* finds a 1st parent whose tagName matches the one specified 
* 
*/
function findParentByIdOrName(e, strName)
{
	if(strName == getNameAttribute(e) || strName == e.id)
		return e;
	else if (e.tagName == "BODY") 
		return null;
	else
		return findParentByIdOrName(e.parentNode, strName);
}

/*
*
*
* returns numeric portion of an id from the string like obj:76
*
*/
function getNumericId(strId)
{
	var strNumericId = "";
	var iPos = strId.indexOf(":");
	if(-1 == iPos) //no numeric id
		return "";
	
	strNumericId = strId.substr(iPos + 1);
	return strNumericId;
}

function XMLencoder(pStr, pFlagASCII){
	var lChars = "&";
	var lHTMLChars = new Array("&amp;");
	var lRetStr = "";
	for(var c=0;c<lChars.length;c++){
		var lChar = lChars.charAt(c);
		var lNewChar = (true == pFlagASCII)? escape(lChar):lHTMLChars[c];

		var i = pStr.indexOf(lChar);
		while(i>-1)
		{
			lRetStr += pStr.substr(0,i)+lNewChar;
			pStr = pStr.substr(i+1);
			i = pStr.indexOf(lChar);
		}
		lRetStr += pStr;
		pStr = lRetStr;
	}
	return lRetStr;
}

function XmlEncode(text){

    var chars = new Array(38, 60, 62, 34, 61, 39);
    
    for(var i=0;i<chars.length;i++){
        text = text.replace(String.fromCharCode(chars[i]), 
            "&#"+chars[i]+";");
    }
    
    return text;
}

function PrintThisPage()
{
	window.print();
	return false;	
}

function DateToXMLString(dt, bConvertTime, bToGMT)
{
	bConvertTime = (arguments[1] == null)?true:bConvertTime;
	bToGMT = (arguments[2] == null)?true:bToGMT;
	
	var yr, dy, mon, hrs, mins, secs, offset;
	if(bToGMT){
		yr = dt.getUTCFullYear();
		mon = dt.getUTCMonth() + 1;
		dy = dt.getUTCDate();
		hrs = dt.getUTCHours();
		mins = dt.getUTCMinutes();
		secs = dt.getUTCSeconds();
		offset = dt.getTimezoneOffset();
	}
	else{
		yr = dt.getFullYear();
		mon = dt.getMonth() + 1;
		dy = dt.getDate();
		hrs = dt.getHours();
		mins = dt.getMinutes();
		secs = dt.getSeconds();
		offset = dt.getTimezoneOffset();
	}

	if(!bConvertTime)
		offset = 0;
	
	var strYr, strDy, strMon, strHours, strMins, strSecs, strOffset;
	strYr = PadInFront(yr, 4);
	strMon = PadInFront(mon, 2);
	strDy = PadInFront(dy, 2);
	strHours = PadInFront(hrs, 2);
	strMins = PadInFront(mins, 2);
	strSecs = PadInFront(secs, 2);
	
	var nOffsetHours, nOffsetMinutes, strOffsetSign;
	nOffsetMinutes = offset % 60;
	nOffsetHours = (offset - nOffsetMinutes) / 60;
	
	//find out if we are ahead or behind UTC
	if(nOffsetHours > 0)
		strOffsetSign = "-";
	else
		strOffsetSign = "+";
		
	//Remove Sign
	nOffsetMinutes = Math.abs(nOffsetMinutes);
	nOffsetHours = Math.abs(nOffsetHours);
	
	strOffset = strOffsetSign + PadInFront(nOffsetHours, 2) + PadInFront(nOffsetMinutes, 2);
	
	//assemble the string
	return strYr + "-" + strMon + "-" + strDy + "T" + strHours + ":" + strMins + ":" + strSecs + ".0000000";// + strOffset; //.NET 2 version
	
	//return strYr + "-" + strMon + "-" + strDy + "T" + strHours +  ":" + strMins + ":" + strSecs + ".0000000" + strOffset;
}

function StopClick(e)
{
	if(null == e && typeof(window.event) == "undefined")
		return;

	if (!e) 
		var e = window.event;
		
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

/*---------------------------------------:DateTime---------------------------------------*/
function PadInFront(Val, nZeroes)
{
	retVal = "" + Val; //convert to string
	while(retVal.length < nZeroes)
		retVal = "0" + retVal;
		
	return retVal;
}
/*---------------------------------------------------------------------------------------*/
 
 function showPerformanceContent(oTr,EventID,ShortDate)
{
	var oSpan=oTr.cells[0].childNodes[0];
	if(oSpan.innerHTML==null) oSpan=oTr.cells[0].childNodes[1];
	
	var oDiv = null;
	if(typeof(showHidePrfListContent) == "function")
		oDiv = showHidePrfListContent(oSpan);
	else
		oDiv = showHideLeftContent(oSpan);
	
	oDiv.innerHTML="<center><img src='images/loader.gif'/></center>";
	$.post("FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=2&d1=" + ShortDate+"&EvId="+EventID
		,function(data){
			fillPerformanceContent(data, oDiv)
		});
}

function fillPerformanceContent(strResp,oDiv)
{
	var oSpan = document.createElement("SPAN");
	oSpan.innerHTML = strResp;
	oSpan=getChildByTagName(oSpan,'span',true);
	var lWords = oSpan.innerHTML.split('<!-- Calendar -->');
	oSpan.innerHTML = lWords[0];
	oDiv.innerHTML = "";
	oDiv.appendChild(oSpan);
}

function GetRandomQSParam()
{
	var nNum = getRandomInt(0, 1000000); 
	return "rnd=" + String(nNum);
}

function getRandomInt(minN,maxN)
{
	return Math.round(Math.random()*(maxN-minN)) + minN;
}

//---------------------------------:PerformanceList---------------------------------
function ShowPerformance(oDiv, PerfID, ClId, SoldOut, nAgyId)
{
    if (SoldOut != null && SoldOut == 'True')
    {
        alert("This Performance is sold out!");
        return;
    }
    
    ShowProgressbar();

    $(oDiv).css("color", "#FF0099");
    $(oDiv).attr("select", "1");

    var req = 'EventsPage.aspx?PerfID=' + PerfID;

    if ("number" == typeof (nAgyId))
        if (nAgyId > 0)
            return NavOut( req + '&QuickSales=1');

    if ($("#QuickSales_Bar").is(':visible')) {
        req += '&QuickSales=1';
        SetCookie(ClId + "QSPerformance", PerfID, null, "/");
        SetCookie(ClId + "Sales_ShowTab", 4, null, "/");
    }

    return NavOut(req);
}

function StopClick(e)
{
	if(null == e && typeof(window.event) == "undefined")
		return;

	if (!e) 
		var e = window.event;
		
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function ShowHidePerformanceList(oSpan,EventID,DefCount)
{
	 var DivArray = getChildrenByPartialIdOrName(gEBI("PerfLisDiv"+EventID),"PerformanceDiv"+EventID,false);
	 
     if (DivArray[DefCount] != null && DivArray[DefCount].style.display == 'none')
         for (var i = 0; i < DivArray.length; i++) 
            DivArray[i].style.display='block';
	 else
	     for (var i = DefCount; i < DivArray.length; i++) 
            DivArray[i].style.display='none';
}

function SetCalendarMonth(month,year)
{
	ShowProgressbarDark();
	
	var strShortDate = "" + year + "-" + month + "-1";
	var strURL = "FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=0&d1=" + strShortDate +"&ne="+(arguments[2]!=null&&arguments[2]!=""?"&for="+arguments[2]:"");
	var oldSales;
	if(arguments[2]!=null&&arguments[2]!="")
		{
			oldSales=true;
		}
	var daytoshow=0;
	if(arguments[3]!=null&&arguments[3]!="")
		{
			daytoshow=arguments[3];
		}
	
	$.post(strURL, function(data){
			var oSpan = document.createElement("SPAN");
			$(oSpan).html(data);
			
			var strHTMLCal = "";
			var jsChild = $(oSpan).find("span");
			if(jsChild.length > 0)
				strHTMLCal = $(jsChild[0]).html();
			
			var divEventsList="DivContent";
			var divCalendar="DivCalendar";
			
			if(oldSales)
			{
				divEventsList="divSingle";
				divCalendar="tdCal";
			}
			
			var lWords = strHTMLCal.split('<!-- Calendar -->');
			$("#"+divEventsList).html("<span>" + lWords[0] + "</span>");
			
			if(lWords.length > 0)
				$("#"+divCalendar).html("<span>" + lWords[1] + "</span>");

			// for old sales
			$("#divOrders").show();
			$("#divNonOrders").hide();

			HideProgressbarDark();
			
			//reinit aspnet postback form reference, if needed
			if("undefined" == typeof(theForm))
			{
				theForm = document.forms['aspnetForm'];
				if (!theForm) 
					theForm = document.aspnetForm;
			}
			
			if(daytoshow!=0)
			{
				var visible_count=SetDate(daytoshow);
				if(visible_count==0) // if there are no today performnce show the default view
				{
					ShowProgressbarDark();
					window.location="EventsPage.aspx";
				}
			}
		});
}

function SetDate(date)
{
	var prflistVisible=$("div[name^=PerformanceDiv][date="+date+"]");	
	var prflistInVisible=$("div[name^=PerformanceDiv][date!="+date+"]");	
	prflistVisible.css('display','block');
	prflistInVisible.css('display','none');
	var visible_count=0;
	$("div[name^=EventsDiv]").each(function()
		{		
			if($(this).find("div[name^=PerformanceDiv][date="+date+"]").length>0)
			{
				$(this).show();
				visible_count++;
			}
			else
				$(this).hide();
		});
	// for old sales
	$("#divOrders").show();
	$("#divNonOrders").hide();
	return visible_count;
}

function SetWeek(WeekNum)
{
	var prflistVisible=$("div[name^=PerformanceDiv][WeekNum="+WeekNum+"]");	
	var prflistInVisible=$("div[name^=PerformanceDiv][WeekNum!="+WeekNum+"]");	
	prflistVisible.css('display','block');
	prflistInVisible.css('display','none');
	$("div[name^=EventsDiv]").each(function()
		{		
			if($(this).find("div[name^=PerformanceDiv][WeekNum="+WeekNum+"]").length>0)
				$(this).show();
			else
				$(this).hide();
		});
	// for old sales
	$("#divOrders").show();
	$("#divNonOrders").hide();
}

function SetWeekDay(Weekday)
{
	var prflistVisible=$("div[name^=PerformanceDiv][Weekday="+Weekday+"]");	
	var prflistInVisible=$("div[name^=PerformanceDiv][Weekday!="+Weekday+"]");	
	prflistVisible.css('display','block');
	prflistInVisible.css('display','none');
	$("div[name^=EventsDiv]").each(function()
		{		
			if($(this).find("div[name^=PerformanceDiv][Weekday="+Weekday+"]").length>0)
				$(this).show();
			else
				$(this).hide();
		});
	// for old sales
	$("#divOrders").show();
	$("#divNonOrders").hide();
}

function SetDateRange(date1,date2)
{
	$("div[name^=EventsDiv]").each(function()
		{	
			var perfcounter=0;	
			$(this).find("div[name^=PerformanceDiv]").each(function()
				{		
					if(this.getAttribute("date")>=date1 && this.getAttribute("date")<=date2)
					{
						$(this).show();
						perfcounter++;
					}
					else
						$(this).hide();
				});	
				
			if(perfcounter==0)
				$(this).hide();
			else
				$(this).show();
		});	
	// for old sales
	$("#divOrders").show();
	$("#divNonOrders").hide();
}

function showHidePrfListContent(oSpan)
{
	var oDiv=oSpan.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
	if(oDiv.childNodes[0].innerHTML==null) oDiv=oDiv.childNodes[3];
	else oDiv=oDiv.childNodes[1];
	if(oDiv.style.display=='none')
	{
		oDiv.style.display='block';
		var html=oSpan.innerHTML.replace('expand','collapse');		
		oSpan.innerHTML=html;
	}
	else
	{
		oDiv.style.display='none';
		var html=oSpan.innerHTML.replace('collapse','expand');	
		oSpan.innerHTML=html;
	}
	return oDiv;
}

function showHideLeftContent(oSpan)
{
	var oDiv=oSpan.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
	if(oDiv.childNodes[0].innerHTML==null) oDiv=oDiv.childNodes[3];
	else oDiv=oDiv.childNodes[1];
	if(oDiv.style.display=='none')
	{
		oDiv.style.display='block';
		oSpan.innerHTML = oSpan.innerHTML.replace("expand_", "collapse_");  
		//"<img src='images/collapse_new.gif'/>";
	}
	else
	{
		oDiv.style.display='none';
		oSpan.innerHTML = oSpan.innerHTML.replace("collapse_", "expand_");
		//oSpan.innerHTML="<img src='images/expand_new.gif'/>";
	}
}

function NavigateMoveOverPerformance(oDiv)
{
if(arguments[1]!=null && arguments[1]=='True') return;
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0000'
}
}

function NavigateMoveOutPerformance(oDiv)
{
if(arguments[1]!=null && arguments[1]=='True') return;
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#000000';
}
}

function NavigateMoveOutSinglePerformance(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='';
}
}
//---------------------------------------------------------------------------------- 
 var gPerformancePieChart = null;

function Ticket_In_Shopping_Cart(oTD,vPerformanceId,SeatId)
{
	var lgSeasonLightningSeat = false;
	if(typeof(gSeasonLightningSeat) != "undefined")
		lgSeasonLightningSeat = gSeasonLightningSeat;
	
	if(null == gEBI("HoldBlocks")) 
		return;
		
	var sh = gEBI("divTicketDetails");
	var strTds = "<table width='100%'><tr><td style='BACKGROUND-COLOR:#5587AD;'><a href='#' onclick='return CloseDivTicketDetails();' style='text-decoration: none' class='AItemDetail'>" + GetTranslation('close') + "</a></td></tr></table><nobr><b>"+oTD.getAttribute("title")+"</b></nobr><br />";
	strTds +="<div id='PlzWaitTicketDetails'>" + GetTranslation('seat_is_held_shopping_cart') +  "</div>";
	strTds +="<div style='display:none;FONT:8pt Arial;' id='SeatInformationHold'></div>";
	sh.innerHTML = strTds;
	sh.style.display = 'block';
	var sPerfList = vPerformanceId;		
	if(lgSeasonLightningSeat && null != gPerfs && gPerfs.length > 0)
	{
		sPerfList = "";
		var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, vPerformanceId); //this is old sales only!
		for(var i = 0; i < lCurrPerfs.length; i++)
		{
			sPerfList +=lCurrPerfs[i][0]+",";
		}
	}
	var strXML = "<envelope><body><command name=\"ReleaseHolds\"><class name=\"Seats\" />";
	strXML += "<param type=\"Seat\"><Seat><ErrorString></ErrorString><ID>"+SeatId+"</ID></Seat></param>";
	strXML += "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
	strXML += "</command></body></envelope>"; 
	
	$.post("UserControls/ObjectFactory.aspx", 
		strXML, 
		function(data){
			FillSeatInformationHold(data, SeatId);
		});
}
function ReleaseSeatHold(pSeatId,pTicketId,pPerfs)
{
	var strXML = "<envelope><body><command name=\"ReleaseHolds\"><class name=\"Seats\" />";
		strXML += "<param type=\"Seat\"><Seat><ErrorString></ErrorString><ID>"+pSeatId+"</ID></Seat></param>";
		strXML += "<param type=\"Ticket\"><Ticket><ErrorString></ErrorString><ID>"+pTicketId+"</ID></Ticket></param>";
		strXML += "<param type=\"System.String\"><string>"+pPerfs+"</string></param>"; 
		strXML += "</command></body></envelope>"; 
	
	$.post("UserControls/ObjectFactory.aspx", 
			strXML, 
			function(data){
				FillSeatInformationHold(data, pSeatId);
			});
}
function CloseDivTicketDetails()
{
	var sh = gEBI("divTicketDetails");
	if(sh != null)
		sh.style.display = 'none';
		
	return false;
}

function FillSeatInformationHold(strResp,pSeatId)
{
	gEBI("SeatInformationHold").innerHTML=strResp;
	gEBI("SeatInformationHold").style.display="block";
	if(""==Trim(strResp))
	{
		var oTD = gEBI(pSeatId);
		oTD.setAttribute("shopping_cart","0");
		oTD.setAttribute("hold","0");
		oTD.style.backgroundColor = oTD.getAttribute("defCol");
		CloseDivTicketDetails();
	}
}

function sendXmlHttpRequest_for_history(SeatId, sPerfList)
{
	var strXML = "<envelope><body><command name=\"Populate\"><class name=\"Seats\" />";
	strXML += "<param type=\"Seat\"><Seat><ErrorString></ErrorString><ID>"+SeatId+"</ID></Seat></param>";
	strXML += "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
	if(arguments[2]!=null) strXML +="<param type=\"Ticket\"><Ticket><ErrorString></ErrorString><ID>"+arguments[2]+"</ID></Ticket></param>";
	strXML += "</command><xslt>boxUtilityTemplates.xslt</xslt></body></envelope>"; 
	
	$.post("UserControls/ObjectFactory.aspx", 
			strXML, 
			function(data){
				FillSeatInformationOrder(data);
			});
}

function FillSeatInformationOrder(strResp)
{
	$("#PlzWaitTicketDetails").hide();
	
	$("#SeatInformationOrder").html(strResp.substring(0,strResp.lastIndexOf("||")));
	$("#SeatInformationOrder").show();
	
	var jqSIM = $("#SeatInformationMenu")
	if(jqSIM.length > 0)
	{
		var strHTML = "<a href='#' style='text-decoration: none' onclick='return HideDisplayTicketHistory();' class='AItemDetail'>" + GetTranslation("ticket_history") + "</a><br />";
		strHTML += strResp.substring(strResp.lastIndexOf("||")+2,strResp.length);
		
		jqSIM.html(strHTML);
		jqSIM.show();
	}
}

function HideDisplayTicketHistory()
{
	$("#txtTicketHistory").toggle();
	return false;
}

function showSeatName(sSeatName)
{
	window.status = sSeatName;
	$("#divHoverSeat").html(": " + sSeatName);
}

function clearSeatName()
{
	window.status = "";
	$("#divHoverSeat").html("<br/>");
}

function BuildDivTicketDetails(oTD,ticketId, vPerformanceId, SeatId)
{
	var lgSeasonLightningSeat = false;
	if(typeof(gSeasonLightningSeat) != "undefined")
		lgSeasonLightningSeat = gSeasonLightningSeat;

	var sh = gEBI("divTicketDetails");
	var strTds = "<table width='99%'><tr><td style='BACKGROUND-COLOR:#5587AD;'><a href='#' onclick='return CloseDivTicketDetails();' style='text-decoration: none' class='AItemDetail'>" + GetTranslation('close') + "</a></td></tr></table><NOBR><B>"+oTD.getAttribute("title")+"</B></NOBR><br/>";
	var sPerfList = "";
	strTds +="<Div id='PlzWaitTicketDetails'><br/>" + GetTranslation('Please_wait') + "<img src='images/SpinningWheel.gif'/><br/></Div>";
	strTds +="<Div style='display:none;' id='SeatInformationOrder'></Div>";
	sh.innerHTML = strTds;
	strTds="";
	if(lgSeasonLightningSeat && null != gPerfs && gPerfs.length > 0)
	{
		var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, vPerformanceId);
		for(var i = 0; i < lCurrPerfs.length; i++)
		{
			sPerfList +=lCurrPerfs[i][0]+",";
		}
		sendXmlHttpRequest_for_history(SeatId,sPerfList);
	}
	else
	{
		sendXmlHttpRequest_for_history(SeatId,vPerformanceId,ticketId);
		if(window.opener == null && oTD.getAttribute("isSelected") == null) 
			strTds = "<Div style='display:none;' id='SeatInformationMenu'></Div>";
	}
	sh.innerHTML += strTds;
	sh.style.display = 'block';
}

//----------------------:PieChart-----------------------------------------------
function ShowPerformanceInfo(pClid, pLayid, pPerfid, e)
{	
	ShowPerformancePieChart(pClid,pLayid,pPerfid,0,"PerformancePieChart","",false,ShowPerformanceInfoComplete);
	
	var cX = 0;
	var cY = 0;
	if(!e) 
	{
		e = window.event; 
		cX = e.x;
		cY = e.y;
	}
	else
	{
		cX = e.clientX;
		cY = e.clientY;
	}
	
	var oPerfInfo = gEBI("PerformanceInfo");
	if(null == oPerfInfo) 
		return;
	
	oPerfInfo.style.display = "block";
	oPerfInfo.style.left = document.body.scrollLeft + cX + 10;
	oPerfInfo.style.top = document.body.scrollTop + cY + 20;
	
	ShowPerformanceInfoComplete();
}
//To be sure to leave the pie chart on the popup icon
function ShowPerformanceInfoComplete()
{
	var lPerfInfo = gEBI("PerformanceInfo");
	if(null == lPerfInfo) 
		return;
	
	if(//vertical
		(parseInt(lPerfInfo.style.top)+parseInt(lPerfInfo.clientHeight)) > 
		(parseInt(document.body.scrollTop)+parseInt(document.body.clientHeight))
		)
	{
		lPerfInfo.style.top = parseInt(document.body.scrollTop)+parseInt(document.body.clientHeight) - parseInt(lPerfInfo.clientHeight);
	}
	if(//horizontal
		(parseInt(lPerfInfo.style.left)+parseInt(lPerfInfo.clientWidth)) > 
		(parseInt(document.body.scrollLeft)+parseInt(document.body.clientWidth))
		)
	{
		lPerfInfo.style.left = parseInt(document.body.scrollLeft)+parseInt(document.body.clientWidth) - parseInt(lPerfInfo.clientWidth);
	}
	
}

function ClosePerformanceInfo()
{
	gEBI("PerformanceInfo").style.display="none";
}

function ShowPerformancePieChart(pClid,pLayid,pPerfid,pSecid,pDivId,pUpperDivId,bIsGA,pFunctionComplete)
{
	var lgSeasonLightningSeat = false;
	if(typeof(gSeasonLightningSeat) != "undefined")
		lgSeasonLightningSeat = gSeasonLightningSeat;
	if(true == lgSeasonLightningSeat)
		return;
		
	if(pSecid!=0)
	{
		// if section is not 0 and we want to get the Section Info pDivId - doesn't exist and we must create it
		pDivId=""+pDivId+pSecid;
		if(pSecid!=gSecid) 
			return;
		
		var PieArr=getChildrenByPartialIdOrName(gEBI(pUpperDivId),'PerformancePieChart',false);
		if(PieArr!=null && PieArr.length > 0) 
			for(var i =0;i<PieArr.length;i++) 
				PieArr[i].style.display = "none";
				
		if(null == gEBI(pDivId)) 
		{
			var oDIV=gEBI('divMapLegend');
			if(oDIV == null ) return;
			oDIV.innerHTML+="<div name='PerformancePieChart' id='"+pDivId+"'>";		
		}
		else
		{
			gEBI(pDivId).style.display = "block";
			return;
		}
		gEBI(pUpperDivId).style.display='block';		
	}
	
	var lDiv = gEBI(pDivId);
	if(null == lDiv ) return;
	
	if(null == gPerformancePieChart)
	{
		gPerformancePieChart = new Object();

		var lPerfPieChart = {ClientId : pClid, LayoutId : pLayid, PerformanceId : pPerfid, SectionId : pSecid};
		if(
			lDiv.PerformanceId	== lPerfPieChart.PerformanceId && lDiv.SectionId == lPerfPieChart.SectionId
		)
		{
			lDiv.style.display = "block";
			gPerformancePieChart = null;
		}
		else
		{
			var Url="PerformancePieChart.aspx?isWeb=" + (isWeb) + "&clid=" + lPerfPieChart.ClientId + "&layid=" + lPerfPieChart.LayoutId + "&perfid=" + lPerfPieChart.PerformanceId + "&secid=" + lPerfPieChart.SectionId;
			if(lPerfPieChart.SectionId!=0)
			{	
				Url+="&type=1";	
				lDiv.innerHTML = "<center>" + GetTranslation("loading_section") + "...<br/><IMG src='images/Loading.gif'/></center>";
			}
			else  
				lDiv.innerHTML = "<img src='images/SpinningWheel.gif'/>";
			
			if(bIsGA)
				Url += "&sectionGA=1";
			
			$.ajax({
				type: "POST",
				url: Url,
				data: "<a></a>",
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					ResponsePerformancePieChart(data, pDivId, lPerfPieChart, pFunctionComplete)
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					//alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
		}
	}
	
	if(null != gPerformancePieChart)
	{
		gPerformancePieChart.ClientId		= pClid;
		gPerformancePieChart.LayoutId		= pLayid;
		gPerformancePieChart.PerformanceId	= pPerfid;
		gPerformancePieChart.SectionId		= pSecid;
	}
}

function GetPerformancePieChart(pClid,pLayid,pPerfid,pSecid,pDivId,pUpperDivId,bIsGA,pFunctionComplete)
{
	gSecid=pSecid;
	if(null != gEBI(pDivId+pSecid)) 
		ShowPerformancePieChart(pClid,pLayid,pPerfid,pSecid,pDivId,pUpperDivId,bIsGA,pFunctionComplete);
	else 
		window.setTimeout(function(){ShowPerformancePieChart(pClid,pLayid,pPerfid,pSecid,pDivId,pUpperDivId,bIsGA,pFunctionComplete);}, 1500);
}

function ResponsePerformancePieChart(strResp,pDivId,pPerfPieChart,pFunctionComplete)
{
	if(null == gPerformancePieChart) 
		return;

	var lDiv = gEBI(pDivId);
	if(null == lDiv) return;

	if(
		gPerformancePieChart.PerformanceId	== pPerfPieChart.PerformanceId &&
		gPerformancePieChart.SectionId		== pPerfPieChart.SectionId
	)
	{
		gPerformancePieChart = null;
		
		lDiv.PerformanceId	= pPerfPieChart.PerformanceId;
		lDiv.SectionId		= pPerfPieChart.SectionId;
		lDiv.innerHTML = strResp;
		lDiv.style.display = "block";
		if(null != pFunctionComplete)
			pFunctionComplete();
	}
}
//---------------------------------------------------------------------------
 
 //depends on jquery dialog
function ShowPopUpInput(perfID)
{
	var oDiv=gEBI("ForModalWindow");
	if(oDiv == null)
	{
		oDiv = document.createElement('DIV');
		oDiv.id="ForModalWindow";
		oDiv.style.display = 'none';
		document.body.appendChild(oDiv);	
	}
	var sHTML = "<DIV style='width:830px;height:620px' class='SectionDiv_old'>";
		sHTML += "<DIV class='SectionDivContent_old'>";	
		sHTML += "<center><iframe id='iframe' style='BORDER-RIGHT: medium none; BORDER-TOP: medium none; BACKGROUND: none transparent scroll repeat 0% 0%; BORDER-LEFT: medium none; BORDER-BOTTOM: medium none' src='PerformanceEditor.aspx?PerfID="+perfID+"' frameBorder='0' width='830px' height='640px' scrolling='auto'  allowTransparency>Your browser does not support IFrames. Please upgrade. </iframe></center>";
		sHTML += "</DIV>";
		sHTML += "</DIV>";
	oDiv.innerHTML = sHTML;

	
	modaldialogfromdiv("ForModalWindow", 840, 640, false, "Edit Performance");
}
 
 function RefreshSession()
{
	$.post("blank.aspx", function(data){	});
}

function modaldialogfromdiv(strDivId, nWidth, nHeight, bDraggable, strTitle, bUseASPNETHack, CloseFunction, bOKButton)
{
	var oDialogOptions = {
					    modal: true,
					    resizable: false,
					    draggable: bDraggable,
					    autoOpen: false,
					    width: nWidth,
					    height: nHeight,
					    title : strTitle, 
					    closeText : GetTranslation("close"), 
					    close : CloseFunction,
					    overlay: {
					        opacity: 0.5,
					        background: "black"
					    }
					};
	
	if(bUseASPNETHack)
		oDialogOptions.open = function(){
				$(this).parent().appendTo("form");
			};

    if (bOKButton != null && bOKButton == true)
        oDialogOptions.buttons = { "Ok": function () { $(this).dialog("close"); } };


    jQuery("#" + strDivId).dialog(
					oDialogOptions
				);

	jQuery("#" + strDivId).show();
	var dlg = jQuery("#" + strDivId).dialog("open");
	
	return false;
}

function copyPatronToShipping()
{
	$("#shipping_salutation1").val( $("#patron_salutation1").val() );
	$("#shipping_firstname1").val( $("#patron_firstname1").val() );
	$("#shipping_lastname1").val( $("#patron_lastname1").val() );
	
	$("#shipping_salutation2").val( $("#patron_salutation2").val() );
	$("#shipping_firstname2").val( $("#patron_firstname2").val() );
	$("#shipping_lastname2").val( $("#patron_lastname2").val() );
	
	$("#shipping_company").val( $("#patron_company").val() );
	$("#shipping_address").val( $("#patron_address").val() );
	$("#shipping_address2").val( $("#patron_address2").val() );
	
	$("#shipping_city").val( $("#patron_city").val() );
	$("#shipping_state").val( $("#patron_state").val() );
	$("#shipping_zip").val( $("#patron_zip").val() );
	$("#shipping_city").val( $("#patron_city").val() );
	$("#shipping_country").val( $("#patron_country").val() );
	$("#shipping_region").val( $("#patron_region").val() );
	
	$("#shipping_phone").val( $("#patron_phone").val() );
	$("#shipping_phonetype").val( $("#patron_phonetype").val() );
	$("#shipping_email").val( $("#patron_email").val() );
	$("#shipping_emailtype").val( $("#patron_emailtype").val() );

	for(var i=1;i<=7;i++)
	{
		if(0 == $("#patron_custom" + i).length || 0 == $("#shipping_custom" + i).length)
			continue;
		
		$("#shipping_custom" + i).val( $("#patron_custom" + i).val() );
		SetCustomCartFields("shipping_custom" + i);
	}
	
    /*
    removed by JL 12/22/2011.  we want to update shipping address, do not reuese billing id
	$("#patron_shippingaddressid").val( $("#patron_billingaddressid").val() );
    */

	SetCountryAndState("patron");
	SetCountryAndState("shipping");
 }
 
function GetShippAddress()
{
	var lXMLData = $("#selShippDetails option:selected").attr("ShippXML");
	if("" == lXMLData || null == lXMLData)
		return;

	var lPatronAddress = JSObjectFromXML(lXMLData);
		
	var lAddress = new Object();
	if(null != lPatronAddress && null != lPatronAddress.Address)
		lAddress = lPatronAddress.Address;
		
	$("#patron_shippingaddressid").val( (null != lAddress.ID?String(lAddress.ID):"0") );
	
	$("#shipping_salutation1").val( (null != lAddress.Salutation?String(lAddress.Salutation):"") );
	$("#shipping_firstname1").val( (null != lAddress.FirstName?String(lAddress.FirstName):"") );
	$("#shipping_lastname1").val( (null != lAddress.Name?String(lAddress.Name):"") );
	
	$("#shipping_salutation2").val( (null != lAddress.PartnerSalutation?String(lAddress.PartnerSalutation):"") );
	$("#shipping_firstname2").val( (null != lAddress.PartnerFirstName?String(lAddress.PartnerFirstName):"") );
	$("#shipping_lastname2").val( (null != lAddress.PartnerLastName?String(lAddress.PartnerLastName):"") );
	
	$("#shipping_company").val( (null != lAddress.Company?String(lAddress.Company):"") );
	$("#shipping_address").val( (null != lAddress.Street?String(lAddress.Street):"") );
	$("#shipping_address2").val( (null != lAddress.Street2?String(lAddress.Street2):"") );
	
	$("#shipping_city").val( (null != lAddress.City?String(lAddress.City):"") );
	$("#shipping_state").val( (null != lAddress.State?String(lAddress.State):"") );
	$("#shipping_zip").val( (null != lAddress.ZIP?String(lAddress.ZIP):"") );

	$("#shipping_country").val( (null != lAddress.Country?String(lAddress.Country):"") );
	$("#shipping_region").val( (null != lAddress.Region?String(lAddress.Region):"") );
	
	$("#shipping_phone").val( (null != lAddress.Phone?String(lAddress.Phone):"") );
	$("#shipping_email").val( (null != lAddress.EMail?String(lAddress.EMail):"") );
	
	$("#shipping_phonetype option").each(function(index)
	{
		if($(this).text() == (null != lAddress.PhoneType?String(lAddress.PhoneType):"") || 0 == index)
		{
			$(this).attr("selected", "selected");
			return;
		}
	});
	
	$("#shipping_emailtype option").each(function(index)
	{
		if($(this).text() == (null != lAddress.EmailType?String(lAddress.EmailType):"") || 0 == index)
		{
			$(this).attr("selected", "selected");
			return;
		}
	});
				
	for(var i=1;i<=7;i++)
	{
		if(0 == $("#shipping_custom" + i).length)
			continue;
		
		var xmlVal = eval("lAddress.Custom" + i);
		if(null == xmlVal)
			xmlVal = "";
		
		var jsCust = $("#shipping_custom" + i);
		jsCust.val( xmlVal );
		SetCustomCartFields("shipping_custom" + i);
		
		if( -1 == jsCust.attr("selectedIndex"))
			jsCust.attr("selectedIndex", 0);
	}
	
	SetCountryAndState("patron");
	SetCountryAndState("shipping");
}
 
function getClientCoupons(){
	getClientCoupon(0, 0); 
}

function getClientCoupon(rcID, cpID){
	clXML = "<Client><ID>" + gClientId + "</ID></Client>";
	
	if(rcID > 0 && cpID > 0)
	{
		rcXML = "<string>" + rcID + "</string>";
		cpXML = "<string>" + cpID + "</string>";
		orderIdXML = "<string>" + oParentIDHolder["gEditOrderId"] + "</string>";
	}

	var strRequestXML = "<envelope><body>" +
						"<command name=\"Populate\">" +
						"<class name=\"" + 'RedeemedCoupons' + "\" />";
						
	strRequestXML += "<param type=\"" + "Client" + "\">" + clXML + "</param>";
	
	if(rcID > 0 && cpID > 0)
	{
		strRequestXML += "<param type=\"" + "System.String" + "\">" + rcXML + "</param>";  //olegc
		strRequestXML += "<param type=\"" + "System.String" + "\">" + cpXML + "</param>";
		strRequestXML += "<param type=\"" + "System.String" + "\">" + orderIdXML + "</param>";
	}

	var strXsltName = "CouponSell.xslt";	//just pull back xml
	strRequestXML += "</command>" +
						"<xslt>" + strXsltName + "</xslt>" +
						"</body></envelope>";
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: gSOAPListenerURL,
				data: strRequestXML,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					var strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});					
	
	xml = '<ArrayOfRedeemedCoupon>' + HtmlDecode(strResp) + '</ArrayOfRedeemedCoupon>';

	gClientCoupons = new JSObjectFromXML(xml);
}

function GetXFromInt(i)
{
	var strX = "";
	var x = i % 36;
	var rem = Math.floor(i / 36);
	strX = I2X(x);
	if(rem>0)
	{
		strX = GetXFromInt(rem) + strX;
	}
	return strX;
}

function GetIntFromX(X)
{
	var arr = X.split('');
	var I = 0;
	for(var i=0;i<arr.length;i++)
	{	
		var c = arr[arr.length-i-1];
		var x = X2I(c);
		I += Math.pow(36,i) * x;
	}
	return I;
}

function I2X(i)
{
	var arrX = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	return arrX[i];
}

function X2I(x)
{
	var I = -1;
	var arrX = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	for(var i=0;i<arrX.length;i++)
	{
		if(x==arrX[i])
		{
			I = i;
			break;
		}
	}
	return I;
}


function buildCustomXML(oCustom,CustomN)
{
	if(null == oCustom || "undefined" == typeof(oCustom))
		return ""; 
	
	var OKReturn = "<"+CustomN+"><![CDATA["+String(oCustom.value)+"]]></"+CustomN+">";
	
	if("Salutation" == CustomN) //NEVER require salutation
		return OKReturn;
	
	//skip validation for QuickSale Mode
	if(gQuickSaleMode && !isPatron)
		return OKReturn;
	
	if(null != gEBI("chSippAddress"))
	{
		if( true != oCustom.disabled && null != oCustom.getAttribute("required") &&
			"true" == oCustom.getAttribute("required").toLowerCase() && 
			(
				("" == returnBlank(String(oCustom.value)) && gEBI("chSippAddress").checked) || 
				("" == returnBlank(String(oCustom.value)) && !gEBI("chSippAddress").checked && oCustom.id.indexOf("patron")!=-1) || 
				("checkbox" == oCustom.getAttribute("CustomType") && "false" == oCustom.value.toLowerCase())
			)
		)
		{
			if(oCustom.getAttribute("RequiredMessage") != null && oCustom.getAttribute("RequiredMessage") != "")
				alert(oCustom.getAttribute("RequiredMessage"))
			else
				alert(oCustom.getAttribute("CustomName") + " "+GetTranslation("cannot_be_empty")+"!")
			EraseOrderData(true);
			return "0";
		}
	}
	else
	{
		if( true != oCustom.disabled && 
			"true" == oCustom.getAttribute("required").toLowerCase() &&
			(
				"" == returnBlank(String(oCustom.value)) || 
				("checkbox" == oCustom.getAttribute("CustomType") && "false" == oCustom.value.toLowerCase())
			)
		)
		{
			if(oCustom.getAttribute("RequiredMessage") != null && oCustom.getAttribute("RequiredMessage") != "")
				alert(oCustom.getAttribute("RequiredMessage"))
			else
				alert(oCustom.getAttribute("CustomName") + " "+GetTranslation("cannot_be_empty")+"!")
			EraseOrderData(true);
			return "0";
		}
	}	
	
    //check for valid email format on email field
    if ("EmailAddress" == CustomN) 
    {
        if("" != returnBlank(String(oCustom.value)))  //if value entered, validate it
	        if(!isValidEmailAddress(returnBlank(String(oCustom.value))))
            {
                alert("Please enter a valid email address");
                EraseOrderData(true);
			    return "0";
            }
	}

	return OKReturn;
}

function OrderBuildBillingAddressXML()
{
	var strBA = "<BillingAddress>";
	
	if(null != gEBI("patron_firstname1"))
		strBA +=	"<FirstName><![CDATA[" + gEBI("patron_firstname1").value + "]]></FirstName>";
	if(null != gEBI("patron_lastname1"))
		strBA +=	"<Name><![CDATA[" + gEBI("patron_lastname1").value + "]]></Name>";
	if(null != gEBI("patron_address"))
		strBA +=	"<Street><![CDATA[" + gEBI("patron_address").value + "]]></Street>";
	if(null != gEBI("patron_address2"))
		strBA +=	"<Street2><![CDATA[" + gEBI("patron_address2").value + "]]></Street2>";
	if(null != gEBI("patron_city"))
		strBA +=	"<City><![CDATA[" + gEBI("patron_city").value + "]]></City>";
	if(null != gEBI("patron_state"))
		strBA +=	"<State><![CDATA["+gEBI("patron_state").value+"]]></State>";
	if(null != gEBI("patron_zip"))
		strBA +=	"<ZIP><![CDATA[" + gEBI("patron_zip").value + "]]></ZIP>";
	if(null != gEBI("patron_country"))
		strBA +=	"<Country><![CDATA[" + gEBI("patron_country").value + "]]></Country>";
	if(null != gEBI("patron_region"))
		strBA +=	"<Region><![CDATA[" + gEBI("patron_region").value + "]]></Region>";
	if(null != gEBI("patron_phone"))
		strBA +=	"<Phone><![CDATA[" + gEBI("patron_phone").value + "]]></Phone>";
	if(null != gEBI("patron_email"))
		strBA +=	"<EMail><![CDATA[" + gEBI("patron_email").value + "]]></EMail>";
		
	strBA += "</BillingAddress>";
	
	return strBA;
}

function quicksale_dropdownchange(oSelect)
{
	//set cookie about current dropdown selection
	var cookieName = $(oSelect).attr("objtype");
	if(null == cookieName || "undefined" == typeof(cookieName) || "" == cookieName)
		return false;
	
	var cookieVal = $(oSelect).val();
	if(null == cookieVal || "undefined" == typeof(cookieVal) || "" == cookieVal)
		return false;
		
	//set cookie
	SetCookie(cookieName, cookieVal);
	
	return false;
}

function ConfirmHoldtoCart(strWhichButtonToClickId, strDlgId)
{
	$("#" + strDlgId).dialog("close");
	$("#" + strDlgId).hide();
	
	ShowProgressbar();
	
	var strButtonId = $("#" + strWhichButtonToClickId).val();
	
	$("#" + strButtonId).click();
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function OpenSignatureForm(tid, sTargetId) {
    if (tid != null && tid != '0') {
        jQuery.facebox({ ajax: 'SignatureRead.aspx?tid=' + tid + '&rnd=' + Math.random() });
    }
    else {
        jQuery.facebox({ ajax: 'SignatureRead.aspx?target=' + sTargetId + '&rnd=' + Math.random() });
    }

    return false;
} 
 //called from orderactivity.aspx, orderdetails.aspx

function PrintOrder(nID)
{
	if(typeof(gClientObj) == "undefined")
	{
		alert("ERROR - gClientObj not found")
		return false;
	}
	
	if(arguments[7] != null) 
		gClientId=arguments[7];
		
	if(arguments[6] == null || arguments[6] == false && arguments[8]==null)
	{
		//check if order is paid for
		var fPayTotal = 0;
		var fOrderTotal = 0;
		if(gEBI("LookupPaymentTotal") != null)
			fPayTotal = parseFloat(gEBI("LookupPaymentTotal").value);
		if(gEBI("LookupOrderTotal") != null)
			fOrderTotal = parseFloat(gEBI("LookupOrderTotal").value);

		if(fPayTotal < fOrderTotal)
		{
			alert("You cannot print tickets for orders that have a balance due.")
			return false;
		}
	}
	
	var ticketId = arguments[2];
	var trxId = arguments[5];
	var CouponId=0;
	if(arguments[8] != null) 
		CouponId=arguments[8];
	var CouponRec = 0;
	if(arguments[4] != null) 
		CouponRec = 1;
	
	
	var sOrderId = nID;
	
	var strXML = "<Envelope><Body><Orders id='" + nID + "'>" + nID + "</Orders>";
	if (arguments[1]==1){							//print single ticket in order
		strXML += "<SingleTicket>1</SingleTicket>";
	}else if (arguments[1]==2){						//print all tickets in order
		strXML += "<SingleTicket>0</SingleTicket>";
	}
	if (null!=ticketId)
	{
		strXML += "<TicketId>" + ticketId + "</TicketId>";
	}
	if (null!=arguments[3])
	{
		strXML += "<CouponPrint>1</CouponPrint>";
	}else{
		strXML += "<CouponPrint>0</CouponPrint>";
	}
	if (CouponRec > 0)
	{
		strXML += "<CouponPrintReceipt>1</CouponPrintReceipt>";
	}else{
		strXML += "<CouponPrintReceipt>0</CouponPrintReceipt>";
	}
	strXML += "</Body></Envelope>";
	
	/*
		FGL = 0,
		NewFGL = 1,
		HTMLPrintCarpenter = 2,
		HTMLPrint = 3
	*/
	
	var sFullUrl = "";
	
	switch(gClientObj.PrintingType)
	{
		case 0:
			if (ticketId==null)
			{
				sFullUrl="TicketPrinterFgl.aspx?ticketid=" + 0 +"&new=0&couponId="+CouponId;
			}
			else 
			{
				sFullUrl="TicketPrinterFgl.aspx?orderid="+sOrderId; 	
				sFullUrl+="&ticketid="+ticketId;	
			}
			if(trxId != null)
				sFullUrl += "&trx=" + trxId;
			
			
			var strResp = top.sendXmlHttpRequest(sFullUrl, strXML);
			
			var oWin = window.open("about.html", "_blank","menubar=no,status=yes,location=no,scrollbars=yes,titlebar=yes,top=0,left=0,height=710,width=1015,directories=no");
			oWin.document.write(strResp);
			//oWin.checkclose();
			oWin.location.reload();
			return false;
		case 1:
			if(null!=gEBI("inpOrderPrintURL"))
			{
				sFullUrl = gEBI("inpOrderPrintURL").value;
				if (null != ticketId)
				{
					sFullUrl = sFullUrl.replace("&hTicketId=", "&hTicketId=" + ticketId)
				}
				if (null != trxId)
				{
					sFullUrl = sFullUrl.replace("&hTransactionId=", "&hTransactionId=" + trxId)
				}
				if (CouponId > 0 && 0 == CouponRec)
				{
					sFullUrl = sFullUrl.replace("&hCouponId=", "&hCouponId=" + CouponId)
				}
				if (CouponId > 0 && 0 != CouponRec)
				{
					sFullUrl = sFullUrl.replace("&hCouponIdRec=", "&hCouponIdRec=" + CouponId)
				}
				
				window.location = sFullUrl;
			}
			return false;
		case 2:
			sFullUrl+="TempTicketPrintCarp.aspx?orderid=" + nID;	
			if (null != ticketId)
			{
				sFullUrl = sFullUrl + "&tid=" + ticketId;
			}
			if (null != trxId)
			{
				sFullUrl = sFullUrl + "&rcpt=" + trxId;
			}
			window.open(sFullUrl);
			return false;
		case 3:
			window.open("TempTicketPrint.aspx?orderid=" + nID);
			return false;
	}
	
	return false;
}

/*
arguments[0] - orderId
arguments[1] - tranId
arguments[2] - ticketId
*/
function DoQuickPrintNewWay(nID)
{
	var sOrderId = String(nID);
	sOrderId = sOrderId.replace('\n', '');
	sOrderId = sOrderId.replace('\r', '');
	
	var sFullUrl = "";
	
	var trxId = arguments[1];
	var ticketId = arguments[2];
	
	//try to print tickets based on PrintingType rather than clientId
	if(typeof(gClientObj) != "undefined")
	{
		/*
			FGL = 0,
			NewFGL = 1,
			HTMLPrintCarpenter = 2,
			HTMLPrint = 3
		*/
		
		switch(gClientObj.PrintingType)
		{
			case 0:
				if (ticketId==null)
				{
					sFullUrl="TicketPrinterFgl.aspx?orderid="+sOrderId+"&unprintedOnly=1&new=1&ticketid=0&whereRedirect=2&isFrame=1";
				}
				else 
				{
					sFullUrl="TicketPrinterFgl.aspx?orderid="+sOrderId; 	
					sFullUrl+="&ticketid="+ticketId;	
				}
				sFullUrl+="&opt=2";
				
				if(null != trxId)	
					sFullUrl += "&trx=" + trxId;
				
				if (null!=gEBI("frPrintFgl") )
				{
					gEBI("tdfrPrintFgl").style.display='block';
					gEBI("frPrintFgl").src=sFullUrl;
				}
				return;
			case 1:
				if(null!=gEBI("inpOrderPrintURL"))
				{
					sFullUrl = gEBI("inpOrderPrintURL").value;
					if (null != ticketId)
					{
						sFullUrl = sFullUrl.replace("&hTicketId=", "&hTicketId=" + ticketId)
					}
					if (null != trxId)
					{
						sFullUrl = sFullUrl.replace("&hTransactionId=", "&hTransactionId=" + trxId)
					}
					
					if (null!=gEBI("frPrintFgl") )
					{
						gEBI("tdfrPrintFgl").style.display='block';
						gEBI("frPrintFgl").src=sFullUrl;
					}
				}
				return;
			case 2:
				sFullUrl+="TempTicketPrintCarp.aspx?orderid=" + nID;	
				if (null != ticketId)
				{
					sFullUrl = sFullUrl + "&tid=" + ticketId;
				}
				if (null != trxId)
				{
					sFullUrl = sFullUrl + "&rcpt=" + trxId;
				}
				window.open(sFullUrl);
				return;
			case 3:
				window.open("TempTicketPrint.aspx?orderid=" + nID);
				return;
		}
	}
	
	alert("ERROR - gClientObj not found")
	return;
	//normally code should not get here
}

function OpenCashDrawer(){
	var sFullUrl = "tks:cashDraw=1";

	if (null!=gEBI("frPrintFgl") )
	{
		gEBI("tdfrPrintFgl").style.display='block';
		gEBI("frPrintFgl").src=sFullUrl;
	}
} 
 /*
Script: JSON.js

JSON encoder / decoder:	
	This object uses good practices to encode/decode quikly and a bit safer(*) every kind of JSON compatible variable.
	
	(*) Please read more about JSON and Ajax JavaScript Hijacking problems, <http://www.fortifysoftware.com/advisory.jsp>
	
	To download last version of this script use this link: <http://www.devpro.it/code/149.html>

Version:
	1.3b - modified toDate method, now compatible with milliseconds time too (time or milliseconds/1000)

Compatibility:
	FireFox - Version 1, 1.5, 2 and 3 (FireFox uses secure code evaluation)
	Internet Explorer - Version 5, 5.5, 6 and 7
	Opera - 8 and 9 (probably 7 too)
	Safari - Version 2 (probably 1 too)
	Konqueror - Version 3 or greater

Dependencies:
	<JSONError.js>

Credits:
	- JSON site for safe RegExp and generic JSON informations, <http://www.json.org/>
	- kenta for safe evaluation idea, <http://mykenta.blogspot.com/>

Author:
	Andrea Giammarchi, <http://www.3site.eu>

License:
	>Copyright (C) 2007 Andrea Giammarchi - www.3site.eu
	>	
	>Permission is hereby granted, free of charge,
	>to any person obtaining a copy of this software and associated
	>documentation files (the "Software"),
	>to deal in the Software without restriction,
	>including without limitation the rights to use, copy, modify, merge,
	>publish, distribute, sublicense, and/or sell copies of the Software,
	>and to permit persons to whom the Software is furnished to do so,
	>subject to the following conditions:
	>
	>The above copyright notice and this permission notice shall be included
	>in all copies or substantial portions of the Software.
	>
	>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
	>INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	>IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	>DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
	>ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
	>OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*
Object: JSON
	Stand alone or prototyped encode, decode or toDate public methods.

Example:
	>alert(JSON.encode([0,1,false,true,null,[2,3],{"some":"value"}]));
	>// [0,1,false,true,null,[2,3],{"some":"value"}]
	>
	>alert(JSON.decode('[0,1,false,true,null,[2,3],{"some":"value"}]'))
	>// 0,1,false,true,,2,3,[object Object]
*/
JSON = new function() {

    /* Section: Methods - Public */

    /*
    Method: decode
    decodes a valid JSON encoded string.
	
	Arguments:
    [String / Function] - Optional JSON string to decode or a filter function if method is a String prototype.
    [Function] - Optional filter function if first argument is a JSON string and this method is not a String prototype.
	
	Returns:
    Object - Generic JavaScript variable or undefined
	
	Example [Basic]:
    >var	arr = JSON.decode('[1,2,3]');
    >alert(arr);	// 1,2,3
    >
    >arr = JSON.decode('[1,2,3]', function(key, value){return key * value});
    >alert(arr);	// 0,2,6
	
	Example [Prototype]:
    >String.prototype.parseJSON = JSON.decode;
    >
    >alert('[1,2,3]'.parseJSON());	// 1,2,3
    >
    >try {
    >	alert('[1,2,3]'.parseJSON(function(key, value){return key * value}));
    >	// 0,2,6
    >}
    >catch(e) {
    >	alert(e.message);
    >}
	
	Note:
    Internet Explorer 5 and other old browsers should use a different regular expression to check if a JSON string is valid or not.
    This old browsers dedicated RegExp is not safe as native version is but it required for compatibility.
    */
    this.decode = function() {
        var filter, result, self, tmp;
        if ($$("toString")) {
            switch (arguments.length) {
                case 2:
                    self = arguments[0];
                    filter = arguments[1];
                    break;
                case 1:
                    if ($[typeof arguments[0]](arguments[0]) === Function) {
                        self = this;
                        filter = arguments[0];
                    }
                    else
                        self = arguments[0];
                    break;
                default:
                    self = this;
                    break;
            };
            if (rc.test(self)) {
                try {
                    result = e("(".concat(self, ")"));
                    if (filter && result !== null && (tmp = $[typeof result](result)) && (tmp === Array || tmp === Object)) {
                        for (self in result)
                            result[self] = v(self, result) ? filter(self, result[self]) : result[self];
                    }
                }
                catch (z) { }
            }
            else {
                return "";
                //throw new JSONError("bad data");
            }
        };
        return result;
    };

    /*
    Method: encode
    encode a generic JavaScript variable into a valid JSON string.
	
	Arguments:
    [Object] - Optional generic JavaScript variable to encode if method is not an Object prototype.
	
	Returns:
    String - Valid JSON string or undefined
	
	Example [Basic]:
    >var	s = JSON.encode([1,2,3]);
    >alert(s);	// [1,2,3]
	
	Example [Prototype]:
    >Object.prototype.toJSONString = JSON.encode;
    >
    >alert([1,2,3].toJSONString());	// [1,2,3]
    */
    this.encode = function() {
        var self = arguments.length ? arguments[0] : this,
			result, tmp;
        if (self === null)
            result = "null";
        else if (self !== undefined && (tmp = $[typeof self](self))) {
            switch (tmp) {
                case Array:
                    result = [];
                    for (var i = 0, j = 0, k = self.length; j < k; j++) {
                        if (self[j] !== undefined && (tmp = JSON.encode(self[j])))
                            result[i++] = tmp;
                    };
                    result = "[".concat(result.join(","), "]");
                    break;
                case Boolean:
                    result = String(self);
                    break;
                case Date:
                    result = '"'.concat(self.getFullYear(), '-', d(self.getMonth() + 1), '-', d(self.getDate()), 'T', d(self.getHours()), ':', d(self.getMinutes()), ':', d(self.getSeconds()), '"');
                    break;
                case Function:
                    break;
                case Number:
                    result = isFinite(self) ? String(self) : "null";
                    break;
                case String:
                    result = '"'.concat(self.replace(rs, s).replace(ru, u), '"');
                    break;
                default:
                    var i = 0, key;
                    result = [];
                    for (key in self) {
                        if (self[key] !== undefined && (tmp = JSON.encode(self[key])))
                            result[i++] = '"'.concat(key.replace(rs, s).replace(ru, u), '":', tmp);
                    };
                    result = "{".concat(result.join(","), "}");
                    break;
            }
        };
        return result;
    };

    /*
    Method: toDate
    transforms a JSON encoded Date string into a native Date object.
	
	Arguments:
    [String/Number] - Optional JSON Date string or server time if this method is not a String prototype. Server time should be an integer, based on seconds since 1970/01/01 or milliseconds / 1000 since 1970/01/01.
	
	Returns:
    Date - Date object or undefined if string is not a valid Date
	
	Example [Basic]:
    >var	serverDate = JSON.toDate("2007-04-05T08:36:46");
    >alert(serverDate.getMonth());	// 3 (months start from 0)
	
	Example [Prototype]:
    >String.prototype.parseDate = JSON.toDate;
    >
    >alert("2007-04-05T08:36:46".parseDate().getDate());	// 5
	
	Example [Server Time]:
    >var	phpServerDate = JSON.toDate(<?php echo time(); ?>);
    >var	csServerDate = JSON.toDate(<%=(DateTime.Now.Ticks/10000-62135596800000)%>/1000);
	
	Example [Server Time Prototype]:
    >Number.prototype.parseDate = JSON.toDate;
    >var	phpServerDate = (<?php echo time(); ?>).parseDate();
    >var	csServerDate = (<%=(DateTime.Now.Ticks/10000-62135596800000)%>/1000).parseDate();
	
	Note:
    This method accepts an integer or numeric string too to mantain compatibility with generic server side time() function.
    You can convert quickly mtime, ctime, time and other time based values.
    With languages that supports milliseconds you can send total milliseconds / 1000 (time is set as time * 1000)
    */
    this.toDate = function() {
        var self = arguments.length ? arguments[0] : this,
			result;
        if (rd.test(self)) {
            result = new Date;
            result.setHours(i(self, 11, 2));
            result.setMinutes(i(self, 14, 2));
            result.setSeconds(i(self, 17, 2));
            result.setMonth(i(self, 5, 2) - 1);
            result.setDate(i(self, 8, 2));
            result.setFullYear(i(self, 0, 4));
        }
        else if (rt.test(self))
            result = new Date(self * 1000);
        return result;
    };

    /* Section: Properties - Private */

    /*
    Property: Private
	
	List:
    Object - 'c' - a dictionary with useful keys / values for fast encode convertion
    Function - 'd' - returns decimal string rappresentation of a number ("14", "03", etc)
    Function - 'e' - safe and native code evaulation
    Function - 'i' - returns integer from string ("01" => 1, "15" => 15, etc)
    Array - 'p' - a list with different "0" strings for fast special chars escape convertion
    RegExp - 'rc' - regular expression to check JSON strings (different for IE5 or old browsers and new one)
    RegExp - 'rd' - regular expression to check a JSON Date string
    RegExp - 'rs' - regular expression to check string chars to modify using c (char) values
    RegExp - 'rt' - regular expression to check integer numeric string (for toDate time version evaluation)
    RegExp - 'ru' - regular expression to check string chars to escape using "\u" prefix
    Function - 's' - returns escaped string adding "\\" char as prefix ("\\" => "\\\\", etc.)
    Function - 'u' - returns escaped string, modifyng special chars using "\uNNNN" notation
    Function - 'v' - returns boolean value to skip object methods or prototyped parameters (length, others), used for optional decode filter function
    Function - '$' - returns object constructor if it was not cracked (someVar = {}; someVar.constructor = String <= ignore them)
    Function - '$$' - returns boolean value to check native Array and Object constructors before convertion
    */
    var c = { "\b": "b", "\t": "t", "\n": "n", "\f": "f", "\r": "r", '"': '"', "\\": "\\", "/": "/" },
		d = function(n) { return n < 10 ? "0".concat(n) : n },
		e = function(c, f, e) { e = eval; delete eval; if (typeof eval === "undefined") eval = e; f = eval("" + c); eval = e; return f },
		i = function(e, p, l) { return 1 * e.substr(p, l) },
		p = ["", "000", "00", "0", ""],
		rc = null,
		rd = /^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/,
		rs = /(\x5c|\x2F|\x22|[\x0c-\x0d]|[\x08-\x0a])/g,
		rt = /^([0-9]+|[0-9]+[,\.][0-9]{1,3})$/,
		ru = /([\x00-\x07]|\x0b|[\x0e-\x1f])/g,
		s = function(i, d) { return "\\".concat(c[d]) },
		u = function(i, d) {
		    var n = d.charCodeAt(0).toString(16);
		    return "\\u".concat(p[n.length], n)
		},
		v = function(k, v) { return $[typeof result](result) !== Function && (v.hasOwnProperty ? v.hasOwnProperty(k) : v.constructor.prototype[k] !== v[k]) },
		$ = {
		    "boolean": function() { return Boolean },
		    "function": function() { return Function },
		    "number": function() { return Number },
		    "object": function(o) { return o instanceof o.constructor ? o.constructor : null },
		    "string": function() { return String },
		    "undefined": function() { return null }
		},
		$$ = function(m) {
		    function $(c, t) { t = c[m]; delete c[m]; try { e(c) } catch (z) { c[m] = t; return 1 } };
		    return $(Array) && $(Object)
		};
    try { rc = new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$') }
    catch (z) { rc = /^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/ }
};
 
 // /////////////////////////////////////////////////////////////////////////////////
// JavaScript Magstripe (track 1, track2) data parser object
//
// Mar-22-2005	Modified by Wayne Walrath,
//				Acme Technologies http://www.acmetech.com
//			based on demo source code from www.skipjack.com
//
// USAGE:
// var p = new SwipeParserObj();
// p.dump();  -- returns parsed field values and meta info.
//	-- or --
// get individual field names (see member variables at top of object)
//
// if( p.hasTrack1 ){
//		p.surname;
//		p.firstname;
//		p.account;
//		p.exp_month + "/" + p.exp_year;
//	}
///////////////////////////////////////////////////////////////////////////////////

function SwipeParserObj(strParse)
{
	///////////////////////////////////////////////////////////////
	///////////////////// member variables ////////////////////////
	this.input_trackdata_str = strParse;
	this.account_name = null;
	this.surname = null;
	this.firstname = null;
	this.account = null;
	this.exp_month = null;
	this.exp_year = null;
	this.track1 = null;
	this.track2 = null;
	this.hasTrack1 = false;
	this.hasTrack2 = false;
	/////////////////////////// end member fields /////////////////
	
	
	sTrackData = this.input_trackdata_str;     //--- Get the track data
	
  //-- Example: Track 1 & 2 Data
  //-- %B1234123412341234^CardUser/John^030510100000019301000000877000000?;1234123412341234=0305101193010877?
  //-- Key off of the presence of "^" and "="

  //-- Example: Track 1 Data Only
  //-- B1234123412341234^CardUser/John^030510100000019301000000877000000?
  //-- Key off of the presence of "^" but not "="

  //-- Example: Track 2 Data Only
  //-- 1234123412341234=0305101193010877?
  //-- Key off of the presence of "=" but not "^"

  if ( strParse != '' )
  {
    // alert(strParse);

    //--- Determine the presence of special characters
    nHasTrack1 = strParse.indexOf("^");
    nHasTrack2 = strParse.indexOf("=");

    //--- Set boolean values based off of character presence
    this.hasTrack1 = bHasTrack1 = false;
    this.hasTrack2 = bHasTrack2 = false;
    if (nHasTrack1 > 0) { this.hasTrack1 = bHasTrack1 = true; }
    if (nHasTrack2 > 0) { this.hasTrack2 = bHasTrack2 = true; }

    //--- Test messages
    // alert('nHasTrack1: ' + nHasTrack1 + ' nHasTrack2: ' + nHasTrack2);
    // alert('bHasTrack1: ' + bHasTrack1 + ' bHasTrack2: ' + bHasTrack2);    

    //--- Initialize
    bTrack1_2  = false;
    bTrack1    = false;
    bTrack2    = false;

    //--- Determine tracks present
    if (( bHasTrack1) && ( bHasTrack2)) { bTrack1_2 = true; }
    if (( bHasTrack1) && (!bHasTrack2)) { bTrack1   = true; }
    if ((!bHasTrack1) && ( bHasTrack2)) { bTrack2   = true; }

    //--- Test messages
    // alert('bTrack1_2: ' + bTrack1_2 + ' bTrack1: ' + bTrack1 + ' bTrack2: ' + bTrack2);

    //--- Initialize alert message on error
    bShowAlert = false;
    
    //-----------------------------------------------------------------------------    
    //--- Track 1 & 2 cards
    //--- Ex: B1234123412341234^CardUser/John^191110100000019301000000877000000?;1234123412341234=0305101193010877?
    //-----------------------------------------------------------------------------    
    if (bTrack1_2)
    { 
//      alert('Track 1 & 2 swipe');

      strCutUpSwipe = '' + strParse + ' ';
      arrayStrSwipe = new Array(4);
      arrayStrSwipe = strCutUpSwipe.split("^");
  
      var sAccountNumber, sName, sShipToName, sMonth, sYear;
  
      if ( arrayStrSwipe.length > 2 )
      {
        this.account = stripAlpha( arrayStrSwipe[0].substring(1,arrayStrSwipe[0].length) );
        this.account_name          = arrayStrSwipe[1];
        this.exp_month         = arrayStrSwipe[2].substring(2,4);
        this.exp_year          = arrayStrSwipe[2].substring(0,2); 
        
        //--- Different card swipe readers include or exclude the % in the front of the track data - when it's there, there are
        //---   problems with parsing on the part of credit cards processor - so strip it off
        if ( sTrackData.substring(0,1) == '%' ) {
        	sTrackData = sTrackData.substring(1,sTrackData.length);
        }

       	var track2sentinel = sTrackData.indexOf(";");
       	if( track2sentinel != -1 ){
       		this.track1 = sTrackData.substring(0, track2sentinel);
       		this.track2 = sTrackData.substring(track2sentinel);
       	}

		//--- parse name field into first/last names
		var nameDelim = this.account_name.indexOf("/");
		if( nameDelim != -1 ){
			this.surname = this.account_name.substring(0, nameDelim);
			this.firstname = this.account_name.substring(nameDelim+1);
		}
      }
      else  //--- for "if ( arrayStrSwipe.length > 2 )"
      { 
        bShowAlert = true;  //--- Error -- show alert message
      }
    }
    
    //-----------------------------------------------------------------------------
    //--- Track 1 only cards
    //--- Ex: B1234123412341234^CardUser/John^191110100000019301000000877000000?
    //-----------------------------------------------------------------------------    
    if (bTrack1)
    {
//      alert('Track 1 swipe');

      strCutUpSwipe = '' + strParse + ' ';
      arrayStrSwipe = new Array(4);
      arrayStrSwipe = strCutUpSwipe.split("^");
  
      var sAccountNumber, sName, sShipToName, sMonth, sYear;
  
      if ( arrayStrSwipe.length > 2 )
      {
        this.account = sAccountNumber = stripAlpha( arrayStrSwipe[0].substring( 1,arrayStrSwipe[0].length) );
        this.account_name = sName	= arrayStrSwipe[1];
        this.exp_month = sMonth	= arrayStrSwipe[2].substring(2,4);
        this.exp_year = sYear	= arrayStrSwipe[2].substring(0,2); 
  
        
        //--- Different card swipe readers include or exclude the % in
        //--- the front of the track data - when it's there, there are
        //---   problems with parsing on the part of credit cards processor - so strip it off
        if ( sTrackData.substring(0,1) == '%' ) { 
        	this.track1 = sTrackData = sTrackData.substring(1,sTrackData.length);
        }
  
        //--- Add track 2 data to the string for processing reasons
//        if (sTrackData.substring(sTrackData.length-1,1) != '?')  //--- Add a ? if not present
//        { sTrackData = sTrackData + '?'; }
		this.track2 = ';' + sAccountNumber + '=' + sYear.substring(2,4) + sMonth + '111111111111?';
        sTrackData = sTrackData + this.track2;
  
		//--- parse name field into first/last names
		var nameDelim = this.account_name.indexOf("/");
		if( nameDelim != -1 ){
			this.surname = this.account_name.substring(0, nameDelim);
			this.firstname = this.account_name.substring(nameDelim+1);
		}
		
		//if we still do not have first and last names, try o parse for the space???
		if(null == this.surname || "" == this.surname)
		{
			nameDelim = this.account_name.indexOf(" ");
			if( nameDelim != -1 ){
				this.surname = this.account_name.substring(0, nameDelim);
				this.firstname = this.account_name.substring(nameDelim+1);
			}
			
			if(null == this.surname || "" == this.surname)
			{
				this.surname = this.account_name;
			}
			
			if((null == this.firstname || "" == this.firstname) && null != this.surname)
			{
				nameDelim = this.surname.indexOf(" ");
				if( nameDelim != -1 ){
					this.firstname = this.surname.substring(nameDelim+1);
					this.surname = this.surname.substring(0, nameDelim);
				}
			}
		}
      }
      else  //--- for "if ( arrayStrSwipe.length > 2 )"
      { 
        bShowAlert = true;  //--- Error -- show alert message
      }
    }
    
    //-----------------------------------------------------------------------------
    //--- Track 2 only cards
    //--- Ex: 1234123412341234=0305101193010877?
    //-----------------------------------------------------------------------------    
    if (bTrack2)
    {
//      alert('Track 2 swipe');
    
      nSeperator  = strParse.indexOf("=");
      sCardNumber = strParse.substring(1,nSeperator);
      sYear       = strParse.substr(nSeperator+1,2);
      sMonth      = strParse.substr(nSeperator+3,2);

      // alert(sCardNumber + ' -- ' + sMonth + '/' + sYear);

      this.account = sAccountNumber = stripAlpha(sCardNumber);
      this.exp_month = sMonth		= sMonth;
      this.exp_year = sYear			= sYear; 
        
      //--- Different card swipe readers include or exclude the % in the front of the track data - when it's there, 
      //---  there are problems with parsing on the part of credit cards processor - so strip it off
      if ( sTrackData.substring(0,1) == '%' ) {
		sTrackData = sTrackData.substring(1,sTrackData.length);
      }
  
    }
    
    //-----------------------------------------------------------------------------
    //--- No Track Match
    //-----------------------------------------------------------------------------    
    if (((!bTrack1_2) && (!bTrack1) && (!bTrack2)) || (bShowAlert))
    {
      //alert('Difficulty Reading Card Information.\n\nPlease Swipe Card Again.');
    }

//    alert('Track Data: ' + document.formFinal.trackdata.value);
    
    //document.formFinal.trackdata.value = replaceChars(document.formFinal.trackdata.value,';','');
    //document.formFinal.trackdata.value = replaceChars(document.formFinal.trackdata.value,'?','');

//    alert('Track Data: ' + document.formFinal.trackdata.value);

  } //--- end "if ( strParse != '' )"


	this.dump = function(){
		var s = "";
		var sep = "\r\n"; // line separator
		s += "Name: " + this.account_name + sep;
		s += "Surname: " + this.surname + sep;
		s += "first name: " + this.firstname + sep;
		s += "account: " + this.account + sep;
		s += "exp_month: " + this.exp_month + sep;
		s += "exp_year: " + this.exp_year + sep;
		s += "has track1: " + this.hasTrack1 + sep;
		s += "has track2: " + this.hasTrack2 + sep;
		s += "TRACK 1: " + this.track1 + sep;
		s += "TRACK 2: " + this.track2 + sep;
		s += "Raw Input Str: " + this.input_trackdata_str + sep;
		
		return s;
	}

	function stripAlpha(sInput){
		if( sInput == null )	return '';
		return sInput.replace(/[^0-9]/g, '');
	}

}

var gbCheckLoopActive = false;
function startCheckLoop(i) {
	var oCardReader = gEBI("TrackData" + i);
	if(null == oCardReader)
		return;
	
  	oCardReader.value = "";
  	oCardReader.style.color = "00cc00";
  	oCardReader.style.backgroundColor = "00cc00";
  	gbCheckLoopActive = true;
  	
  	setTimeout(function(){checkReaderInput(i)}, 800);
  }
function endCheckLoop(i) {
	var oCardReader = gEBI("TrackData" + i);
	if(null == oCardReader)
		return;
	
  	oCardReader.style.color = "cc0000";
  	oCardReader.style.backgroundColor = "cc0000";
  	gbCheckLoopActive = false;
  }
  
function checkReaderInput(i) {
	var oCardReader = gEBI("TrackData" + i);
	if(null == oCardReader)
		return;
	
  	var sVal = oCardReader.value;
  	if (sVal.length > 0 && sVal.lastIndexOf("?") > -1) {
  		setTimeout(function(){extract(oCardReader.value, i)}, 800);
  	}
  	
  	if (gbCheckLoopActive) 
  		setTimeout(function(){checkReaderInput(i)}, 800);
  }
  
  function extract(trackdata, payindex) {
	var oCCwasSwiped = gEBI("CCwasSwiped" + payindex);
	if(oCCwasSwiped!= null)
	{
		oCCwasSwiped.value = "true";
	}
	
  	var td = String(trackdata);
  	
  	var p = new SwipeParserObj(td);
  	//alert(p.dump());
  	
  	var sCardNum = "";
  	if(null != p.account)
  	{
  		sCardNum = p.account;
  		gEBI("pay_" + payindex + "_cardnumber").value = sCardNum;
  	}
  	var fname = "";
  	if(null != p.firstname)
  	{
  		fname = Trim(p.firstname);
  		gEBI("pay_" + payindex + "_firstname").value = fname;
  	}
  	var lname = "";
  	if(null != p.surname)
  	{
  		lname = Trim(p.surname);
  		gEBI("pay_" + payindex + "_lastname").value = lname;
  	}
  	
  	var expmonth = "";
  	if(null != p.exp_month)
  	{
  		expmonth = p.exp_month;
  		ChangeSelectByValue(gEBI("pay_" + payindex + "_expmo"), expmonth);
  	}
  	var expyear = "";
  	if(expyear != p.exp_year)
  	{
  		expyear = p.exp_year;
  		ChangeSelectByValue(gEBI("pay_" + payindex + "_expyr"), expyear);
  	}
	
	/*try to set cart fields as well if theyre not already set*/
	if(null != gEBI("patron_firstname1") && Trim(gEBI("patron_firstname1").value) == '' )
		gEBI("patron_firstname1").value = fname
	if(null != gEBI("patron_lastname1") && Trim(gEBI("patron_lastname1").value) == '')
		gEBI("patron_lastname1").value = lname

	setCardType(payindex);
	gEBI("pay_" + payindex + "_cvvnumber").focus();
  }

function setCardType(payindex) {
	var cardtype = 1; //visa
	var cardNum = gEBI("pay_" + payindex + "_cardnumber").value.replace(/\s/g,'');
	if (cardNum.length > 2) {
		if (cardNum.substring(0,1) == '4') { cardtype=1; }
		if ((cardNum.substring(0,2) == '34') || (cardNum.substring(0,2)=='37')) { cardtype = 4; }
		if ((cardNum.substring(0,2) > 50) && (cardNum.substring(0,2)<56)) { cardtype = 2; }
		if (cardNum.substring(0,4) == '6011') { cardtype = 3; }
	}
	
	ChangeSelectByValue(gEBI("pay_"+payindex+"_cardtype"), cardtype);
}

function doSwipe(i) {
	payindex = i;
	var oCardReader = gEBI("TrackData" + i);
  	try
  	{
		oCardReader.focus();
	}
	catch(e)
	{
	}
}
//end credit card swipe

//Handles blue dropdown images, apply all discounts to the cart, all tickettypes to the cart
function OnCartFillDiscounts(oImg)
{
	OnCartApplyGeneric(oImg, "extradiscount_td");
}
function OnCartFillTicketTypes(oImg)
{
	OnCartApplyGeneric(oImg, "tickettype_td");
}
function OnCartApplyGeneric(oImg, ApplyTo)
{

	GenericIdToApply = oImg.previousSibling.previousSibling.options[oImg.previousSibling.previousSibling.selectedIndex].innerHTML;
	oParentRow = getParentNodeByTagName(oImg,"TR")
	oParentTable = getParentNodeByTagName(oParentRow,"TABLE")
	oTicketRows = getChildrenByPartialIdOrName(oParentTable, "trTicket_", true)

	var strTicketsXML = "";
	var oTTSelect;
	var start = parseInt(oParentRow.id.replace("trTicket_",""));
	
	gUpdateTotals=false;
	try
	{	
		for(var i=start+1;i<oTicketRows.length;i++)
		{
			var oTTtd = getChildByIdOrName(oTicketRows[i],ApplyTo, true);
			oTTSelect = getChildByTagName(oTTtd, "SELECT", true);
			ChangeSelectByValue(oTTSelect, GenericIdToApply, true);
			
			if(ApplyTo == "extradiscount_td") //build change extra discount or fee in session XML for multiple tickets
			{
				try{
					var tid = 	getChildrenByPartialIdOrName(oTicketRows[i], "h_TicketId", true)[0].value;
					var isGA = 	getChildrenByPartialIdOrName(oTicketRows[i], "h_TicketGA", true)[0].value;
					var ttSel = getChildByTagName(getChildByIdOrName(oTicketRows[i],"tickettype_td", true), "SELECT", true);
					var ttid = ttSel.value;
					var polid = ttSel.getAttribute("polid");
					var tagname = (oTTSelect.options[oTTSelect.selectedIndex].getAttribute('extraType')=='discount'?'ExtraDiscountId':'FeeId')
					strTicketsXML += "<Ticket>"+
					"<ID>" + tid + "</ID>"+
					"<GA>" + isGA + "</GA>"+
					"<TicketType><ID>" + ttid + "</ID></TicketType>"+	
					"<POLevel><ID>" + polid + "</ID></POLevel>"+	
					"<"+tagname+">" + oTTSelect.value + "</"+tagname+">" +
					"</Ticket>";
				}catch(e){}
			}
			else
			if(ApplyTo == "tickettype_td") //build change tickettype in session XML for multiple tickets
			{
				try{
					var tid = 	getChildrenByPartialIdOrName(oTicketRows[i], "h_TicketId", true)[0].value;
					strTicketsXML += "<Ticket>"+
					"<ID>" + tid + "</ID>"+
					"<GA>" + oTTSelect.getAttribute('IsGA') + "</GA>"+
					"<TicketType><ID>" + oTTSelect.options[oTTSelect.selectedIndex].getAttribute('TicketType') + "</ID></TicketType>"+	
					"<POLevel><ID>" + oTTSelect.getAttribute('PolID') + "</ID>"+		
					"<TicketPrices><TicketPrice><TicketType><ID>" + oTTSelect.getAttribute('prevtt') + "</ID></TicketType></TicketPrice></TicketPrices></POLevel>"+		
					"</Ticket>";
				}catch(e){}
			}
		}
	}
	catch(e){}

	try{
		var commandname	= "TryChangeTicketsType";
		//check for discount type to change command name
		if(ApplyTo == "extradiscount_td")
			commandname="TryChangeTicketsExtra" + (oTTSelect.options[oTTSelect.selectedIndex].getAttribute('extraType')=='discount'?'Discount':'Fee');	
		
		var strRequestXML = "<envelope><body><command name=\""+commandname+"\"><class name=\"CartProcessor\"/>"+
			"<param type=\"Tickets\"><ArrayOfTicket>"+
			strTicketsXML
			+
			"</ArrayOfTicket></param>"+
			"</command></body></envelope>";
		$.post(gSOAPListenerURL, strRequestXML);
	}catch(e){}
	
	gUpdateTotals=true;
	updateTotals();
}
//end apply all in cart


//zip code

function CheckAllowedZIP(oZipCodeInput) {
    var sEnteredZIP = $(oZipCodeInput).val();

    if (sEnteredZIP.length < 5)
        return;

    var zipToCheck = "," + sEnteredZIP.substr(0, 5) + ",";

    //go through deliverymethods and disable some
    var jqDelivMethodsDD = $("#" + $("#deliverymethodUniqueId").val());

    jqDelivMethodsDD.children().each(function (index) {
        //enable option by default
        $(this).attr("disabled", false);

        var zipCodes = $(this).attr("zipcodes");
        if ("undefined" == typeof (zipCodes))
            return;

        if (zipCodes.indexOf(zipToCheck) < 0) {
            $(this).attr("disabled", true);

            if ($(this).attr("selected")) {
                $(this).attr("selected", false);

                alert("We are sorry, but your zip code is not covered by this delivery method");
            }
        }
    });

}

function AutoFillCityState(oInput) {
    CheckAllowedZIP(oInput);

	if(gEBI("patron_city") != null && gEBI("patron_city").value != "")
		return;

    var oDiv = gEBI("divProgressBar");
    var oProgress = null;
	if(null != oDiv)
		oProgress = createBar(oDiv,100,10,'#ffffff',1,'#ffffff','#41D744',80,5,1,""); //xp_progress.js

	var oParams = { ClientId: gClientId, zipCode: oInput.value }
    var JSONparams = JSON.encode(oParams);
    
    //here we make AJAX call
    //call ajax
    $.ajax({
        type: "POST",
        url: "svc/svcGeo.aspx/CityStateDistanceByZIP",
        data: JSONparams,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus) {
            var oAddressData = eval(data);
			
			var oState = gEBI("selpatron_state");
			try{
				$("#patron_city").val(oAddressData.d.City);
				ChangeSelectByValue(oState, oAddressData.d.State);
				oState.onchange();
			}
			catch(e){}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            var oException = null;
            eval("oException = " + XMLHttpRequest.responseText);
            if (null != oException)
                if (typeof (oException.Message) != "undefined")
					alert(oException.Message);
        }
    });
    
    if(null != oProgress)
	{
		oProgress.togglePause();
		oProgress.hideBar();
	}
}
//end zip code

//This file is used for calculation various Shopping Cart Items. both for new and old sales

var arrDiscountIDs = new Array();
//This Object initializes tickets, subscriptions, seasontickets.
function Group(pTixQty,pBaseAmount){
	if("undefined" == typeof(pTixQty) || null == pTixQty)
		pTixQty = 1;
	pTixQty = parseInt(pTixQty);
	
	if("undefined" == typeof(pBaseAmount) || null == pBaseAmount)
		pBaseAmount = 0;
	pBaseAmount = parseFloat2(pBaseAmount);
	
	//members
	this.nTixQty = pTixQty;
	this.nBaseAmount = pBaseAmount;
	this.nPosition = 0;
	this.nCumulativeDiscountAmount = 0;
	this.nCumulativeFeeAmount = 0;
	this.nCumulativeHiddenFeeAmount = 0;	
	this.nDiscountAmountPerTicketGroup = 0;
	this.nFeeAmountPerTicketGroup = 0;
	this.Items =new Array();
	for(var i=0; i<this.nTixQty; i++)
	{
		this.Items[i] = new Object();
		this.Items[i].Discounts = new Array();
		this.Items[i].nDiscountAmount = 0;
		this.Items[i].Fees = new Array();
		this.Items[i].nFeeAmount = 0;
	}
	
	//methods 
	
	//private
	this.setFee = SetFee;
	this.setDiscount = SetDiscount;
	this.roundTo = RoundTo;

	//public
	this.calculateTicketExtra = CalculateTicketExtra;
	this.calculateTicketDiscountsAndFees = CalculateTicketDiscountsAndFees;
	this.buildFeeGroup = BuildFeeGroup;
	this.buildDiscountGroup = BuildDiscountGroup;
}

//private method
function SetFee(pFeeID, pDollarAmount, pPercentageAmount, pFeeCap, pFeeGroupId, pFeeGroupName, pCalculateAfterDiscounts, pRoundTo, pRoundingType, pHidden, pAboveOtherFees)
{
	if(pAboveOtherFees == null)
		pAboveOtherFees = "false";

	var lAppliedFlag = 0;
	for(var i=0; i<this.nTixQty; i++)
	{
		var lBaseAmount = this.nBaseAmount;
		if( "true"== pCalculateAfterDiscounts )
			lBaseAmount -= this.Items[i].nDiscountAmount;
		if( "true"== pAboveOtherFees.toLowerCase() )
			lBaseAmount += this.Items[i].nFeeAmount;
		
		var lFeeAmount = pDollarAmount + pPercentageAmount*lBaseAmount/100;
		
		if(null != pFeeCap && "" != pFeeCap && 0 != Number(pFeeCap) && lFeeAmount > Number(pFeeCap))
			lFeeAmount = pFeeCap;
			
		//apply rounding if necessary
		lFeeAmount = this.roundTo(lFeeAmount, pRoundTo, pRoundingType);

		if("true" == pHidden && lAppliedFlag==0)
		{
			this.nCumulativeHiddenFeeAmount += lFeeAmount;
			lAppliedFlag = 1;
		}
		else if(lAppliedFlag==0)//Once only for one fee
		{
			this.nCumulativeFeeAmount += lFeeAmount;
			this.nFeeAmountPerTicketGroup += lFeeAmount;
			lAppliedFlag = 1;
		}
		
		var lFee = new Object();
		lFee.ID = pFeeID;
		lFee.Amount = lFeeAmount;
		lFee.FeeGroupId = pFeeGroupId;
		lFee.FeeGroupName = pFeeGroupName;
		lFee.Hidden = pHidden;
		this.Items[i].Fees[ this.Items[i].Fees.length ] = lFee;
		this.Items[i].nFeeAmount += lFeeAmount;
		
	}
	return this;
}

//private method
function SetDiscount(pDiscountID, pDiscountAmount, pModifierCode, pDiscountGroupId, pDiscountGroupName, pFloor, pCeilling, pLimit,nTicketType,lActivationCode)
{
	//One Discount must be applied to one Ticket once only.
	if(pDiscountID == arrTkPerf[this.PerfId]["Ticket_"+this.nPosition+"Applied_"+pDiscountID])
		return this;
	
	//round discount amount to 1 cent
	pDiscountAmount = Number(pDiscountAmount.toFixed(2));
		
	var lAppliedFlag = 0;
   	for (var i=0;i<this.nTixQty;i++)
	{
	//alert(parseInt(arrTkPerf[this.PerfId].cntTickets));
	//alert(parseInt(arrTkPerTypes[this.PerfId+"tp_"+nTicketType]));
		if (	(pLimit==0 || 
						parseInt(pLimit)>parseInt(arrDiscountIDs[pDiscountID])) &&
				( pFloor==0 || pCeilling==0 || 
					(
					(null != nTicketType && "" != nTicketType && ( (parseInt(arrTkPerf[this.PerfId].cntTickets)-parseInt(arrTkPerTypes[this.PerfId+"tp_"+nTicketType])-this.nTixQty+i)%(pFloor+pCeilling) >= pFloor ))
					||( ((nTicketType==null || "" == nTicketType) && parseInt(arrTkPerf[this.PerfId].cntTickets)-this.nTixQty+i)%(pFloor+pCeilling)) >= pFloor )
					)
		)
		{
			if(lAppliedFlag==0)//Once only for one discount
			{
				lAppliedFlag = 1;
				this.nCumulativeDiscountAmount += pDiscountAmount;
				arrTkPerf[this.PerfId]["Ticket_"+this.nPosition+"Applied_"+pDiscountID] = pDiscountID;
			}
			
			this.nDiscountAmountPerTicketGroup += pDiscountAmount;

			var lDiscount = new Object();
				lDiscount.ID = pDiscountID;
				lDiscount.Amount = pDiscountAmount;
				lDiscount.modifierCode = pModifierCode;
				lDiscount.DiscountGroupId = pDiscountGroupId;
				lDiscount.DiscountGroupName = pDiscountGroupName;
				lDiscount.ActivationCode = lActivationCode;
			this.Items[i].Discounts[ this.Items[i].Discounts.length ] = lDiscount;
			this.Items[i].nDiscountAmount += pDiscountAmount;

			arrDiscountIDs[pDiscountID] =parseInt(arrDiscountIDs[pDiscountID])+1;
			arrTkPerf[this.PerfId]["discTkApplied_"+pDiscountID] =parseInt(arrTkPerf[this.PerfId]["discTkApplied_"+pDiscountID])+1;
		}
	}
	return this;
}

//private method
function RoundTo(nNumber, nFactor, RoundingType)
{
	if(nFactor <= 0)
		return nNumber;

//wanna have integers, not doubles
	if(RoundingType == "Up")
	{
		nNumber = Math.ceil(nNumber*100);
		nFactor = Math.ceil(nFactor*100);
	}
	else
	if(RoundingType == "Down")
	{
		nNumber = Math.floor(nNumber*100);
		nFactor = Math.floor(nFactor*100);
	}
	else
	{
		//check for float precision errors (xx.499999999)
		
		if(Math.abs((nNumber*100) % 1 - 0.5) < 0.000001) //checks if number is repeating .499999 and if so treats it like .5
			nNumber = Math.round(Math.ceil(nNumber*100));
		else
			nNumber = Math.round(nNumber*100);
		
		nFactor = Math.round(nFactor*100);
	}

	switch(RoundingType)
	{
		case "Up":
			nNumber = Math.ceil(nNumber/nFactor)*nFactor; //round up
			break;
		case "Down":
			nNumber = Math.floor(nNumber/nFactor)*nFactor; //round down
			break;
		case "Mathematical":
			nNumber = Math.round(nNumber/nFactor)*nFactor; //round math
			break;
		default:
		case "None":
			break;
	}

	nNumber = nNumber/100; //divide back
	return nNumber;
}

//public method
//used in GetTickets.js/updateTotals()
function CalculateTicketExtra(pTicketPosition)
{
	var lSelect = gEBI("selTicketExtra_"+pTicketPosition)
	if(null == lSelect) 
		return this;
		

	var lOption = lSelect.options[lSelect.selectedIndex];
	if(lOption.getAttribute("extraType")!="fee" && lOption.getAttribute("extraType")!="discount")
		return this;
	
	var lDollarAmount = parseFloat2(lOption.getAttribute("dollaramount"));
	var lPercentageAmount = parseFloat2(lOption.getAttribute("percentageamount"));

	if(null == lDollarAmount || "" == lDollarAmount || isNaN(lDollarAmount))
		lDollarAmount = 0;
	else
		lDollarAmount = Number(lDollarAmount);
		
	if(null == lPercentageAmount || "" == lPercentageAmount || isNaN(lPercentageAmount))
		lPercentageAmount = 0;
	else
		lPercentageAmount = Number(lPercentageAmount);

	if(lOption.getAttribute("extraType")=="fee")
		this.setFee(lOption.getAttribute("feeID"), lDollarAmount, lPercentageAmount, 0, lOption.getAttribute("FeeGroupId"), lOption.getAttribute("FeeGroupName"), "false", 0, "None");
	if(lOption.getAttribute("extraType")=="discount")
	{
		var lAmount = (lDollarAmount + lPercentageAmount*this.nBaseAmount/100);
		this.setDiscount(lOption.getAttribute('DiscountId'), lAmount, lOption.getAttribute('ModifierCode'), lOption.getAttribute("DiscountGroupId"), lOption.getAttribute("DiscountGroupName"), 0,0,0)
	}
}
//public method
//used in GetTickets.js/updateTotals()
function CalculateTicketDiscountsAndFees(oTkDiscount, hiddenInputName, oTicketTypeSelect, oDM, pSeasonPackageId)
{
	var orderDM_ID=0;
	if(oDM!=null)
	{
		if(oDM.selectedIndex >= 0)
		{
			var oOption = oDM.options[oDM.selectedIndex];
			orderDM_ID = oOption.value;
		}
	}
	
	//get other discounts
	var oNextTicketDiscount = oTkDiscount;
	var arrFeesID = new Array();
	
	//calculate total ticket count only once, not once per discount
	var lTotalTicketCount = 0;
    if(gEBI('trTicketColumns')!= null)
    {
		//get total ticket count for GA tix
		var oCountTicketRows = jQuery("table#tblCart input[name=txtTixQty]");
		for(var i=0;i<oCountTicketRows.length;i++)
			lTotalTicketCount += parseInt(oCountTicketRows[i].value);
			
		//add ticket count for reserved tix
		oCountTicketRows = jQuery("table#tblCart tr[name=trTicket]")
		for(var i=0;i<oCountTicketRows.length;i++)
			lTotalTicketCount++;		//increment once per row since reserved ticket rows awlays represent exactly one ticket
    } 
	
	do{
		oNextTicketDiscount = getNextSibling(oNextTicketDiscount);
		if(null == oNextTicketDiscount)
			break;

		if("INPUT" != oNextTicketDiscount.tagName)
			continue;
		if("hidden" != oNextTicketDiscount.type)
			continue;
		if(hiddenInputName != oNextTicketDiscount.name)
			continue;
		
		//at this point we are sure we got the correct input as fee id	
		var bHasPayment = false;  //flag, if the fee was applied as a result of payment type check
		var bHasDelivery = false;  //flag, if the fee was applied as a result of delivery method check
		
		var feeID = oNextTicketDiscount.getAttribute("feeID");
		if(null != arrFeesID[feeID])
			if(feeID == arrFeesID[feeID])
				continue;
				
		
		var nDollarAmount = parseFloat2(oNextTicketDiscount.getAttribute("dollaramount"));
		var nPercentageAmount = parseFloat2(oNextTicketDiscount.getAttribute("percentageamount"));
		
		if(null == nDollarAmount || "" == nDollarAmount || isNaN(nDollarAmount)) 
			nDollarAmount = 0;
		else 
			nDollarAmount = Number(nDollarAmount);
			
		if(null == nPercentageAmount || "" == nPercentageAmount || isNaN(nPercentageAmount)) 
			nPercentageAmount = 0;
		else 
			nPercentageAmount = Number(nPercentageAmount);
		
		var nPointAmount = oNextTicketDiscount.getAttribute("pointamount");
		
		var feeDM_ID = oNextTicketDiscount.getAttribute("DeliveryMethodId");
		var feePM_ID = oNextTicketDiscount.getAttribute("PaymenttypesClientId");
		var nTicketType = oNextTicketDiscount.getAttribute("tickettype");
		
		var sRoundingType = oNextTicketDiscount.getAttribute("roundingtype");
		if("" == sRoundingType || null == sRoundingType)
			sRoundingType = "None";
		var nRoundTo = parseFloat2(oNextTicketDiscount.getAttribute("roundto"));
		if("" == nRoundTo || null == nRoundTo || isNaN(nRoundTo))
			nRoundTo = 0;
		nRoundTo = Number(nRoundTo).toFixed(2);
		
		var nPriceFloor = 0;
		var nPriceCeiling = 0;
		if(null != oNextTicketDiscount.getAttribute("PriceFloor"))
			nPriceFloor = parseFloat2(oNextTicketDiscount.getAttribute("PriceFloor"));
		if(null != oNextTicketDiscount.getAttribute("PriceFloor"))
			nPriceCeiling = parseFloat2(oNextTicketDiscount.getAttribute("PriceCeiling"));
		//if(null == nTicketType || "" == nTicketType)
		{
			if(orderDM_ID == feeDM_ID || (Number(feeDM_ID) == 0 && Number(feePM_ID) == 0))
			{
				if((null == nTicketType || "" == nTicketType) && hiddenInputName == "fee" && (0 == nPriceCeiling || (nPriceFloor < this.nBaseAmount && this.nBaseAmount <= nPriceCeiling)))
				{
					arrFeesID[feeID] = feeID;
					bHasDelivery = true;
				}
				if(hiddenInputName == "discount" 
					&& ( null == oNextTicketDiscount.getAttribute("ActivationCode") || "" == oNextTicketDiscount.getAttribute("ActivationCode") 
						|| oNextTicketDiscount.getAttribute("ActivationCode").toUpperCase()==gEBI("txtDiscountActivationCode").value.toUpperCase())
				)
				{
					if(null != nTicketType && "" != nTicketType && null != oTicketTypeSelect)
					{
						var nIdx = oTicketTypeSelect.selectedIndex;
						if(nIdx < 0)
							continue;
						if(oTicketTypeSelect.options[nIdx].getAttribute("TicketType") != nTicketType)
							continue;
					}
				
					var discountID = oNextTicketDiscount.getAttribute("discountID");
					if(null == arrDiscountIDs[discountID])
						arrDiscountIDs[discountID]=0;
					if(null == arrTkPerf[this.PerfId]["discTkApplied_"+discountID])
						arrTkPerf[this.PerfId]["discTkApplied_"+discountID]=0;
				    var nLimit=0;
				    var nFloor=0;
				    var nCeilling=0;
				    var lCntTicketsPerEvent = 0;
				    var lCntTicketsPerPerformance = 0;				    
				    var lQuantityRequired = 0;
				    var lDiscountType=0;
				    var bIsDiscountEventGlobal = (oNextTicketDiscount.getAttribute("Global") == "True")?true:false;
					
					var attrActCode = $(oNextTicketDiscount).attr("ActivationCode");
					var lActivationCode = attrActCode;
					if(null == lActivationCode)
						lActivationCode = "";
					if(lActivationCode != $("#txtDiscountActivationCode").val())
						lActivationCode = "";
				    
				    if  (null!=oTkDiscount.getAttribute("cntTicketsPerEvent"))
						lCntTicketsPerEvent = Number(oTkDiscount.getAttribute("cntTicketsPerEvent"));
					if  (null!=oTkDiscount.getAttribute("cntTicketsPerPerformance"))
						lCntTicketsPerPerformance = Number(oTkDiscount.getAttribute("cntTicketsPerPerformance"));
					if  (null!=oNextTicketDiscount.getAttribute("DiscountType"))
				       lDiscountType=Number(oNextTicketDiscount.getAttribute("DiscountType"));						
					if  (null!=oNextTicketDiscount.getAttribute("QuantityRequired"))
				       lQuantityRequired=Number(oNextTicketDiscount.getAttribute("QuantityRequired"));
				    
				    if(null == arrTkPerTypes[this.PerfId+"tp_"+nTicketType])
						arrTkPerTypes[this.PerfId+"tp_"+nTicketType] = 0;
				    
				    if(lDiscountType==1 && 
						(lQuantityRequired > lCntTicketsPerPerformance-arrTkPerTypes[this.PerfId+"tp_"+nTicketType])) 
							continue;
						
				    if( (!bIsDiscountEventGlobal && lQuantityRequired > lCntTicketsPerEvent-arrTkPerTypes[this.PerfId+"tp_"+nTicketType]) 
				      || (bIsDiscountEventGlobal && lQuantityRequired > lTotalTicketCount )) continue;
				    if  (null!=oNextTicketDiscount.getAttribute("Limit"))
				       nLimit=Number(oNextTicketDiscount.getAttribute("Limit"));
				    if (null!=oNextTicketDiscount.getAttribute("Floor") )
				        nFloor=Number(oNextTicketDiscount.getAttribute("Floor"));
				    if (null!=oNextTicketDiscount.getAttribute("Ceiling") )
				        nCeilling=Number(oNextTicketDiscount.getAttribute("Ceiling"));
				        
					this.setDiscount(discountID, (nDollarAmount + nPercentageAmount*this.nBaseAmount/100), oNextTicketDiscount.getAttribute("modifierCode"), oNextTicketDiscount.getAttribute("DiscountGroupId"), oNextTicketDiscount.getAttribute("DiscountGroupName"), nFloor, nCeilling, nLimit,nTicketType,lActivationCode);
					
					if(null != nPointAmount && "" != nPointAmount)
					{
						AddPointsToAccountBalance(Number(this.nTixQty)*Number(nPointAmount));
					}
				}
				if(null != oNextTicketDiscount.getAttribute("ActivationCode") && "" != oNextTicketDiscount.getAttribute("ActivationCode"))
				{
					$("#lblDiscountActivationCode").show();
					$("#inpDiscountActivationCode").show();
				}

			}
			if(0 != feePM_ID)
			{
				for(var i=0;i<aryPayTypes.length;i++)
				{
					//even if it applies by delivery method, still set payment method applicability
					
					//if(null != arrFeesID[feeID])
					//	if(feeID == arrFeesID[feeID])
					//	{
					//		bHasPayment = true; 
					//		continue;
					//	}

					if(feePM_ID == aryPayTypes[i].PaymenttypesClientId && (hiddenInputName != "fee" || 0 == nPriceCeiling || (nPriceFloor < this.nBaseAmount && this.nBaseAmount <= nPriceCeiling)))
					{
						arrFeesID[feeID] = feeID;
						bHasPayment = true;
					}
				}
			}
		}
		
		//if both payment and delivery method is set, check that both apply
		if(null != feeDM_ID &&  null != feePM_ID)
			if(feeDM_ID > 0 && feePM_ID > 0)
			{
				//alert("feeID=" + feeID);
				//alert("feeID, pm=" + bHasPayment);
				//alert("feeID, dm=" + bHasDelivery);
				if(!bHasPayment || !bHasDelivery)
					arrFeesID[feeID] = -1; //exclude fee since either payment or delivery criterion not met
			}
		
		
		if(hiddenInputName == "fee")
		{
			//check for event exclusion
			var sAddEvents = oNextTicketDiscount.getAttribute("AddEvt");
			var sAddPerfs = oNextTicketDiscount.getAttribute("AddPrf");

			if(sAddEvents == null)
				sAddEvents = "";
			if(sAddPerfs == null)
				sAddPerfs = "";
				
			var sIndex = oNextTicketDiscount.id.replace("fee", "");
			var hEventName = getChildByIdOrName(oNextTicketDiscount.parentNode.parentNode, "h_EventName"+sIndex, true);
			var sEventId = "-1";
			var sPerfId = "-1";
			if(hEventName != null)
			{
				sEventId = hEventName.getAttribute("evid");
				sPerfId = hEventName.getAttribute("prfid");
			}

			var nFeeExtra = oNextTicketDiscount.getAttribute("Extra");
			var nFeeGlobal = oNextTicketDiscount.getAttribute("Global");
			var nAboveOtherFees = oNextTicketDiscount.getAttribute("aboveallotherfees");
			var nFeeCap = parseFloat2(oNextTicketDiscount.getAttribute("cap"));
			if(null == nFeeCap || "" == nFeeCap || isNaN(nFeeCap)) 
				nFeeCap = 0;
			else 
				nFeeCap = Number(nFeeCap);
			
			var strTTFeesId = ""; //fees that are applicable on this tickettype
			if(null != oTicketTypeSelect)
				if(oTicketTypeSelect.selectedIndex >= 0)
				{
					var nFeeAmount = 0;
					
					strTTFeesId = oTicketTypeSelect.options[oTicketTypeSelect.selectedIndex].getAttribute("feesid");
					if(null == strTTFeesId)
						strTTFeesId = "";
				}

			if(null == pSeasonPackageId) 
				pSeasonPackageId = "";
			
			//alert("nFeeGlobal=" + nFeeGlobal);
			//alert("nFeeExtra=" + nFeeExtra);
			//alert("strTTFeesId=" + strTTFeesId);
			//alert("sAddEvents=" + sAddEvents);
			//alert("sEventId=" + sEventId);
			//alert("sAddPerfs=" + sAddPerfs);
			//alert("sPerfId=" + sPerfId);
			
			//alert(nFeeGlobal!="false");
			//alert(nFeeExtra != "true");
			//alert("feeID=" + feeID);
			if( 
				nFeeExtra != "true" &&
				(nFeeGlobal!="false" ||
				(nFeeGlobal =="false" && sAddEvents.indexOf(sEventId + ",True") != -1) || 
				(nFeeGlobal =="false" && sAddEvents.indexOf(sEventId + ",False") != -1 && strTTFeesId.indexOf(feeID + "&") != -1) ||
				(nFeeGlobal =="false" && sAddEvents.indexOf(sEventId + ",False") != -1 && sAddPerfs.indexOf(sPerfId + ",") != -1) ||
				(nFeeGlobal =="false" /*&& sAddEvents.indexOf(sEventId + ",False") != -1*/ && sAddEvents.indexOf(pSeasonPackageId + ",True") !=-1 && pSeasonPackageId != "")
				)
				)
			{		
				if(null == arrFeesID["seted"+feeID] && feeID == arrFeesID[feeID])
				{
					//alert("setFee: "+feeID);
					this.setFee(feeID, nDollarAmount, nPercentageAmount, nFeeCap, oNextTicketDiscount.getAttribute("FeeGroupId"), oNextTicketDiscount.getAttribute("FeeGroupName"), oNextTicketDiscount.getAttribute("CalculateAfterDiscounts"), nRoundTo, sRoundingType, oNextTicketDiscount.getAttribute("Hidden"), nAboveOtherFees);
					arrFeesID["seted"+feeID] = feeID;
				}
			}
			else
			{
			 	arrFeesID[feeID] = -1;
			}
		}
	}while(oNextTicketDiscount != null);
	
	return this;
}

//public method
//used in GetTickets.js/updateTotals()
function BuildFeeGroup(pDiv)
{
	if(null == pDiv) return;

	var arrGroups = new Array();
	for(var xx=0;xx<this.nTixQty;xx++)
	{
		for(var i=0; i< this.Items[xx].Fees.length; i++)
		{		 
			var lFee = this.Items[xx].Fees[i];
			if(lFee.Hidden!="true")
			{
				if(null == arrGroups[lFee.FeeGroupId])
				{
					arrGroups[lFee.FeeGroupId] = new Object();
					arrGroups[lFee.FeeGroupId].Name = lFee.FeeGroupName;
					if("" == arrGroups[lFee.FeeGroupId].Name)
						arrGroups[lFee.FeeGroupId].Name = "Other";
					arrGroups[lFee.FeeGroupId].Amount = 0;
				}
				//Add Fee Amount to Group
				arrGroups[lFee.FeeGroupId].Amount += lFee.Amount;
			}
		}
	}
	
	if(null !=this.SeasonTickets)
	{
		for(var ss=0;ss<this.SeasonTickets.length;ss++)
		{
			if(this.SeasonTickets[ss]!=null)
			{
			for(var xx=0;xx<this.SeasonTickets[ss].nTixQty;xx++)
			{
				for(var i=0; i< this.SeasonTickets[ss].Items[xx].Fees.length; i++)
				{
					var lFee = this.SeasonTickets[ss].Items[xx].Fees[i];
					if(lFee.Hidden!="true")
					{
						if(null == arrGroups[lFee.FeeGroupId])
						{
							arrGroups[lFee.FeeGroupId] = new Object();
							arrGroups[lFee.FeeGroupId].Name = lFee.FeeGroupName;
							if("" == arrGroups[lFee.FeeGroupId].Name)
								arrGroups[lFee.FeeGroupId].Name = "Other";
							arrGroups[lFee.FeeGroupId].Amount = 0;
						}
						//Add Fee Amount to Group
						arrGroups[lFee.FeeGroupId].Amount += lFee.Amount;
					}
				}
			}
			}
		}
	}
		
	//Fill pDiv
	var strTbl = "<TABLE>";
	for(xx in arrGroups)
		if(null != arrGroups[xx].Name && 0 != arrGroups[xx].Amount)
			strTbl += "<TR><TD nowrap>"+arrGroups[xx].Name+"</TD><TD>"+parseFloat2(arrGroups[xx].Amount).toFixed(2)+"</TD></TR>";
	strTbl += "</TABLE>";
	pDiv.innerHTML = strTbl;
}

//public method
//used in GetTickets.js/updateTotals()
function BuildDiscountGroup(pDiv)
{
	if(null == pDiv) return;
	
	var arrGroups = new Array();
	for(var xx=0;xx<this.nTixQty;xx++)
	{
		for(var i=0; i< this.Items[xx].Discounts.length; i++)
		{
			var lDiscount = this.Items[xx].Discounts[i];
			if(null == arrGroups[lDiscount.DiscountGroupId])
			{
				arrGroups[lDiscount.DiscountGroupId] = new Object();
				arrGroups[lDiscount.DiscountGroupId].Name = lDiscount.DiscountGroupName;
				if("" == arrGroups[lDiscount.DiscountGroupId].Name)
					arrGroups[lDiscount.DiscountGroupId].Name = "Other";
				arrGroups[lDiscount.DiscountGroupId].Amount = 0;
			}
			//Add Discount Amount to Group
			arrGroups[lDiscount.DiscountGroupId].Amount += lDiscount.Amount;
		}
	}
		
	//Fill pDiv
	var strTbl = "<TABLE>";
	for(xx in arrGroups)
		if(null != arrGroups[xx].Name && 0 != arrGroups[xx].Amount)
			strTbl += "<TR><TD nowrap>"+arrGroups[xx].Name+"</TD><TD>"+parseFloat2(arrGroups[xx].Amount).toFixed(2)+"</TD></TR>";
	strTbl += "</TABLE>";
	pDiv.innerHTML = strTbl;
}

function parseFloat2(strFloat)
{
	if("undefined" == typeof(strFloat))
		return 0;
	if(null == strFloat)
		return 0;

	//replace comma into dot 
	strFloat = String(strFloat);
	strFloat = strFloat.replace(",", "."); 
	
	return parseFloat(strFloat);
}

function SwitchProtocol(bIsHttps, sNewPage)
{	
	var sRet = "http://"; 
	if(bIsHttps && gIsHttpsSwitchRequired) //check if we have https enabled
		sRet = "https://"; 
	else
		if(window.location.protocol != null && window.location.protocol.indexOf("https:") >= 0)
			sRet = "https://"; 

	sRet += window.location.hostname;
	
	var strPath = "/";
	var iPos = window.location.pathname.lastIndexOf("/");
	if(iPos >= 0)
		strPath = window.location.pathname.substr(0, iPos);
		
	sRet += strPath;
	sRet += "/";
	sRet += sNewPage;
	
	return sRet;
}

// Common sales functions
function onSeatDown(evt)
{
	if(window.event)
	{
		startSeat = window.event.srcElement;
		window.event.returnValue = false;
	}
	else
	{
		startSeat = evt.target;
		evt.preventDefault();
	}

	var oSeat = startSeat;
	if(startSeat.tagName != "TD")
		oSeat = getChildByTagName(startSeat,"TD",true);
	if(oSeat == null)
		oSeat = getParentNodeByTagName(startSeat,"TD",true);

	startSeat = oSeat;
	
	return false;
}

function onSeatUp(evt)
{
	if(typeof(startSeat) == "undefined")
		return;
	if(startSeat == null)
		return;

	if(window.event)
	{
		endSeat = window.event.srcElement;
		window.event.returnValue = false;
	}
	else
	{
		endSeat = evt.target;
		evt.preventDefault();
	}

	var oSeat = endSeat;
	if(endSeat.tagName != "TD")
		oSeat = getChildByTagName(endSeat,"TD",true);
	if(oSeat == null)
		oSeat = getParentNodeByTagName(endSeat,"TD",true);

	endSeat = oSeat;

	//if only one seat, clear and let onclick event handle the work
	if(endSeat == startSeat)
	{
		endSeat = null;
		startSeat = null;
		return;
	}

	startx = parseInt(startSeat.getAttribute("x"));
	starty = parseInt(startSeat.getAttribute("y"));
	endx = parseInt(endSeat.getAttribute("x"));
	endy = parseInt(endSeat.getAttribute("y"));

	if(startx > endx )
	{
		var tmp = startx;
		startx = endx;
		endx = tmp;
	}
	if(starty > endy)
	{
		var tmp = starty;
		starty = endy;
		endy = tmp;
	}

	var oTable = $(endSeat).parents("TABLE")[0];
	$(oTable).find("td").each(
			function(){
				var x = this.getAttribute("x");
				var y = this.getAttribute("y");
				
				if(typeof(x) == "undefined" || typeof(y) == "undefined")
					return;
				
				if( x>= startx && x <= endx && y>=starty && y<=endy && typeof(this.onclick) == "function")
					this.onclick();
			}
		);

	startSeat = null;
	endSeat = null;
}

//----------------------:AddressLookUp-------------------------------------
function PatronLookUpById(patronId)
{
    //lookup patron by id if progress bar is not active (another request is not currently in progress)
    if (!IsProgressbarActive())
        AddressLookUp("pid", patronId, null, null);
}

function AddressLookUp(prm,value,prm2,value2) {
	
	if("" == value && (null == value2 || "" == value2))
		return;
		
	gAddressFindType = "bill";
	var jqFrm = $("#frameAddressLookup");
	var jqDiv = $("#divAddressLookup");
	if(jqFrm.length != 1 || jqDiv.length != 1)
		return;
	
	var sPrm2 = "";
	if(null != prm2 && null != value2)
		sPrm2 = '&'+prm2+'='+value2;
	ShowProgressbar();
	
	var strURL = "ReverseLookup.aspx?"+prm+"="+escape(value)+sPrm2;
	
	$.post(strURL, "<a>a</a>", 
		function(data){
			AddressLookUpComplete(data, prm, value, sPrm2);
		});
	
	$("#patron_billingaddressid").val("0");
	$("#patron_DIVupdateaddress").hide();
	$("#shipp_DIVupdateaddress").hide();
}

function AddressLookUpComplete(strResp,prm,value,sPrm2) 
{
	ShowProgressbar();
	var jqFrm = $("#frameAddressLookup");
	var jqDiv = $("#divAddressLookup");
	if(jqFrm.length != 1 || jqDiv.length != 1)
		return;
		
	var str = "<table cellSpacing='0' cellPadding='0' width='100%' style='background-color:#E2E2F2'>";
		str +="<tr><th style='width:100%;'></th><th onclick='CloseAddressLookUp();' style='width:15px;color:red;cursor:pointer;' ><b>X</b</th></tr></table>";
	
	jqDiv.html(str+strResp);

	if($('#patron_firstname1_10').length > 0)
	{
		CloseAddressLookUp(); 
		PatronLookUp('&'+prm+'='+value+sPrm2); //Z
		return;
	}
	
	var jqPID = $("#h_PatronIDs");
	if(jqPID.length != 1) 
		return;
	var arrPIDs = jqPID.val().split(',');
	/*
	 COMMENTED OUT BY JL 10/10/08.  Do not auto-fill due to confusion caused when its not patron user intended to use.
	if(1 == arrPIDs.length-1)
	{
		UseInfo(arrPIDs[0]);
		return;
	}
	*/
	if(0 == arrPIDs.length-1)
		return;

	jqDiv.show();
	jqFrm.show();
	jqFrm[0].left = jqDiv.css("left");
	jqFrm[0].top = jqDiv.css("top");
	
	var offsetW = jqDiv[0].offsetWidth;
	if(arrPIDs.length-1 > 2) 
		offsetW +=17;
	
	jqFrm[0].width=offsetW+'px';
	jqFrm[0].height=jqDiv[0].offsetHeight+'px';
}

function CloseAddressLookUp()
{
	$("#frameAddressLookup").hide();
	$("#divAddressLookup").hide();
}

function clickDetail(ID)
{
	UseInfo(ID);
}

function PatronLookUp(pReq) {
	if(null == pReq)
		pReq = "";
	gAddressFindType = "patron";
	
	if (!isWeb)
		window.open('SearchPatrons.aspx?mode=ShopingCart&ID='+gClientId+pReq,'PatronLookupWin','width=600,height=600,scrollbars=yes,resize=yes,top=20,left=20,location=0,directories=0,toolbar=0,menubar=0');
}

//--------------- coupons --------------------
var gPatronCoupons = null;

function getPatronCoupons(){
	gPatronCoupons = ""; //default value

	var strPID = $("#patron_id").val();
	if(typeof(strPID) == "undefined" || null == strPID)
		return;
	if(Trim(strPID) == "" || strPID == "0")
		return;
	
	var strSavedCoupons = $("#hPatronCoupons").val();
	if(typeof(strSavedCoupons) != "undefined" && Trim(strSavedCoupons).length > 0)
	{
		gPatronCoupons = strSavedCoupons;
		return;
	}
	
	//doing request 
	var strXML = "<Patron><ID>" + strPID + "</ID></Patron>";

	var strRequestXML = "<envelope><body>" +
					"<command name=\"Populate\">" +
					"<class name=\"" + 'RedeemedCoupons' + "\" />";

	strRequestXML += "<param type=\"" + "Patron" + "\">" + strXML + "</param>";

	var strXsltName = "CouponSellOptions.xslt";	//just pull back xml
	strRequestXML += "</command>" +
					"<xslt>" + strXsltName + "</xslt>" +
					"</body></envelope>";

	//call ajax
    $.ajax({
        type: "POST",
        url: gSOAPListenerURL,
        data: strRequestXML,
        contentType: "text/xml",
        dataType: "text",
        async : false, 
        success: function(data, textStatus) {
            gPatronCoupons = data;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error = " + XMLHttpRequest.responseText);
				return false;
        }
    });
}

function listCoupons(){
	if(null != gPatronCoupons)
		return gPatronCoupons;
	
	//reget patron coupons
	getPatronCoupons();
	return gPatronCoupons;
}
//end common sales functions 
 var cp = new ColorPicker(5);
cp.Build();

function ColorPicker(intBase){
	this.Target = null;
	this.Name = null;
	this.Base = intBase;
	this.Inc = (255 / this.Base);
	this.Mid = this.Base;
	this.BaseColors = new Array(new Array(this.Base,0,0),new Array(this.Base,this.Base,0),new Array(0,this.Base,0),new Array(0,this.Base,this.Base),new Array(0,0,this.Base),new Array(this.Base,0,this.Base),new Array(this.Base,0,0));
	this.yMax = (2 * this.Base);
	this.xMax = (this.Base * (this.BaseColors.length - 1));
	this.Build = build;
	this.ColorHTML = "";
}

function ShowColors(strSpan){
	document.getElementById(strSpan).style.visibility = 'visible';
	var oDiv = document.createElement('DIV');
	if (strSpan=="spToolsItemManagerColor")
	  {
	    oDiv.style.position='absolute';
	    cp.Build("new",arguments[1]);
	    
	  }
	oDiv.innerHTML = cp.ColorHTML;
	document.getElementById(strSpan).appendChild(oDiv);
}

function GetColors(strSpan){
	if(gEBI(strSpan).innerHTML=="") 
	{
	ShowColors(strSpan);
	return;
	}
	if((gEBI(strSpan).style.display=='none')||(gEBI(strSpan).style.visibility=='hidden')) 
		{
		gEBI(strSpan).style.visibility='visible';
		}
	else
		{
		gEBI(strSpan).innerHTML="";
		gEBI(strSpan).style.visibility='hidden';
		}
}

function build(){
	var strHTML = "<table border=0 cellpadding=0 cellspacing=0>";
	//<tr><td height=25 colspan=" + Math.floor((this.xMax + 1) / 2) + " align=left valign=middle id=tdName style=\"background-color: #666666;color: #ffffff;font: 10pt Arial;\">&nbsp;</td><td colspan=" + Math.ceil((this.xMax + 1) / 2) + " height=25 valign=middle align=right style=\"background-color: #666666;color: #ffffff;font: bold 10pt Arial;\"><span style=\"background-color: #666666;color: #ffffff;font: 8pt Arial;cursor: pointer;\" title=CLOSE onmouseover=\"this.style.color='#FF6600';\" onmouseout=\"this.style.color='#FFFFFF';\" onclick=\"cp.Hide();\">X</span></td></tr>";
	var x,y,r,g,b,R,G,B;
	for(y=0;y<=this.yMax;y++){
		strHTML = strHTML + "<tr>";
		for(x=0;x<=this.xMax;x++){
			var xInc = (x % this.Base);
			var xBase = (Math.floor(x / this.Base) % (this.BaseColors.length - 1));
			var xApproach = (Math.ceil(x / this.Base) % (this.BaseColors.length - 1));
			var BaseColor = this.BaseColors[xBase];
			var ApproachColor = this.BaseColors[xApproach];
			var NewColor = new Array();
			var i;
			for(i=0;i<3;i++){
				if(y==this.Mid){
					if(BaseColor[i]>ApproachColor[i]){
						NewColor[i] = (BaseColor[i] - xInc);
					}
					else if(BaseColor[i]<ApproachColor[i]){
						NewColor[i] = (BaseColor[i] + xInc);
					}
					else{
						NewColor[i] = BaseColor[i];
					}
				}
				else if(y==0){
					var grey = (((2 * this.xMax) - (2 * Math.floor(x / 2))) / (2 * this.xMax)) * this.Base;
					NewColor[i] = grey;
				}
				else if(y==this.yMax){
					var grey = (((2 * this.xMax) - (this.xMax + (2 * Math.floor(x / 2)))) / (2 * this.xMax)) * this.Base;
					NewColor[i] = grey;
				}
				else if(y>this.Mid){
					if(BaseColor[i]>ApproachColor[i]){
						NewColor[i] = ((BaseColor[i] - xInc) - Math.abs(this.Mid - y)) >= 0 ? ((BaseColor[i] - xInc) - Math.abs(this.Mid - y)) : 0;

					}
					else if(BaseColor[i]<ApproachColor[i]){
						NewColor[i] = ((BaseColor[i] + xInc) - Math.abs(this.Mid - y)) >= 0 ? ((BaseColor[i] + xInc) - Math.abs(this.Mid - y)) : 0;
					}
					else{
						NewColor[i] = (BaseColor[i] - Math.abs(this.Mid - y)) >= 0 ? (BaseColor[i] - Math.abs(this.Mid - y)) : 0;
					}
				}
				else if(y<this.Mid){
					if(BaseColor[i]>ApproachColor[i]){
						NewColor[i] = ((BaseColor[i] - xInc) + Math.abs(this.Mid - y)) <= this.Base ? ((BaseColor[i] - xInc) + Math.abs(this.Mid - y)) : this.Base;
					}
					else if(BaseColor[i]<ApproachColor[i]){
						NewColor[i] = ((BaseColor[i] + xInc) + Math.abs(this.Mid - y)) <= this.Base ? ((BaseColor[i] + xInc) + Math.abs(this.Mid - y)) : this.Base;
					}
					else{
						NewColor[i] = (BaseColor[i] + Math.abs(this.Mid - y)) <= this.Base ? (BaseColor[i] + Math.abs(this.Mid - y)) : this.Base;
					}
				}
			}
			 var strColor = Dec2Hex(DecValue(NewColor[0],this.Inc)) + Dec2Hex(DecValue(NewColor[1],this.Inc)) + Dec2Hex(DecValue(NewColor[2],this.Inc));
			//strHTML = strHTML + "<td onclick=\"cp.Target.style.backgroundColor=this.style.backgroundColor;cp.Target.style.color='#" + foreColor(strColor) + "';cp.Target.value='#" + strColor + "';cp.Hide();\" style=\"cursor: pointer;height: 10px;width: 10px;background-color: #" + strColor + "\" title=\"" + strColor + "\"><img src=images/blank.gif style=\"-moz-Opacity: 0;filter: alpha(opacity=0);height: 10px;width: 10px;\"></td>";
			if("undefined" == typeof(arguments[0]))
				strHTML = strHTML + "<td onclick=\"getInput(this).value = '#" + strColor + "';getInput(this).style.backgroundColor=this.style.backgroundColor;getInput(this).style.color='#" + foreColor(strColor) + "';getSpan(this).removeChild(getDiv(this));\" style=\"font: 1px Arial;cursor: pointer;height: 5px;width: 5px;background-color: #" + strColor + "\" title=\"" + strColor + "\">&nbsp;</td>";
			  else	
			  {
			   	strHTML = strHTML + "<td onclick=\"getInputRS('"+arguments[1]+"','"+strColor+"');getSpan(this).removeChild(getDiv(this)); \" style=\"font: 1px Arial;cursor: pointer;height: 5px;width: 5px;background-color: #" + strColor + "\" title=\"" + strColor + "\">&nbsp;</td>";
			  }				  
		}
		strHTML = strHTML + "</tr>";
	}
	strHTML = strHTML + "</table>";
	//alert("html="+strHTML);
	this.ColorHTML = strHTML;
}

function parseColorID(strID){
	//cut out span
	return strID.substring(4,strID.length);
}

function DecValue(intX,intInc){
	return Math.floor(intX * intInc);
}

//converts 2 digit hex value to decimal
function Hex2Dec(h){
	var arrH = h.split("");
	var d0, d1;
	if(isNaN(arrH[0])){
		d0 = Number((arrH[0].charCodeAt(0) - 64) + 9);
	}
	else{
		d0 = Number(arrH[0]);
	}
	if(isNaN(arrH[1])){
		d1 = Number((arrH[1].charCodeAt(0) - 64) + 9);
	}
	else{
		d1 = Number(arrH[1]);
	}
	return (d0 * 16) + d1;
}

//converts decimal to 2 digit hex
function Dec2Hex(d){
	var arrHex = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
	var h0 = Math.floor(d / 16);
	var h1 = d % 16;
	return arrHex[h0] + arrHex[h1];
}

function foreColor(strHex){
	// strHex:#ffffff vs. ffffff
	if(strHex.indexOf("#")>=0){
		var r = Hex2Dec(strHex.substring(1,3));
		var g = Hex2Dec(strHex.substring(3,5));
		var b = Hex2Dec(strHex.substring(5,7));
	}
	else{
		var r = Hex2Dec(strHex.substring(0,2));
		var g = Hex2Dec(strHex.substring(2,4));
		var b = Hex2Dec(strHex.substring(4,6));
	}
	var intAvg = Math.floor((r + g + b) / 3);
	if(intAvg>=119){
		return "000000";
	}
	else{
		return "FFFFFF";
	}
}

function getSpan(objTD){
	return objTD.parentNode.parentNode.parentNode.parentNode.parentNode;
}

function getInput(objTD){
	var strID = getSpan(objTD).id;
	var strNoSpan=strID;
	if(strID.substring(0,4).indexOf('span')>=0) strNoSpan = strID.substring(4,strID.length);
	if(strID.indexOf('ColorPickerSpan')>=0) 
	{
	SetCustomHoldBlock();
	strNoSpan='HoldSampleDiv'; //for making holds on sales
	}
	return gEBI(strNoSpan);
}
function getInputRS(obj,color){
	
	gEBI(obj).value='#'+color;
	gEBI(obj).style.backgroundColor='#'+color;
}
function getDiv(objTD){
	return objTD.parentNode.parentNode.parentNode.parentNode;
}

function getGrandParentID(objTD){
	return objTD.parentNode.parentNode.parentNode.parentNode.parentNode.id;
} 
 // xp_progressbar
// Copyright 2004 Brian Gosselin of ScriptAsylum.com
//
// v1.0 - Initial release
// v1.1 - Added ability to pause the scrolling action (requires you to assign
//        the bar to a unique arbitrary variable).
//      - Added ability to specify an action to perform after a x amount of
//      - bar scrolls. This requires two added arguments.
// v1.2 - Added ability to hide/show each bar (requires you to assign the bar
//        to a unique arbitrary variable).

// var xyz = createBar(
// total_width,
// total_height,
// background_color,
// border_width,
// border_color,
// block_color,
// scroll_speed,
// block_count,
// scroll_count,
// action_to_perform_after_scrolled_n_times
// )
var w3c=(document.getElementById)?true:false;
var ie=(document.all)?true:false;
var N=-1;

function createBar(oDoc,w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action){
if(ie||w3c){
var t='<div id="_xpbar'+(++N)+'" style="visibility:visible; position:relative; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
for(i=0;i<blocks;i++){
t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
t+=(ie)?'filter:alpha(opacity='+(100-i*(100/blocks))+')':'-Moz-opacity:'+((100-i*(100/blocks))/100);
t+='"></span>';
}
t+='</span></div>';
if(null == oDoc)
	document.write(t);
else
	oDoc.innerHTML = t;
var bA=(ie)?document.all['blocks'+N]:document.getElementById('blocks'+N);
bA.bar=(ie)?document.all['_xpbar'+N]:document.getElementById('_xpbar'+N);
bA.blocks=blocks;
bA.N=N;
bA.w=w;
bA.h=h;
bA.speed=speed;
bA.ctr=0;
bA.count=count;
bA.action=action;
bA.togglePause=togglePause;
bA.showBar=function(){
this.bar.style.visibility="visible";
}
bA.hideBar=function(){
this.bar.style.visibility="hidden";
}
bA.tid=setInterval('startBar('+N+')',speed);
return bA;
}}

function startBar(bn){
var t=(ie)?document.all['blocks'+bn]:document.getElementById('blocks'+bn);
if(null == t) 
{
	clearInterval(this.tid);
	return;
}
if(parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks)>t.w){
t.style.left=-(t.h*2+1)+'px';
t.ctr++;
if(t.ctr>=t.count){
eval(t.action);
t.ctr=0;
}}else t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}
 
 window.onerror = errorHandler;

function errorHandler(message, url, line)
{
   // message == text-based error description
   // url     == url which exhibited the script error
   // line    == the line number being executed when the error occurred
   
   //check for recursive error call
   if(stackOfCaller(errorHandler,0).split("errorHandler").length > 2)
		return false;
   
	var errMess = "JavaScript Error occurred at " +url+ "\n\r";
	errMess+= "Error Message: "+message + "\n\r";
	errMess+= "Error Line: "+line + "\n\r";
    if(stackOfCaller!=null && "undefined" != typeof(stackOfCaller)) 
		errMess+= "Error Trace:\n\r" + stackOfCaller(errorHandler,0)+"\n\r";
    
    //alert(errMess);
	SendErrorToServer(errMess,url);
	
   return true;
}

function SendErrorToServer(strError,strLocation)
{
	if("undefined" != typeof(gClientId) && gClientId!=null) 
		strError+="Client ID: "+gClientId + "\n\r";
	if("undefined" != typeof(isWeb) && isWeb!=null) 
		strError+="isWeb : "+isWeb + "\n\r";	
	else  
		strError+="isWeb : undefined\n\r";	
	
	var strXML = "<Envelop><Location>"+strLocation+"</Location><Error>"+strError+"</Error></Envelop>";
	$.post("MessageCenter.aspx", strXML)
}
 
 /*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},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 toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},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(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); 
 /*
 * jQuery UI 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.1",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
 
 /*
 * jQuery UI Dialog 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function($) {

var setDataSwitch = {
		dragStart: "start.draggable",
		drag: "drag.draggable",
		dragStop: "stop.draggable",
		maxHeight: "maxHeight.resizable",
		minHeight: "minHeight.resizable",
		maxWidth: "maxWidth.resizable",
		minWidth: "minWidth.resizable",
		resizeStart: "start.resizable",
		resize: "drag.resizable",
		resizeStop: "stop.resizable"
	},
	
	uiDialogClasses =
		'ui-dialog ' +
		'ui-widget ' +
		'ui-widget-content ' +
		'ui-corner-all ';

$.widget("ui.dialog", {

	_init: function() {
		this.originalTitle = this.element.attr('title');

		var self = this,
			options = this.options,

			title = options.title || this.originalTitle || '&nbsp;',
			titleId = $.ui.dialog.getTitleId(this.element),

			uiDialog = (this.uiDialog = $('<div/>'))
				.appendTo(document.body)
				.hide()
				.addClass(uiDialogClasses + options.dialogClass)
				.css({
					position: 'absolute',
					overflow: 'hidden',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
					(options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && self.close(event));
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mousedown(function(event) {
					self.moveToTop(false, event);
				}),

			uiDialogContent = this.element
				.show()
				.removeAttr('title')
				.addClass(
					'ui-dialog-content ' +
					'ui-widget-content')
				.appendTo(uiDialog),

			uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
				.addClass(
					'ui-dialog-titlebar ' +
					'ui-widget-header ' +
					'ui-corner-all ' +
					'ui-helper-clearfix'
				)
				.prependTo(uiDialog),

			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass(
					'ui-dialog-titlebar-close ' +
					'ui-corner-all'
				)
				.attr('role', 'button')
				.hover(
					function() {
						uiDialogTitlebarClose.addClass('ui-state-hover');
					},
					function() {
						uiDialogTitlebarClose.removeClass('ui-state-hover');
					}
				)
				.focus(function() {
					uiDialogTitlebarClose.addClass('ui-state-focus');
				})
				.blur(function() {
					uiDialogTitlebarClose.removeClass('ui-state-focus');
				})
				.mousedown(function(ev) {
					ev.stopPropagation();
				})
				.click(function(event) {
					self.close(event);
					return false;
				})
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
				.addClass(
					'ui-icon ' +
					'ui-icon-closethick'
				)
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			uiDialogTitle = $('<span/>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar);

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		(options.draggable && $.fn.draggable && this._makeDraggable());
		(options.resizable && $.fn.resizable && this._makeResizable());

		this._createButtons(options.buttons);
		this._isOpen = false;

		(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
		(options.autoOpen && this.open());
		
	},

	destroy: function() {
		(this.overlay && this.overlay.destroy());
		this.uiDialog.hide();
		this.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content ui-widget-content')
			.hide().appendTo('body');
		this.uiDialog.remove();

		(this.originalTitle && this.element.attr('title', this.originalTitle));
	},

	close: function(event) {
		var self = this;
		
		if (false === self._trigger('beforeclose', event)) {
			return;
		}

		(self.overlay && self.overlay.destroy());
		self.uiDialog.unbind('keypress.ui-dialog');

		(self.options.hide
			? self.uiDialog.hide(self.options.hide, function() {
				self._trigger('close', event);
			})
			: self.uiDialog.hide() && self._trigger('close', event));

		$.ui.dialog.overlay.resize();

		self._isOpen = false;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force, event) {

		if ((this.options.modal && !force)
			|| (!this.options.stack && !this.options.modal)) {
			return this._trigger('focus', event);
		}
		
		if (this.options.zIndex > $.ui.dialog.maxZ) {
			$.ui.dialog.maxZ = this.options.zIndex;
		}
		(this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ));

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
		this.uiDialog.css('z-index', ++$.ui.dialog.maxZ);
		this.element.attr(saveScroll);
		this._trigger('focus', event);
	},

	open: function() {
		if (this._isOpen) { return; }

		var options = this.options,
			uiDialog = this.uiDialog;

		this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null;
		(uiDialog.next().length && uiDialog.appendTo('body'));
		this._size();
		this._position(options.position);
		uiDialog.show(options.show);
		this.moveToTop(true);

		// prevent tabbing out of modal dialogs
		(options.modal && uiDialog.bind('keypress.ui-dialog', function(event) {
			if (event.keyCode != $.ui.keyCode.TAB) {
				return;
			}

			var tabbables = $(':tabbable', this),
				first = tabbables.filter(':first')[0],
				last  = tabbables.filter(':last')[0];

			if (event.target == last && !event.shiftKey) {
				setTimeout(function() {
					first.focus();
				}, 1);
			} else if (event.target == first && event.shiftKey) {
				setTimeout(function() {
					last.focus();
				}, 1);
			}
		}));

		// set focus to the first tabbable element in the content area or the first button
		// if there are no tabbable elements, set focus on the dialog itself
		$([])
			.add(uiDialog.find('.ui-dialog-content :tabbable:first'))
			.add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first'))
			.add(uiDialog)
			.filter(':first')
			.focus();

		this._trigger('open');
		this._isOpen = true;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = $('<div></div>')
				.addClass(
					'ui-dialog-buttonpane ' +
					'ui-widget-content ' +
					'ui-helper-clearfix'
				);

		// if we already have a button pane, remove it
		this.uiDialog.find('.ui-dialog-buttonpane').remove();

		(typeof buttons == 'object' && buttons !== null &&
			$.each(buttons, function() { return !(hasButtons = true); }));
		if (hasButtons) {
			$.each(buttons, function(name, fn) {
				$('<button type="button"></button>')
					.addClass(
						'ui-state-default ' +
						'ui-corner-all'
					)
					.text(name)
					.click(function() { fn.apply(self.element[0], arguments); })
					.hover(
						function() {
							$(this).addClass('ui-state-hover');
						},
						function() {
							$(this).removeClass('ui-state-hover');
						}
					)
					.focus(function() {
						$(this).addClass('ui-state-focus');
					})
					.blur(function() {
						$(this).removeClass('ui-state-focus');
					})
					.appendTo(uiDialogButtonPane);
			});
			uiDialogButtonPane.appendTo(this.uiDialog);
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = this.options,
			heightBeforeDrag;

		this.uiDialog.draggable({
			cancel: '.ui-dialog-content',
			handle: '.ui-dialog-titlebar',
			containment: 'document',
			start: function() {
				heightBeforeDrag = options.height;
				$(this).height($(this).height()).addClass("ui-dialog-dragging");
				(options.dragStart && options.dragStart.apply(self.element[0], arguments));
			},
			drag: function() {
				(options.drag && options.drag.apply(self.element[0], arguments));
			},
			stop: function() {
				$(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);
				(options.dragStop && options.dragStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = this.options,
			resizeHandles = typeof handles == 'string'
				? handles
				: 'n,e,s,w,se,sw,ne,nw';

		this.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: options.minHeight,
			start: function() {
				$(this).addClass("ui-dialog-resizing");
				(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
			},
			resize: function() {
				(options.resize && options.resize.apply(self.element[0], arguments));
			},
			handles: resizeHandles,
			stop: function() {
				$(this).removeClass("ui-dialog-resizing");
				options.height = $(this).height();
				options.width = $(this).width();
				(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		})
		.find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');
	},

	_position: function(pos) {
		var wnd = $(window), doc = $(document),
			pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
			minTop = pTop;

		if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
			pos = [
				pos == 'right' || pos == 'left' ? pos : 'center',
				pos == 'top' || pos == 'bottom' ? pos : 'middle'
			];
		}
		if (pos.constructor != Array) {
			pos = ['center', 'middle'];
		}
		if (pos[0].constructor == Number) {
			pLeft += pos[0];
		} else {
			switch (pos[0]) {
				case 'left':
					pLeft += 0;
					break;
				case 'right':
					pLeft += wnd.width() - this.uiDialog.outerWidth();
					break;
				default:
				case 'center':
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
			}
		}
		if (pos[1].constructor == Number) {
			pTop += pos[1];
		} else {
			switch (pos[1]) {
				case 'top':
					pTop += 0;
					break;
				case 'bottom':
					pTop += wnd.height() - this.uiDialog.outerHeight();
					break;
				default:
				case 'middle':
					pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2;
			}
		}

		// prevent the dialog from being too high (make sure the titlebar
		// is accessible)
		pTop = Math.max(pTop, minTop);
		this.uiDialog.css({top: pTop, left: pLeft});
	},

	_setData: function(key, value){
		(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
		switch (key) {
			case "buttons":
				this._createButtons(value);
				break;
			case "closeText":
				this.uiDialogTitlebarCloseText.text(value);
				break;
			case "dialogClass":
				this.uiDialog
					.removeClass(this.options.dialogClass)
					.addClass(uiDialogClasses + value);
				break;
			case "draggable":
				(value
					? this._makeDraggable()
					: this.uiDialog.draggable('destroy'));
				break;
			case "height":
				this.uiDialog.height(value);
				break;
			case "position":
				this._position(value);
				break;
			case "resizable":
				var uiDialog = this.uiDialog,
					isResizable = this.uiDialog.is(':data(resizable)');

				// currently resizable, becoming non-resizable
				(isResizable && !value && uiDialog.resizable('destroy'));

				// currently resizable, changing handles
				(isResizable && typeof value == 'string' &&
					uiDialog.resizable('option', 'handles', value));

				// currently non-resizable, becoming resizable
				(isResizable || this._makeResizable(value));
				break;
			case "title":
				$(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
				break;
			case "width":
				this.uiDialog.width(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_size: function() {
		/* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		 * divs will both have width and height set, so we need to reset them
		 */
		var options = this.options;

		// reset content sizing
		this.element.css({
			height: 0,
			minHeight: 0,
			width: 'auto'
		});

		// reset wrapper sizing
		// determine the height of all the non-content elements
		var nonContentHeight = this.uiDialog.css({
				height: 'auto',
				width: options.width
			})
			.height();

		this.element
			.css({
				minHeight: Math.max(options.minHeight - nonContentHeight, 0),
				height: options.height == 'auto'
					? 'auto'
					: Math.max(options.height - nonContentHeight, 0)
			});
	}
});

$.extend($.ui.dialog, {
	version: "1.7.1",
	defaults: {
		autoOpen: true,
		bgiframe: false,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		dialogClass: '',
		draggable: true,
		hide: null,
		height: 'auto',
		maxHeight: false,
		maxWidth: false,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: 'center',
		resizable: true,
		show: null,
		stack: true,
		title: '',
		width: 300,
		zIndex: 1000
	},

	getter: 'isOpen',

	uuid: 0,
	maxZ: 0,

	getTitleId: function($el) {
		return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	maxZ: 0,
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				$(document).bind($.ui.dialog.overlay.events, function(event) {
					var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0;
					return (dialogZ > $.ui.dialog.overlay.maxZ);
				});
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				(dialog.options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = $('<div></div>').appendTo(document.body)
			.addClass('ui-widget-overlay').css({
				width: this.width(),
				height: this.height()
			});

		(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		this.instances.splice($.inArray(this.instances, $el), 1);

		if (this.instances.length === 0) {
			$([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
	},

	height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

})(jQuery);
 
 /*
 * jQuery UI Datepicker 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.1" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false // True to show button panel, false to not show it
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.trigger.remove();
			$target.siblings('.' + this._appendClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			inst.trigger.filter("button").
			each(function() { this.disabled = false; }).end().
				filter("img").
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			inst.trigger.filter("button").
			each(function() { this.disabled = true; }).end().
				filter("img").
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.1";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);
 
 /*
### jQuery FCKEditor Plugin v1.3 - 2008-09-30 ###
* http://www.fyneworks.com/ - diego@fyneworks.com
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
###
Project: http://jquery.com/plugins/project/FCKEditor/
Website: http://www.fyneworks.com/jquery/FCKEditor/
*/
/*
USAGE: $('textarea').fck({ path:'/path/to/fck/editor/' }); // initialize FCK editor
ADVANCED USAGE: $.fck.update(); // update value in textareas of each FCK editor instance
*/

/*# AVOID COLLISIONS #*/
;if (window.jQuery) (function($) {
    /*# AVOID COLLISIONS #*/

    $.extend($, {
        fck: {
            waitFor: 10, // in seconds, how long should we wait for the script to load?
            config: { Config: {} }, // default configuration
            path: '/fckeditor/', // default path to FCKEditor directory
            editors: [], // array of editor instances
            loaded: false, // flag indicating whether FCK script is loaded
            intercepted: null, // variable to store intercepted method(s)

            // utility method to read contents of FCK editor
            content: function(i, v) {
                //try{
                //if(window.console) console.log(['fck.content',arguments]);
                var x = FCKeditorAPI.GetInstance(i);
                //if(window.console) console.log(['fck.content','x',x]);
                // Look for textare with matching name for backward compatibility
                if (!x) {
                    x = $('#' + i.replace(/\./gi, '\\\.') + '')[0];
                    //if(window.console) console.log(['fck.content','ele',x]);
                    if (x) x = FCKeditorAPI.GetInstance(x.id);
                };
                if (!x) {
                    alert('FCKEditor instance "' + i + '" could not be found!');
                    return '';
                };
                if (v) x.SetHTML(v);
                //if(window.console) console.log(['fck.content','x',x.GetXHTML]);
                return x.GetXHTML(true);
                //}catch(e){ return 'OOPS!'; };
            }, // fck.content function

            // inspired by Sebastián Barrozo <sbarrozo@b-soft.com.ar>
            setHTML: function(i, v) {
                if (typeof i == 'object') {
                    v = i.html;
                    i = i.InstanceName || i.instance;
                };
                return $.fck.content(i, v);
            },

            // utility method to update textarea contents before ajax submission
            update: function() {
                LOG('DEBUGGGGGG fck.update 1');
                // Update contents of all instances
                var e = $.fck.editors;
                //if(window.console) console.log(['fck.update',e]);
                for (var i = 0; i < e.length; i++) {
                    var ta = e[i].textarea;
                    //if(window.console) console.log(['fck.update','ta',ta]);
                    var ht = $.fck.content(e[i].InstanceName);
                    //if(window.console) console.log(['fck.update','ht',ht]);
                    ta.val(ht).filter('textarea').text(ht);
                    if (ht != ta.val())
                        alert('Critical error in FCK plugin:' + '\n' + 'Unable to update form data');
                }
                //if(window.console) console.log(['fck.update','done']);
            }, // fck.update

            // utility method to non-existing instances from memory
            clean: function() {
                //if(window.console) console.log(['fck.clean',$.fck.editors]);
                var a = $.fck.editors, b = {}, c = [];
                //if(window.console) console.log(['fck.clean','a',a]);
                $.each(a, function() {
                    //if(window.console) console.log(['fck.clean','a - id',this.InstanceName]);
                    if ($('#' + this.InstanceName.replace(/\./gi, '\\\.') + '').length > 0)
                        b[this.InstanceName] = this;
                });
                //if(window.console) console.log(['fck.clean','b',b]);
                $.each(b, function() { c[c.length] = this; });
                //if(window.console) console.log(['fck.clean','c',c]);
                $.fck.editors = c;
                //if(window.console) console.log(['fck.clean',$.fck.editors]);
            }, // fck.clean

            // utility method to create instances of FCK editor (if any)
            create: function(option) {
                // Create a new options object
                var o = $.extend({}/* new object */, $.fck.config || {}, option || {});
                // Normalize plugin options
                $.extend(o, {
                    selector: (o.selector || 'textarea.fck, textarea.fckeditor'),
                    BasePath: (o.path || o.BasePath || $.fck.path)
                });
                // Find fck.editor-instance 'wannabes'
                var e = $(o.e);
                if (!e.length > 0) e = $(o.selector);
                if (!e.length > 0) return;
                // Accept settings from metadata plugin
                o = $.extend({}, o,
				($.meta ? e.data()/*NEW metadata plugin*/ :
				($.metadata ? e.metadata()/*OLD metadata plugin*/ :
				null/*metadata plugin not available*/)) || {}
			);
                // Load script and create instances
                if (!$.fck.loading && !$.fck.loaded) {
                    $.fck.loading = true;
                    $.getScript(
     o.BasePath + 'fckeditor.js',
     function() { $.fck.loaded = true; }
    );
                };
                // Start editor
                var start = function() {//e){
                    if ($.fck.loaded) {
                        //if(window.console) console.log(['fck.create','start',e,o]);
                        $.fck.editor(e, o);
                    }
                    else {
                        //if(window.console) console.log(['fck.create','waiting for script...',e,o]);
                        if ($.fck.waited <= 0) {
                            alert('jQuery.fckeditor plugin error: The FCKEditor script did not load.');
                        }
                        else {
                            $.fck.waitFor--;
                            window.setTimeout(start, 1000);
                        };
                    }
                };
                start(e);
                // Return matched elements...
                return e;
            },

            // utility method to integrate this plugin with others...
            intercept: function() {
                if ($.fck.intercepted) return;
                // This method intercepts other known methods which
                // require up-to-date code from FCKEditor
                $.fck.intercepted = {
                    ajaxSubmit: $.fn.ajaxSubmit || function() { }
                };
                $.fn.ajaxSubmit = function() {
                    //if(window.console) console.log(['fck.intercepted','$.fn.ajaxSubmit',$.fck.editors]);
                    $.fck.update(); // update html
                    return $.fck.intercepted.ajaxSubmit.apply(this, arguments);
                };
                // Also attach to conventional form submission
                //$('form').submit(function(){
                // $.fck.update(); // update html
                //});
            },

            // utility method to create an instance of FCK editor
            editor: function(e /* elements */, o /* options */) {
                //if(window.console) console.log(['fck.editor','OPTIONS',o]);
                o = $.extend({}, $.fck.config || {}, o || {});
                // Default configuration
                $.extend(o, {
                    Width: (o.width || o.Width || '100%'),
                    Height: (o.height || o.Height || '500px'),
                    BasePath: (o.path || o.BasePath || $.fck.path),
                    ToolbarSet: (o.toolbar || o.ToolbarSet || 'Default'),
                    Config: (o.config || o.Config || {})
                });

                // Make sure we have a jQuery object
                e = $(e);
                //if(window.console) console.log(['fck.editor','E',e,o]);
                if (e.size() > 0) {
                    // Local array to store instances
                    var a = $.fck.editors; // || [];
                    // Go through objects and initialize fck.editor
                    e.each(
     function(i, t) {
         if ((t.tagName || '').toLowerCase() != 'textarea')
             return alert(['An invalid parameter has been passed to the $.fckeditor.editor function', 'tagName:' + t.tagName, 'name:' + t.name, 'id:' + t.id].join('\n'));

         var T = $(t); // t = element, T = jQuery
         if (!t.fck/* not already installed */) {
             t.id = t.id || 'fck' + ($.fck.editors.length + 1);
             t.name = t.name || t.id;
             var n = a.length;
             // create FCKeditor instance
             //if(window.console) console.log(['fck.editor','new FCKeditor',t.id,t]);
             a[n] = new FCKeditor(t.id);
             // Apply inline configuration
             //if(window.console) console.log(['fck.editor','Apply inline configuration',o]);


             o.Config = $.fck.config;  //SERGZ, in order to save config passed from the code

             $.extend(a[n], o, o.Config || {});
             // Start FCKeditor
             a[n].ReplaceTextarea();
             // Store reference to original element
             a[n].textarea = T;
             // Store reference to FCKeditor in element
             //if(window.console) console.log(['fck.editor','Store reference to FCKeditor in element',a[n]]);
             t.fck = a[n];
         };
     }
    );
                    // Store editor instances in global array
                    //if(window.console) console.log(['fck.editor','Store editor instances in global array',a]);
                    $.fck.editors = a;
                    //if(window.console) console.log(['fck.editor','$.fck.editors',$.fck.editors]);
                    // Remove old non-existing editors from memory
                    $.fck.clean();
                };
                // return jQuery array of elements
                return e;
            }, // fck.editor function

            // start-up method
            start: function(o/* options */) {
                // Attach itself to known plugins...
                $.fck.intercept();
                // Create FCK editors
                return $.fck.create(o);
            } // fck.start

} // fck object
            //##############################

        });
        // extend $
        //##############################


        $.extend($.fn, {
            fck: function(o) {
                //(function(opts){ $.fck.start(opts); })($.extend(o || {}, {e: this}));
                $.fck.start($.extend(o || {}, { e: this }));
            }
        });
        // extend $.fn
        //##############################

        /*# AVOID COLLISIONS #*/
    })(jQuery);
    /*# AVOID COLLISIONS #*/ 
 /*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 *
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function($) {
	var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right,

		selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],

		ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,

		loadingTimer, loadingFrame = 1,

		titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),

		isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,

		/*
		 * Private methods 
		 */

		_abort = function() {
			loading.hide();

			imgPreloader.onerror = imgPreloader.onload = null;

			if (ajaxLoader) {
				ajaxLoader.abort();
			}

			tmp.empty();
		},

		_error = function() {
			if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) {
				loading.hide();
				busy = false;
				return;
			}

			selectedOpts.titleShow = false;

			selectedOpts.width = 'auto';
			selectedOpts.height = 'auto';

			tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' );

			_process_inline();
		},

		_start = function() {
			var obj = selectedArray[ selectedIndex ],
				href, 
				type, 
				title,
				str,
				emb,
				ret;

			_abort();

			selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));

			ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts);

			if (ret === false) {
				busy = false;
				return;
			} else if (typeof ret == 'object') {
				selectedOpts = $.extend(selectedOpts, ret);
			}

			title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || '';

			if (obj.nodeName && !selectedOpts.orig) {
				selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
			}

			if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) {
				title = selectedOpts.orig.attr('alt');
			}

			href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null;

			if ((/^(?:javascript)/i).test(href) || href == '#') {
				href = null;
			}

			if (selectedOpts.type) {
				type = selectedOpts.type;

				if (!href) {
					href = selectedOpts.content;
				}

			} else if (selectedOpts.content) {
				type = 'html';

			} else if (href) {
				if (href.match(imgRegExp)) {
					type = 'image';

				} else if (href.match(swfRegExp)) {
					type = 'swf';

				} else if ($(obj).hasClass("iframe")) {
					type = 'iframe';

				} else if (href.indexOf("#") === 0) {
					type = 'inline';

				} else {
					type = 'ajax';
				}
			}

			if (!type) {
				_error();
				return;
			}

			if (type == 'inline') {
				obj	= href.substr(href.indexOf("#"));
				type = $(obj).length > 0 ? 'inline' : 'ajax';
			}

			selectedOpts.type = type;
			selectedOpts.href = href;
			selectedOpts.title = title;

			if (selectedOpts.autoDimensions) {
				if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') {
					selectedOpts.width = 'auto';
					selectedOpts.height = 'auto';
				} else {
					selectedOpts.autoDimensions = false;	
				}
			}

			if (selectedOpts.modal) {
				selectedOpts.overlayShow = true;
				selectedOpts.hideOnOverlayClick = false;
				selectedOpts.hideOnContentClick = false;
				selectedOpts.enableEscapeButton = false;
				selectedOpts.showCloseButton = false;
			}

			selectedOpts.padding = parseInt(selectedOpts.padding, 10);
			selectedOpts.margin = parseInt(selectedOpts.margin, 10);

			tmp.css('padding', (selectedOpts.padding + selectedOpts.margin));

			$('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
				$(this).replaceWith(content.children());				
			});

			switch (type) {
				case 'html' :
					tmp.html( selectedOpts.content );
					_process_inline();
				break;

				case 'inline' :
					if ( $(obj).parent().is('#fancybox-content') === true) {
						busy = false;
						return;
					}

					$('<div class="fancybox-inline-tmp" />')
						.hide()
						.insertBefore( $(obj) )
						.bind('fancybox-cleanup', function() {
							$(this).replaceWith(content.children());
						}).bind('fancybox-cancel', function() {
							$(this).replaceWith(tmp.children());
						});

					$(obj).appendTo(tmp);

					_process_inline();
				break;

				case 'image':
					busy = false;

					$.fancybox.showActivity();

					imgPreloader = new Image();

					imgPreloader.onerror = function() {
						_error();
					};

					imgPreloader.onload = function() {
						busy = true;

						imgPreloader.onerror = imgPreloader.onload = null;

						_process_image();
					};

					imgPreloader.src = href;
				break;

				case 'swf':
					selectedOpts.scrolling = 'no';

					str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
					emb = '';

					$.each(selectedOpts.swf, function(name, val) {
						str += '<param name="' + name + '" value="' + val + '"></param>';
						emb += ' ' + name + '="' + val + '"';
					});

					str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';

					tmp.html(str);

					_process_inline();
				break;

				case 'ajax':
					busy = false;

					$.fancybox.showActivity();

					selectedOpts.ajax.win = selectedOpts.ajax.success;

					ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, {
						url	: href,
						data : selectedOpts.ajax.data || {},
						error : function(XMLHttpRequest, textStatus, errorThrown) {
							if ( XMLHttpRequest.status > 0 ) {
								_error();
							}
						},
						success : function(data, textStatus, XMLHttpRequest) {
							var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader;
							if (o.status == 200) {
								if ( typeof selectedOpts.ajax.win == 'function' ) {
									ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest);

									if (ret === false) {
										loading.hide();
										return;
									} else if (typeof ret == 'string' || typeof ret == 'object') {
										data = ret;
									}
								}

								tmp.html( data );
								_process_inline();
							}
						}
					}));

				break;

				case 'iframe':
					_show();
				break;
			}
		},

		_process_inline = function() {
			var
				w = selectedOpts.width,
				h = selectedOpts.height;

			if (w.toString().indexOf('%') > -1) {
				w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px';

			} else {
				w = w == 'auto' ? 'auto' : w + 'px';	
			}

			if (h.toString().indexOf('%') > -1) {
				h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px';

			} else {
				h = h == 'auto' ? 'auto' : h + 'px';	
			}

			tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>');

			selectedOpts.width = tmp.width();
			selectedOpts.height = tmp.height();

			_show();
		},

		_process_image = function() {
			selectedOpts.width = imgPreloader.width;
			selectedOpts.height = imgPreloader.height;

			$("<img />").attr({
				'id' : 'fancybox-img',
				'src' : imgPreloader.src,
				'alt' : selectedOpts.title
			}).appendTo( tmp );

			_show();
		},

		_show = function() {
			var pos, equal;

			loading.hide();

			if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
				$.event.trigger('fancybox-cancel');

				busy = false;
				return;
			}

			busy = true;

			$(content.add( overlay )).unbind();

			$(window).unbind("resize.fb scroll.fb");
			$(document).unbind('keydown.fb');

			if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') {
				wrap.css('height', wrap.height());
			}

			currentArray = selectedArray;
			currentIndex = selectedIndex;
			currentOpts = selectedOpts;

			if (currentOpts.overlayShow) {
				overlay.css({
					'background-color' : currentOpts.overlayColor,
					'opacity' : currentOpts.overlayOpacity,
					'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
					'height' : $(document).height()
				});

				if (!overlay.is(':visible')) {
					if (isIE6) {
						$('select:not(#fancybox-tmp select)').filter(function() {
							return this.style.visibility !== 'hidden';
						}).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() {
							this.style.visibility = 'inherit';
						});
					}

					overlay.show();
				}
			} else {
				overlay.hide();
			}

			final_pos = _get_zoom_to();

			_process_title();

			if (wrap.is(":visible")) {
				$( close.add( nav_left ).add( nav_right ) ).hide();

				pos = wrap.position(),

				start_pos = {
					top	 : pos.top,
					left : pos.left,
					width : wrap.width(),
					height : wrap.height()
				};

				equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);

				content.fadeTo(currentOpts.changeFade, 0.3, function() {
					var finish_resizing = function() {
						content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
					};

					$.event.trigger('fancybox-change');

					content
						.empty()
						.removeAttr('filter')
						.css({
							'border-width' : currentOpts.padding,
							'width'	: final_pos.width - currentOpts.padding * 2,
							'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
						});

					if (equal) {
						finish_resizing();

					} else {
						fx.prop = 0;

						$(fx).animate({prop: 1}, {
							 duration : currentOpts.changeSpeed,
							 easing : currentOpts.easingChange,
							 step : _draw,
							 complete : finish_resizing
						});
					}
				});

				return;
			}

			wrap.removeAttr("style");

			content.css('border-width', currentOpts.padding);

			if (currentOpts.transitionIn == 'elastic') {
				start_pos = _get_zoom_from();

				content.html( tmp.contents() );

				wrap.show();

				if (currentOpts.opacity) {
					final_pos.opacity = 0;
				}

				fx.prop = 0;

				$(fx).animate({prop: 1}, {
					 duration : currentOpts.speedIn,
					 easing : currentOpts.easingIn,
					 step : _draw,
					 complete : _finish
				});

				return;
			}

			if (currentOpts.titlePosition == 'inside' && titleHeight > 0) {	
				title.show();	
			}

			content
				.css({
					'width' : final_pos.width - currentOpts.padding * 2,
					'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
				})
				.html( tmp.contents() );

			wrap
				.css(final_pos)
				.fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
		},

		_format_title = function(title) {
			if (title && title.length) {
				if (currentOpts.titlePosition == 'float') {
					return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>';
				}

				return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>';
			}

			return false;
		},

		_process_title = function() {
			titleStr = currentOpts.title || '';
			titleHeight = 0;

			title
				.empty()
				.removeAttr('style')
				.removeClass();

			if (currentOpts.titleShow === false) {
				title.hide();
				return;
			}

			titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr);

			if (!titleStr || titleStr === '') {
				title.hide();
				return;
			}

			title
				.addClass('fancybox-title-' + currentOpts.titlePosition)
				.html( titleStr )
				.appendTo( 'body' )
				.show();

			switch (currentOpts.titlePosition) {
				case 'inside':
					title
						.css({
							'width' : final_pos.width - (currentOpts.padding * 2),
							'marginLeft' : currentOpts.padding,
							'marginRight' : currentOpts.padding
						});

					titleHeight = title.outerHeight(true);

					title.appendTo( outer );

					final_pos.height += titleHeight;
				break;

				case 'over':
					title
						.css({
							'marginLeft' : currentOpts.padding,
							'width'	: final_pos.width - (currentOpts.padding * 2),
							'bottom' : currentOpts.padding
						})
						.appendTo( outer );
				break;

				case 'float':
					title
						.css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1)
						.appendTo( wrap );
				break;

				default:
					title
						.css({
							'width' : final_pos.width - (currentOpts.padding * 2),
							'paddingLeft' : currentOpts.padding,
							'paddingRight' : currentOpts.padding
						})
						.appendTo( wrap );
				break;
			}

			title.hide();
		},

		_set_navigation = function() {
			if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) {
				$(document).bind('keydown.fb', function(e) {
					if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
						e.preventDefault();
						$.fancybox.close();

					} else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
						e.preventDefault();
						$.fancybox[ e.keyCode == 37 ? 'prev' : 'next']();
					}
				});
			}

			if (!currentOpts.showNavArrows) { 
				nav_left.hide();
				nav_right.hide();
				return;
			}

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
				nav_left.show();
			}

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
				nav_right.show();
			}
		},

		_finish = function () {
			if (!$.support.opacity) {
				content.get(0).style.removeAttribute('filter');
				wrap.get(0).style.removeAttribute('filter');
			}

			if (selectedOpts.autoDimensions) {
				content.css('height', 'auto');
			}

			wrap.css('height', 'auto');

			if (titleStr && titleStr.length) {
				title.show();
			}

			if (currentOpts.showCloseButton) {
				close.show();
			}

			_set_navigation();
	
			if (currentOpts.hideOnContentClick)	{
				content.bind('click', $.fancybox.close);
			}

			if (currentOpts.hideOnOverlayClick)	{
				overlay.bind('click', $.fancybox.close);
			}

			$(window).bind("resize.fb", $.fancybox.resize);

			if (currentOpts.centerOnScroll) {
				$(window).bind("scroll.fb", $.fancybox.center);
			}

			if (currentOpts.type == 'iframe') {
				$('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
			}

			wrap.show();

			busy = false;

			$.fancybox.center();

			currentOpts.onComplete(currentArray, currentIndex, currentOpts);

			_preload_images();
		},

		_preload_images = function() {
			var href, 
				objNext;

			if ((currentArray.length -1) > currentIndex) {
				href = currentArray[ currentIndex + 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}

			if (currentIndex > 0) {
				href = currentArray[ currentIndex - 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}
		},

		_draw = function(pos) {
			var dim = {
				width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10),
				height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10),

				top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10),
				left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10)
			};

			if (typeof final_pos.opacity !== 'undefined') {
				dim.opacity = pos < 0.5 ? 0.5 : pos;
			}

			wrap.css(dim);

			content.css({
				'width' : dim.width - currentOpts.padding * 2,
				'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2
			});
		},

		_get_viewport = function() {
			return [
				$(window).width() - (currentOpts.margin * 2),
				$(window).height() - (currentOpts.margin * 2),
				$(document).scrollLeft() + currentOpts.margin,
				$(document).scrollTop() + currentOpts.margin
			];
		},

		_get_zoom_to = function () {
			var view = _get_viewport(),
				to = {},
				resize = currentOpts.autoScale,
				double_padding = currentOpts.padding * 2,
				ratio;

			if (currentOpts.width.toString().indexOf('%') > -1) {
				to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10);
			} else {
				to.width = currentOpts.width + double_padding;
			}

			if (currentOpts.height.toString().indexOf('%') > -1) {
				to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10);
			} else {
				to.height = currentOpts.height + double_padding;
			}

			if (resize && (to.width > view[0] || to.height > view[1])) {
				if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
					ratio = (currentOpts.width ) / (currentOpts.height );

					if ((to.width ) > view[0]) {
						to.width = view[0];
						to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10);
					}

					if ((to.height) > view[1]) {
						to.height = view[1];
						to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10);
					}

				} else {
					to.width = Math.min(to.width, view[0]);
					to.height = Math.min(to.height, view[1]);
				}
			}

			to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10);
			to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10);

			return to;
		},

		_get_obj_pos = function(obj) {
			var pos = obj.offset();

			pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0;
			pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0;

			pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0;
			pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0;

			pos.width = obj.width();
			pos.height = obj.height();

			return pos;
		},

		_get_zoom_from = function() {
			var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
				from = {},
				pos,
				view;

			if (orig && orig.length) {
				pos = _get_obj_pos(orig);

				from = {
					width : pos.width + (currentOpts.padding * 2),
					height : pos.height + (currentOpts.padding * 2),
					top	: pos.top - currentOpts.padding - 20,
					left : pos.left - currentOpts.padding - 20
				};

			} else {
				view = _get_viewport();

				from = {
					width : currentOpts.padding * 2,
					height : currentOpts.padding * 2,
					top	: parseInt(view[3] + view[1] * 0.5, 10),
					left : parseInt(view[2] + view[0] * 0.5, 10)
				};
			}

			return from;
		},

		_animate_loading = function() {
			if (!loading.is(':visible')){
				clearInterval(loadingTimer);
				return;
			}

			$('div', loading).css('top', (loadingFrame * -40) + 'px');

			loadingFrame = (loadingFrame + 1) % 12;
		};

	/*
	 * Public methods 
	 */

	$.fn.fancybox = function(options) {
		if (!$(this).length) {
			return this;
		}

		$(this)
			.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
			.unbind('click.fb')
			.bind('click.fb', function(e) {
				e.preventDefault();

				if (busy) {
					return;
				}

				busy = true;

				$(this).blur();

				selectedArray = [];
				selectedIndex = 0;

				var rel = $(this).attr('rel') || '';

				if (!rel || rel == '' || rel === 'nofollow') {
					selectedArray.push(this);

				} else {
					selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
					selectedIndex = selectedArray.index( this );
				}

				_start();

				return;
			});

		return this;
	};

	$.fancybox = function(obj) {
		var opts;

		if (busy) {
			return;
		}

		busy = true;
		opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};

		selectedArray = [];
		selectedIndex = parseInt(opts.index, 10) || 0;

		if ($.isArray(obj)) {
			for (var i = 0, j = obj.length; i < j; i++) {
				if (typeof obj[i] == 'object') {
					$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
				} else {
					obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
				}
			}

			selectedArray = jQuery.merge(selectedArray, obj);

		} else {
			if (typeof obj == 'object') {
				$(obj).data('fancybox', $.extend({}, opts, obj));
			} else {
				obj = $({}).data('fancybox', $.extend({content : obj}, opts));
			}

			selectedArray.push(obj);
		}

		if (selectedIndex > selectedArray.length || selectedIndex < 0) {
			selectedIndex = 0;
		}

		_start();
	};

	$.fancybox.showActivity = function() {
		clearInterval(loadingTimer);

		loading.show();
		loadingTimer = setInterval(_animate_loading, 66);
	};

	$.fancybox.hideActivity = function() {
		loading.hide();
	};

	$.fancybox.next = function() {
		return $.fancybox.pos( currentIndex + 1);
	};

	$.fancybox.prev = function() {
		return $.fancybox.pos( currentIndex - 1);
	};

	$.fancybox.pos = function(pos) {
		if (busy) {
			return;
		}

		pos = parseInt(pos);

		selectedArray = currentArray;

		if (pos > -1 && pos < currentArray.length) {
			selectedIndex = pos;
			_start();

		} else if (currentOpts.cyclic && currentArray.length > 1) {
			selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1;
			_start();
		}

		return;
	};

	$.fancybox.cancel = function() {
		if (busy) {
			return;
		}

		busy = true;

		$.event.trigger('fancybox-cancel');

		_abort();

		selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);

		busy = false;
	};

	// Note: within an iframe use - parent.$.fancybox.close();
	$.fancybox.close = function() {
		if (busy || wrap.is(':hidden')) {
			return;
		}

		busy = true;

		if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
			busy = false;
			return;
		}

		_abort();

		$(close.add( nav_left ).add( nav_right )).hide();

		$(content.add( overlay )).unbind();

		$(window).unbind("resize.fb scroll.fb");
		$(document).unbind('keydown.fb');

		content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank');

		if (currentOpts.titlePosition !== 'inside') {
			title.empty();
		}

		wrap.stop();

		function _cleanup() {
			overlay.fadeOut('fast');

			title.empty().hide();
			wrap.hide();

			$.event.trigger('fancybox-cleanup');

			content.empty();

			currentOpts.onClosed(currentArray, currentIndex, currentOpts);

			currentArray = selectedOpts	= [];
			currentIndex = selectedIndex = 0;
			currentOpts = selectedOpts	= {};

			busy = false;
		}

		if (currentOpts.transitionOut == 'elastic') {
			start_pos = _get_zoom_from();

			var pos = wrap.position();

			final_pos = {
				top	 : pos.top ,
				left : pos.left,
				width :	wrap.width(),
				height : wrap.height()
			};

			if (currentOpts.opacity) {
				final_pos.opacity = 1;
			}

			title.empty().hide();

			fx.prop = 1;

			$(fx).animate({ prop: 0 }, {
				 duration : currentOpts.speedOut,
				 easing : currentOpts.easingOut,
				 step : _draw,
				 complete : _cleanup
			});

		} else {
			wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
		}
	};

	$.fancybox.resize = function() {
		if (overlay.is(':visible')) {
			overlay.css('height', $(document).height());
		}

		$.fancybox.center(true);
	};

	$.fancybox.center = function() {
		var view, align;

		if (busy) {
			return;	
		}

		align = arguments[0] === true ? 1 : 0;
		view = _get_viewport();

		if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) {
			return;	
		}

		wrap
			.stop()
			.animate({
				'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)),
				'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding))
			}, typeof arguments[0] == 'number' ? arguments[0] : 200);
	};

	$.fancybox.init = function() {
		if ($("#fancybox-wrap").length) {
			return;
		}

		$('body').append(
			tmp	= $('<div id="fancybox-tmp"></div>'),
			loading	= $('<div id="fancybox-loading"><div></div></div>'),
			overlay	= $('<div id="fancybox-overlay"></div>'),
			wrap = $('<div id="fancybox-wrap"></div>')
		);

		outer = $('<div id="fancybox-outer"></div>')
			.append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>')
			.appendTo( wrap );

		outer.append(
			content = $('<div id="fancybox-content"></div>'),
			close = $('<a id="fancybox-close"></a>'),
			title = $('<div id="fancybox-title"></div>'),

			nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
			nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
		);

		close.click($.fancybox.close);
		loading.click($.fancybox.cancel);

		nav_left.click(function(e) {
			e.preventDefault();
			$.fancybox.prev();
		});

		nav_right.click(function(e) {
			e.preventDefault();
			$.fancybox.next();
		});

		if ($.fn.mousewheel) {
			wrap.bind('mousewheel.fb', function(e, delta) {
				if (busy) {
					e.preventDefault();

				} else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) {
					e.preventDefault();
					$.fancybox[ delta > 0 ? 'prev' : 'next']();
				}
			});
		}

		if (!$.support.opacity) {
			wrap.addClass('fancybox-ie');
		}

		if (isIE6) {
			loading.addClass('fancybox-ie6');
			wrap.addClass('fancybox-ie6');

			$('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer);
		}
	};

	$.fn.fancybox.defaults = {
		padding : 10,
		margin : 40,
		opacity : false,
		modal : false,
		cyclic : false,
		scrolling : 'auto',	// 'auto', 'yes' or 'no'

		width : 560,
		height : 340,

		autoScale : true,
		autoDimensions : true,
		centerOnScroll : true,

		ajax : {},
		swf : { wmode: 'transparent' },

		hideOnOverlayClick : false,
		hideOnContentClick : false,

		overlayShow : true,
		overlayOpacity : 0.7,
		overlayColor : '#777',

		titleShow : true,
		titlePosition : 'float', // 'float', 'outside', 'inside' or 'over'
		titleFormat : null,
		titleFromAlt : false,

		transitionIn : 'fade', // 'elastic', 'fade' or 'none'
		transitionOut : 'fade', // 'elastic', 'fade' or 'none'

		speedIn : 300,
		speedOut : 300,

		changeSpeed : 300,
		changeFade : 'fast',

		easingIn : 'swing',
		easingOut : 'swing',

		showCloseButton	 : true,
		showNavArrows : true,
		enableEscapeButton : true,
		enableKeyboardNav : true,

		onStart : function(){},
		onCancel : function(){},
		onComplete : function(){},
		onCleanup : function(){},
		onClosed : function(){},
		onError : function(){}
	};

	$(document).ready(function() {
		$.fancybox.init();
	});

})(jQuery); 
  function BlurTxtFind(SearchText, txtFind)
  {
	if(txtFind.value=="")
	txtFind.value=SearchText.toString();
  }
			  
function FocusTxtFind(SearchText, txtFind)
  {
	if(txtFind.value==SearchText.toString())
		txtFind.value="";
  }
			  
function KeyPressGO(SearchText, txtFind,e)
  {				
	if(txtFind.value==SearchText.toString())
		txtFind.value="";
	
	var oBtn = getNextSibling(txtFind);
	//alert(oBtn);
	oBtn.focus();
	
	if(!e) 
		e = window.event; 
		
	if(e.keyCode==13)
	{
		find=txtFind.value;
		var strURL = "SearchOrders.aspx?find="+find;
		return NavOut(strURL,e); 
	}
	return true; 
  }
			  
function NavOut(strURL,event)
  {
	window.location = strURL; 
	
	if(typeof(event) != "undefined")
		event.preventDefault? event.preventDefault() : event.returnValue = false; 
	
	return false;
  }
			  
function GO(oImg,SearchText, txtFind)
  {
	oImg.parentNode.innerHTML="<span style='color:#FFFFFF'>" + GetTranslation('Please_wait') + "</span><img src='images/spinner.gif'/>";
	if(txtFind.value==SearchText.toString())
		txtFind.value="";
	find=txtFind.value;
	var strURL = "SearchOrders.aspx?find="+find; //+res
	return NavOut(strURL); 
 }
			  
function launchAbout() {
		window.location = 'about.htm';
}
			  
function BugReport(link)
  {
		window.location = link;
  } 
 function EditStaticText(oEditLink, EditAreaId,ToolBar) {

    var editAreaSelector = "#" + EditAreaId;

    //get the DIV that contains content to be edited    
    var oDIV = $(editAreaSelector + " > div[name=htmldiv]")[0];
    var strHTML = "";

    //alert($(editAreaSelector + " > div[name=htmldiv]").html());
    
    if($(editAreaSelector + " > span[name=DefaultHTML]").length > 0)
        strHTML = $(editAreaSelector + " > span[name=DefaultHTML]").html();
    else if ($(editAreaSelector + " > div[name=htmldiv] > textarea").length > 0)
        strHTML = $(editAreaSelector + " > div[name=htmldiv] > textarea").val();
    else
        strHTML = $(editAreaSelector + " > div[name=htmldiv]").html();

    //once we got HTML, save it as defaultHTML for later use with cancel link
    $(editAreaSelector + " > span[name=DefaultHTML]").html(strHTML);
        
    var strFCKTextAreaId = EditAreaId + "_fck";
    var thetext = document.createTextNode(strHTML);
    
    //dynamically create TEXTAREA with name & id and content of the div
    var textarea = document.createElement("textarea");
    textarea.setAttribute("id", strFCKTextAreaId);
    textarea.setAttribute("name", strFCKTextAreaId);
    textarea.setAttribute("btpswebtext", "1");
    textarea.style.display = "none";
    textarea.appendChild(thetext);
    
    oDIV.innerHTML = ""; //remove anything from DIV
    oDIV.appendChild(textarea); //append FCKTextarea

    //show cancel link, hide edit link
    $(editAreaSelector + " a[name=editLink]").hide();
    $(editAreaSelector + " a[name=cancelLink]").show();

    $.fck.config = { path: 'fckeditor/', 
                    height: 300,
                    AutoDetectLanguage : true
                   };
    $("#" + strFCKTextAreaId).fck({ toolbar: ToolBar });
}

function CancelEditStaticText(oEditLink, EditAreaId) {

    var editAreaSelector = "#" + EditAreaId;

    //hide cancel link, show edit link
    $(editAreaSelector + " a[name=editLink]").show();
    $(editAreaSelector + " a[name=cancelLink]").hide();
}

var gFCK = new Array();

function FCKeditor_OnComplete(editorInstance) {
    //called when FCKeditor instance loads
    if (null != editorInstance.LinkedField) {
        if ("1" == editorInstance.LinkedField.getAttribute("btpswebtext")) {
            if (editorInstance.LinkedField.form != null) {
                editorInstance.LinkedField.form.onsubmit = function() {
                    var strHTML = editorInstance.GetHTML();
                    var oDIV = editorInstance.LinkedField.parentNode;

                    var txtLabel = oDIV.getAttribute("label");
                    var txtGroup = oDIV.getAttribute("group");
                    var txtId = oDIV.getAttribute("objId");
                    var langId = oDIV.getAttribute("langId");

                    if (null == txtId)
                        txtId = "0";
                    if ("" == txtId)
                        txtId = "0";

                    var oText = { ID: txtId, Label: txtLabel, Group: txtGroup, HTML: strHTML }

                    var JSONparams = JSON.encode({ obj: oText });

                    //alert(JSONparams);

                    //call ajax
                    $.ajax({
                        type: "POST",
                        url: "svc/svcStaticTexts.aspx/UpdateInsert",
                        data: JSONparams,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(data, textStatus) {
                            var objId = eval(data);
                            oDIV.setAttribute("objId", objId.d);
                            oDIV.innerHTML = strHTML;

                            //destroy FCKEditor
                            //delete all inputs and iframes from div
                            $(oDIV).find("input, textarea, iframe").remove();

                            //hide cancel link, show edit link
                            $(oDIV).parent().find("a[name=editLink]").show();
                            $(oDIV).parent().find("a[name=cancelLink]").hide();

                            //reset form's onsubmit
                            document.forms[0].onsubmit = null; //may cause a problem if there are many forms in doc
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            var oException = null;
                            eval("oException = " + XMLHttpRequest.responseText);
                            if (null != oException)
                                if (typeof (oException.Message) != "undefined")
                                alert(Translate("ErrorOccured") + " " + oException.Message);
                        }
                    });

                    return false;
                }
            } //if (editorInstance.LinkedField.form != null)
        } //if ("1" == editorInstance.LinkedField.getAttribute("btpswebtext")) {
        else {
            gFCK[editorInstance.Name] = editorInstance;
        }
    }//if (null != editorInstance.LinkedField)
}
 
 //---------------------------------:Globals---------------------------------
var gSOAPListenerURL = "UserControls/ObjectFactory.aspx";
var gOrderTotal = 0;
var gOrderCompleted = 0;
var gTransactionTotal = 0; // fro qucik sale
var gQuickSaleMode = false;
var gSeasonLightningSeat = false;
var gSeasonRunId = null;
var gCurrentPerformanceId=0; // for HoldBlocks(function SetHolds) filled in SelectSeats.ascx
var gFunctionXmlHttpRequestAnisochronousComplite = null;
var checkoutway="2";
var isPatron=false;

var aryPayTypes = new Array();
var arrTickets  = new Array();
var arrTkPerTypes  = new Array();
var arrItems  = new Array();
var gOrder = new Array();

var formFocusTempVal;

var oParentIDHolder = new Object();

// mozilla fix for innerhtml usage
var gIsSafari = false;
if(/Safari/.test(navigator.userAgent))
	gIsSafari = true;

$(document).ready(function() {
    $("a.minimap_showmap").fancybox();
});
//------------------------------------------------------------------------

//---------------------------------:Right_Nav---------------------------------
function xlaTSlaunch(SQLSessionId,helpSiteUrl){
	xlaTSopenwindow('','','',SQLSessionId,helpSiteUrl);
}

function xlaTSopenwindow(faqid,topicid,question,SQLSessionId,helpSiteUrl){
if (document.all) {
	windowheight = screen.availHeight;
	windowwidth=screen.availWidth;
	rightwidth=300;
	leftwidth=screen.availWidth-rightwidth-11;
	TSwindow=window.open(helpSiteUrl + 'tsmain.aspx?topicid=' + topicid + '&faqid=' + faqid + '&question=' + question + SQLSessionId,'xlaTS','width='+rightwidth+',height='+windowheight+',screenX='+leftwidth+',screenY=0,top=0,left=' +leftwidth+',toolbar=0,location=0,status=1,menubar=0,resizable=1');
	TSwindow.focus();
	
	// Resize Current Window //
	top.resizeTo(leftwidth,windowheight);
	top.moveTo(0,0);
	top.focus();
	} else {
	TSwindow=window.open(helpSiteUrl + 'tsmain.aspx?topicid=' + topicid + '&faqid=' + faqid + '&question=' + question + SQLSessionId,'','width=300,height=480,toolbar=0,location=0,status=1,menubar=0,resizable=1');
	}
}

function xlaTSopentopic(what){
	xlaTSopenwindow('',what,'');
}

function xlaTSopenfaq(what){
	xlaTSopenwindow(what,'','');
}

function xlaTSsearch(what,topicid,selfpage,helpSiteUrl){
	if (selfpage==''){
	xlaTSopenwindow('',topicid,what);
	} else {
	self.location.href= helpSiteUrl + 'tsmain.aspx?topicid=' + topicid + '&question=' + what;
	}
}

function ConfirmEmptyCart(strDlgId)
{
	return modaldialogfromdiv(strDlgId, 280, "auto", false, GetTranslation("capl_please_confirm"), true);
}

function emptycart(strDlgId)
{
	$("#" + strDlgId).dialog("close");
	$("#" + strDlgId).hide();

	NavOut('EventsPage.aspx?RemoveAll=1');
}
//---------------------------------------------------------------------------

//---------------------------------:Navigate---------------------------------
var CanClick=true;

function NavigateMoveOver(oTR)
{
if(oTR.getAttribute('select')==null)
{
	oTR.style.backgroundColor='#D6D7DE'
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#16D7DE'
}
}

function NavigateMoveOut(oTR)
{
if(oTR.getAttribute('select')==null)
{
	oTR.style.backgroundColor='#ffffff';
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#D6DFFE';
}
}

function Goto(oTR,key,Id)
{
	 oTR.style.backgroundColor='#D6DFFE';
	 oTR.setAttribute('select','1');
	 window.location = "OrderActivity.aspx?"+key+"="+Id+"&fromrevid="+Id;
}

function NavigateMoveOverMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0099'
}
}

function NavigateMoveOutMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FFFFFF';
}
}


function NavigateMoveOverTabMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0000'
}
}

function NavigateMoveOutTabMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FFFFFF';
}
}

function NavigateMoveOverSubTabMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0000'
}
}

function NavigateMoveOutSubTabMenu(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FFFFFF';
}
else
{
	oDiv.style.color='#4A6E9B';
}
}

function NavigateMoveOutSection(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='blue';
}
}

function NavigateMoveOverSection(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0000'
}
}

function ShowMenu(oDiv,action)
{
	 oDiv.style.color='#FF0099';
	 oDiv.setAttribute('select','1');
	 if(action.indexOf("@")!=0) window.location = action;
	 else 
	 {
		 action = action.replace("@","");
		 //alert(action);
		 eval(action);
	 }
}
//------------------------------------------------------------------------

//---------------------------------:Currency---------------------------------
function CheckCurrency(val,id) {
    val = parseFloat(val);
	if (!isNaN(val)) {
		id.value = FormatCurrency(val,2);
	} else {
		id.value = formFocusTempVal;
	}
}

function FormatCurrency(data,acc) {
	data = parseFloat(data);
	if(isNaN(data))
		return "0.00";

  	data = data.toString();
  	if (data.indexOf(".") == -1){
  		data += ".00";
  	} else {
  		var decs = data.substr(data.indexOf(".")+1, data.length).length;
  		if (decs > acc) {
  			data = NumAccuracy(parseFloat(data),acc);
  		} else if (decs < acc) {
			for (d=1;d<=(acc-decs);d++) {
				data += "0";
			}
  		}
  	}
	return data;
}

function CheckAccount(obj,AccAmount)
{
 if ( parseFloat(obj.value)>parseFloat(AccAmount))
   {
		obj.value=AccAmount;
		alert('Your account balance is' +AccAmount+ ' $  \n You cannot exceed this limit when paying from your account.');
   }
}

function NumAccuracy(val,acc) {
 	if (isNaN(val)) {
		val = 0;
	} else {
		acc = Math.pow(10,acc);
		val = Math.round(val*acc)/acc;
	}
	return val;
}
//---------------------------------------------------------------------------


//---------------------------------:PackageList---------------------------------
function ShowHidePackage(oDIV)
{
	var Caption;
	var Description;
	if (isIE && !isMoz) Caption=oDIV.childNodes[0];
	else Caption=oDIV.childNodes[1];
	if (isIE && !isMoz) Description=oDIV.childNodes[1];
	else Description=oDIV.childNodes[3];
	//var Description=oDIV.childNodes[1];
	if(Caption.style.display=='block')
	{
	Caption.style.display='none';
	Description.style.display='block';
	}
	else
	{
	Caption.style.display='block';
	Description.style.display='none';
	}
}

function ShowByShowClick(spID,EventChoices)
{
	if(EventChoices!=0)
	{
		var arrChecbox=gEBN("checkboxList_"+spID);
		var iChoosen=0;
		for(var i=0;i<arrChecbox.length;i++) if(arrChecbox[i].checked) iChoosen++;
		if(iChoosen<EventChoices)
		{
			alert("You must select "+EventChoices+" events.");
			return;
		}
	}
	ShowProgressbar();
	var req = 'EventsPage.aspx?SpID='+spID;
	if(gEBI('PackageItem'+spID)!=null)
	{
	req+='&perflist='+gEBI('PackageItem'+spID).value;
	}
	req+='&SpMode=1';
	return NavOut(req);
}

function ChangeDwnSeasonPerformance(dpdwn,spID)
{
	var cperflist=gEBI('PackageItem'+spID);
	if(cperflist!=null)
	{
		var lWords = cperflist.value.split(";");
		var newperfList="";
		var lperfid=dpdwn.getAttribute('selperf');
		for(var i=0; i<lWords.length-1; i++)
		{
			if(lperfid!=lWords[i]) newperfList+=lWords[i]+';';
			else newperfList+=dpdwn.value+';';
		}
		cperflist.value=newperfList;
		dpdwn.setAttribute('selperf',dpdwn.value);
	}
}

function ChangeDefaultPrf(dpdwn)
{
	if(dpdwn.getAttribute('selperf')=='') dpdwn.setAttribute('selperf',dpdwn.value);
}

function ChangeAllSeasonEventsForPackage(oSelect, sSeasonPackageId)
{
	var oSeasonPerformances = oSelect.parentNode.parentNode;
	var oSelects = getChildrenByPartialIdOrName(oSeasonPerformances, "PerformancesPackagesInput", true)
	
	if(oSelects != null && oSelects.length > 1)	//if there are more than one performance lists
		if(oSelects[0].id == oSelect.id)		//if top one was changed
		{
			//check if all are selects.  if not we dont auto-change since its a mixed package
			var bMixed = false;
			for(var i = 1; i<oSelects.length; i++)
			{
				if(oSelects[i].options == null)
				{
					bMixed = true;
					break;
				}
			}
			if(!bMixed)  //if not mixed between single perfs and multi perfs autochange
			{
				for(var i = 1; i<oSelects.length; i++)
				{	//change all other performance lists to same index
					if(oSelects[i].options != null && oSelect.selectedIndex <= oSelects[i].options.length-1 )
					{
						oSelects[i].onclick();
						oSelects[i].selectedIndex = oSelect.selectedIndex;
						oSelects[i].onchange();
					}
				}
			}
		}
}

function SelectSeasonEvent(pChecbox,spevID,EventChoices,spID)
{
	if(pChecbox.checked)
	{
		var arrChecbox=gEBN("checkboxList_"+spID);
		var iChoosen=0;
		for(var i=0;i<arrChecbox.length;i++)
		{
			if(arrChecbox[i].checked) iChoosen++;
		}
		if(iChoosen>EventChoices) 
		{
			alert("You can choose only +"+EventChoices+" events!");
			pChecbox.checked = false;
			return;
		}
		gEBI('PackageItem'+spID).value += gEBI("PerformancesPackagesInput_"+spevID).value + ";";
	}
	else
	{
		var cperflist=gEBI('PackageItem'+spID);
		if(cperflist!=null)
		{
			var lWords = cperflist.value.split(";");
			var newperfList="";
			var lperfid=gEBI("PerformancesPackagesInput_"+spevID).value;
			for(var i=0; i<lWords.length-1; i++)
			{
				if(lperfid!=lWords[i]) newperfList+=lWords[i]+';';
			}
			cperflist.value=newperfList;
		}
	}
}

function OneClick(spID,EventChoices)
{
	if(EventChoices!=0)
	{
		var arrChecbox=gEBN("checkboxList_"+spID);
		var iChoosen=0;
		for(var i=0;i<arrChecbox.length;i++) if(arrChecbox[i].checked) iChoosen++;
		if(iChoosen<EventChoices)
		{
			alert("You must select "+EventChoices+" events.");
			return;
		}
	}
	ShowProgressbar();
	var req = 'EventsPage.aspx?SpID='+spID;
	if(gEBI('PackageItem'+spID)!=null)
	{
	req+='&perflist='+gEBI('PackageItem'+spID).value;
	}
	req+='&SpMode=2';
	return NavOut(req);
}

function Next_Season_Performace(spID, PerfId, EventChoices, strDlgId)
{	
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(arguments[2]!=null) var LayoutId=arguments[2];
	if(oInput==null) oInput=oDiv.childNodes[1];
	if(gEBI('MaxOrderedTickCount')!=null)
	{
		var MaxOrderedTickCount = gEBI('MaxOrderedTickCount').value;
		if(MaxOrderedTickCount!='') 
		{
			var lWords=oInput.value.split(";");	
			if(lWords.length-1!=MaxOrderedTickCount)// lWords.length-1 because there is a value 'st1;st2;' and its splist in 3 elements st1 st2 and empty string
			{
			alert("You must select "+MaxOrderedTickCount+" Seats!");
			return
			}
		}
	}
	ShowProgressbar();
	var countinblock=parseInt(oInput.getAttribute("InHoldBlock"));
	if(countinblock!=0)
	{
		modaldialogfromdiv(strDlgId, 280, "auto", false, GetTranslation("capl_please_confirm"), true);
	}
	else 
	{
		var req = 'EventsPage.aspx?SpID='+spID;
		req+='&SPerfId='+PerfId;
		req+='&SeatIds='+oInput.value;
		if(arguments[2]!=null) 
		{
			req+='&SLayID='+LayoutId;
			req+='&SpMode=2';
		}
			
		window.location=req;
	}
}

function Show_Next_Season_Performace(spID,PerfId) // for hold confirmation
{
	ShowProgressbar();
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var req = 'EventsPage.aspx?SpID='+spID;
	req+='&SPerfId='+PerfId;
	req+='&SeatIds='+oInput.value;
	if(arguments[2]!=null) 
		{
		var LayoutId=arguments[2];
		req+='&SLayID='+LayoutId;
		req+='&SpMode=2';
		}
	window.location=req;
}

function NavigateMoveOverSeasonPackage(oDiv)
{
	if(oDiv.getAttribute('select')==null)
	{
		oDiv.style.color='#FF0000'
	}
}

function NavigateMoveOutSeasonPackage(oDiv)
{
	if(oDiv.getAttribute('select')==null)
	{
		oDiv.style.color='#FFFFFF';
	}
}
//---------------------------------------------------------------------------


//---------------------------------:CategoryList---------------------------------
function ShowCategory(oDiv,CatID)
{
	 ShowProgressbar();
	 if(oDiv!=null)
	 {
		 oDiv.style.color='#FF0099';
		 oDiv.setAttribute('select','1');
	 }
	 var req='EventsPage.aspx?TabMenu=3&CatID='+CatID;
	 return NavOut(req);
}
//-------------------------------------------------------------------------------

//---------------------------------:KeyWordList---------------------------------
function ShowKeyWord(oDiv,KwdID)
{
	 ShowProgressbar();
	 if(oDiv!=null)
	 {
		 oDiv.style.color='#FF0099';
		 oDiv.setAttribute('select','1');
	 }
	 var req='EventsPage.aspx?TabMenu=1&KwdID='+KwdID;
	 return NavOut(req);
}
//-------------------------------------------------------------------------------

//---------------------------------:PerformanceCalendar---------------------------------
function ShowCalendarPerformances(m,y)
{
	ShowProgressbar();
	window.location = 'EventsPage.aspx?TabMenu=1&SubTabMenu=2&m='+m+'&y='+y;
}
//----------------------------------------------------------------------------------

//---------------------------------:Sections----------------------------------------
function ShowSection(oDiv, PerfID, SectionID)
{
	 ShowProgressbar();
	 $(oDiv).css("color", "#FF0099");
	 $(oDiv).attr("select", "1");
	 
	 var SeasonLink='';
	 if(arguments[4]!=null) 
		SeasonLink+=arguments[4];
	 if(arguments[5]!=null) 
		SeasonLink+=arguments[5];
		
	 window.location = 'EventsPage.aspx?MapType=1&PerfID='+PerfID+'&SectId='+SectionID+(arguments[3]!=null?'&AdmissionType='+arguments[3]:'')+SeasonLink;
	 
	 return false;
}

function GetScanSectionView(vPerformanceId,vSectionId)
{
	 window.location = 'EventsPage.aspx?MapType=2&PerfID='+vPerformanceId+'&SectId='+vSectionId;
}

function SelectSeats(oTD,SeatId, ticketId, vPerformanceId, bSoldSeatInformation)
{
	if(bSoldSeatInformation == null) bSoldSeatInformation = true;
	
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	var MaxOrderedTickCount = gEBI('MaxOrderedTickCount').value;
	if(oInput==null) oInput=oDiv.childNodes[1];
	if(oTD.getAttribute("hold") == "1")
	{
		var isW = false;
		if(typeof(isWeb) != "undefined")
			isW = isWeb;
	
		if(oTD.getAttribute("shopping_cart") == "1") 
			Ticket_In_Shopping_Cart(oTD,vPerformanceId,SeatId);
		else if(!isW && bSoldSeatInformation)
			BuildDivTicketDetails(oTD,ticketId, vPerformanceId, SeatId);
	}
	else
	{
	if(oTD.getAttribute("isSelected") == "0") {

	    if ($(oTD).attr('notifyid')) {
	        var sDlgId = "snNotify_" + $(oTD).attr('notifyid');
	        var oCloseFunction = null;
	        if ($(gEBI(sDlgId)).attr('snrepeat') && $(gEBI(sDlgId)).attr('snrepeat').toLowerCase() == 'false') {
	            //do not repeat message
	            oCloseFunction = function () { $( gEBI("snNotify_" + $(oTD).attr('notifyid'))).remove(); };
	        }
	        modaldialogfromdiv(sDlgId, 280, "auto", false, "Seat Notifcation", true, oCloseFunction, true);
	    }
		oTD.style.backgroundColor = gClientIncartColor;
		oTD.setAttribute("isSelected","1");
		if(oTD.getAttribute("InHoldBlock") == "1") 
		{
			var countinblock=parseInt(oInput.getAttribute("InHoldBlock"));
			countinblock++;
			oInput.setAttribute("InHoldBlock",countinblock);
		}
		if(oInput.value!="" && MaxOrderedTickCount!="")
		{
			var lWords = oInput.value.split(";");
			if(lWords.length-1==MaxOrderedTickCount)// lWords.length-1 because there is a value 'st1;st2;' and its splist in 3 elements st1 st2 and empty string
			{
			var newSeat='';
			for(var i=1; i<lWords.length-1; i++)
			{
				if(SeatId!=lWords[i]) newSeat+=lWords[i]+';';
			}
			oInput.value= newSeat;
			
			gEBI(lWords[0]).style.backgroundColor = oTD.getAttribute("defCol")!=null?oTD.getAttribute("defCol"):'';
			gEBI(lWords[0]).setAttribute("isSelected","0");
			}
		}
		oInput.value += SeatId+';';
	}
	else
	{
		oTD.style.backgroundColor = oTD.getAttribute("defCol")!=null?oTD.getAttribute("defCol"):'';
		oTD.setAttribute("isSelected","0");
		var lWords = oInput.value.split(";");
		var newSeat='';
		for(var i=0; i<lWords.length-1; i++)
		{
			if(SeatId!=lWords[i]) newSeat+=lWords[i]+';';
		}
		if(oTD.getAttribute("InHoldBlock") == "1") 
		{
			var countinblock=parseInt(oInput.getAttribute("InHoldBlock"));
			countinblock--;
			oInput.setAttribute("InHoldBlock",countinblock);
		}
		oInput.value= newSeat;
	}
	CloseDivTicketDetails();
	}
	var oLImg = getChildByIdOrName(oTD, "large");
	var oSImg = getChildByIdOrName(oTD, "small");
	if(oSImg != null && oSImg.getAttribute("imagetype") == 'graphic')
		{
			InvertObjectVisibility(oLImg);
			InvertObjectVisibility(oSImg);
		}
	$("#divCountOfSelectedSeats").html( oInput.value.split(";").length-1 );
}

function CheckForOrphanSeats(oSeat, bSelect)
{
	//get surrounding seats (2 on each side)
	var oSeatR1 = oSeat.nextSibling;
	var oSeatL1 = oSeat.previousSibling;
	var oSeatR2 = (oSeatR1 != null)?oSeatR1.nextSibling:null;
	var oSeatL2 = (oSeatL1 != null)?oSeatL1.previousSibling:null;
	
	var R1Open = (oSeatR1!=null)?( oSeatR1.getAttribute("hold") == null?false:(oSeatR1.getAttribute("hold") != 1) ) : false;
	var R2Open = (oSeatR2!=null)?( oSeatR2.getAttribute("hold") == null?false:(oSeatR2.getAttribute("hold") != 1) ) : false;
	var L1Open = (oSeatL1!=null)?( oSeatL1.getAttribute("hold") == null?false:(oSeatL1.getAttribute("hold") != 1) ): false;
	var L2Open = (oSeatL2!=null)?( oSeatL2.getAttribute("hold") == null?false:(oSeatL2.getAttribute("hold") != 1) ): false;
	
	var R1Sel = (oSeatR1!=null)?oSeatR1.getAttribute("isSelected") == 1:false;
	var R2Sel = (oSeatR2!=null)?oSeatR2.getAttribute("isSelected") == 1:false;
	var L1Sel = (oSeatL1!=null)?oSeatL1.getAttribute("isSelected") == 1:false;
	var L2Sel = (oSeatL2!=null)?oSeatL2.getAttribute("isSelected") == 1:false;
	
	var bOrphan = false;
	
	if(bSelect)
	{
		if((R1Open && !R1Sel) && (!R2Open || R2Sel))
			bOrphan = true;

		if((L1Open && !L1Sel) && (!L2Open || L2Sel))
			bOrphan = true;
	}
	else
	{
		if((!R1Open || R1Sel) && (!L1Open || L1Sel))
			bOrphan = true;
	}
		
	return bOrphan;
}

function OrphanCheck(oInputSeats)
{
	if(isWeb == true && window.location.href.indexOf("PerfID=107783") > 0)
	{
		//do orphan check
		var arrSelSeatIds = oInputSeats.value.split(";")
		for(var i=0; i < arrSelSeatIds.length; i++)
		{
			var oSeat = gEBI(arrSelSeatIds[i]);
			if(oSeat != null)
				{
				var bOrphan = CheckForOrphanSeats(oSeat, true)
				if(bOrphan)
				{
					alert("Invalid selection.  Your selection would result in orphaned seats.  Please choose seats that do not leave single open seats.")
					return false;
				}
			}
		}
	}
	
	return true;
}

function TryEnterShopingCart(strAddToScButtonId, spID, strDlgId)
{
	$("#CartButtonClicked").val(strAddToScButtonId);

	var jsInputSeats = $("#divSeatsIds > input");
	var oInputSeats = jsInputSeats[0];
	
	if("" == jQuery.trim( jsInputSeats.val() ))
	{
		alert("No seats selected");
		return false;
	}
	
	//if(!OrphanCheck(oInputSeats)) 
	//	return false;
	
	
	if(gEBI('MaxOrderedTickCount')!=null)
	{
		var MaxOrderedTickCount = gEBI('MaxOrderedTickCount').value;
		if(MaxOrderedTickCount!='') 
		{
			var lWords=oInputSeats.value.split(";");	
			if(lWords.length-1>MaxOrderedTickCount) // lWords.length-1 because there is a value 'st1;st2;' and its splist in 3 elements st1 st2 and empty string
			{
			alert("You must select "+MaxOrderedTickCount+" Seats!");
			return
			}
		}
	}
	var countinblock=parseInt(oInputSeats.getAttribute("InHoldBlock"));
	if(countinblock!=0) 
	{
		modaldialogfromdiv(strDlgId, 280, "auto", false, GetTranslation("capl_please_confirm"), true);
	}
	else 
	{
		ShowProgressbar();
		
		$("#" + strAddToScButtonId)[0].click();
	}
	
	return false;
}

function TryEnterBestAvailable(oInputID)
{
	ShowProgressbar();
	gEBI(oInputID).click();
}
	  
function AddToCartBASeats(pButtonID,pSelect,pInput)
{
	var count = pSelect!=null? pSelect.value:pInput.value;
	
	count = parseInt(count);
    if(isNaN(count) || count <= 0)
	{
		alert("Please Select a total of seats.");
		return;
	}
 
    ShowProgressbar();

	gEBI(pButtonID).click();

}	  
	  
function FocusTxtBA(txtFind)
  {
	txtFind.select();
  }
			  
function KeyPressBA(e)
{
	if(!e) 
		e = window.event;

	if(e.keyCode==13)
	{
		gEBI('AddBestAvailablebtn').click();
	}
	return true;
}
  
function SetDefault_Performance(oCheck,PrfID,ClId)
{		 
	if(oCheck.checked)
	{
		SetCookie(ClId+"DefPrf", PrfID, null, "/");
	}
	else
	{
		DeleteCookie(ClId+"DefPrf","/");
	}
}

function SetDefault_Section(oCheck,PrfID,SectID,ClId)
{
	if(oCheck.checked)
	{
		SetCookie(ClId+"DefPrf", PrfID, null, "/");
		SetCookie(ClId+"DefSect", SectID, null, "/");
	}
	else
	{
		DeleteCookie(ClId+"DefPrf","/");
		DeleteCookie(ClId+"DefSect","/");
	}
}

function SetDefault_Tab(oCheck,ClId)
{		 
	if(oCheck.checked)
	{
		SetCookie(ClId+"Sales_ShowTab", 4, null, "/");
	}
	else
	{
		DeleteCookie(ClId+"Sales_ShowTab","/");
	}
}

function ShowMapInPopUp(MAPsrc)
{
	if($('#MapPopUp').length==0)
	{
		var MapPopUp=document.createElement("div");
		MapPopUp.id = "MapPopUp";
		MapPopUp.style.display="none";
		document.body.appendChild(MapPopUp);
	     $('#MapPopUp').dialog(
				{
				    modal: true,
				    resizable: true,
				    draggable: true,
				    autoOpen: false,
				    width: 800,
				    height: 600,
				    overlay: {
				        opacity: 0.5,
				        background: "black"
				    }
				}
			);
		$("#MapPopUp").show();
		$("#MapPopUp").dialog("open");	
		$("#MapPopUp")[0].innerHTML="<img src='"+MAPsrc+"'/>";	
	}
	else
	{
		$("#MapPopUp").show();
		$("#MapPopUp").dialog("open");
		$("#MapPopUp")[0].innerHTML="<img src='"+MAPsrc+"'/>";	
	}
	return false;
}
//----------------------------------------------------------------------------------

//---------------------------------:GASections--------------------------------------
function GetGASeats(InputId)
{
	var oInput=gEBI(InputId);
	if(oInput==null) 
	{
	InputId=InputId.replace("_","$");
	oInput=gEBI(InputId);
	}
	var oGAQuants = gEBI('GAQuantity');
	var oQuants = getChildrenByPartialIdOrName(oGAQuants, 'gapol', true);
	var Limit = -1;
	if(arguments[1]!=null) var spID=arguments[1];
	if(arguments[2]!=null) var PerfId=arguments[2];
	if(arguments[3]!=null) var LayoutId=arguments[3];
	var count = 0;
	for(var i=0; i<oQuants.length; i++)
	{
	  Limit=-1;
	  if(oQuants[i].getAttribute('limit') != null) Limit = parseInt(oQuants[i].getAttribute('limit'));
	  if(Limit <= 0 && oQuants[i].value!='' && oQuants[i].value>0 )
		   {
				alert("There are no more seats available, please choose seats for a different section or performance");
				oInput.value = "";
				return false;
		   }          
	  for(var j=parseInt(oQuants[i].value); j>0; j--)
	  {
		   //if past limit break;
		   if(Limit != -1 && count >= Limit)
				break;
		   count++;
		   oInput.value  += oQuants[i].getAttribute('seatid') + "," + oQuants[i].getAttribute('ttid') + "," + Limit + "," + oQuants[i].getAttribute('sectionid') + ";";
	  }
	}
	
	if(gEBI('MaxOrderedTickCount')!=null)
	{
		var MaxOrderedTickCount = gEBI('MaxOrderedTickCount').value;
		if(MaxOrderedTickCount!='') 
		{
			if(count!=MaxOrderedTickCount)
			{
			alert("You must select "+MaxOrderedTickCount+" Seats!");
			oInput.value="";
			return
			}
		}
	}
    
    //user must choose at least 1 ga seat
    if(count == 0)
    {
		alert("Please enter a valid quantity for the number of tickets you wish to request.")
		return false;
    }
	if(arguments[1]!=null && arguments[2]!=null)
	{
		ShowProgressbar();
		var oDiv=gEBI('divSeatsIds');
		var req = 'EventsPage.aspx?SpID='+spID;
		req+='&SPerfId='+PerfId;
		req+='&SeatGAIds='+oInput.value;
		if(arguments[3]!=null) 
		{
		req+='&SLayID='+LayoutId;
		req+='&SpMode=2';
		}
		window.location=req;
	}
	else
	{
		ShowProgressbar();
		DoPostBack();
	}
}
//----------------------------------------------------------------------------------

//---------------------------------:DonationList----------------------------------------
function ChangeDonationAmount(pSelect,DID)
{
	gEBI('DonationPrice_'+DID).value=pSelect.options[pSelect.selectedIndex].getAttribute('max_amount');
	gEBI('DonationsChk_'+DID).checked=true;
	gEBI('DonationLevelID_'+DID).value=pSelect.options[pSelect.selectedIndex].getAttribute('levelid');
	gEBI('DonationLevelMaxAmount_'+DID).value=pSelect.options[pSelect.selectedIndex].getAttribute('max_amount');	
	gEBI('DonationLevelAFA_'+DID).value=pSelect.options[pSelect.selectedIndex].getAttribute('AFA')=='true'?'1':'0';			
}

function DonationAmountChanged(pInput,DID)
{
	if(gEBI('DonationLevel_'+DID)!=null)
	{
		var curAmount=parseFloat(pInput.value);
		if(parseFloat(gEBI('DonationLevel_'+DID).value)>curAmount)
			pInput.value=gEBI('DonationLevel_'+DID).value;
		if(curAmount>parseFloat(gEBI('DonationLevelMaxAmount_'+DID).value) && gEBI('DonationLevelAFA_'+DID).value=='1')
			{
				var lSelect=gEBI('DonationLevel_'+DID);
				for(var i=0;i<lSelect.options.length;i++)
				{
					if(curAmount>=parseFloat(lSelect.options[i].getAttribute('value')) && curAmount<=parseFloat(lSelect.options[i].getAttribute('max_amount')))
					{
						lSelect.options[i].selected=true;
						gEBI('DonationLevelID_'+DID).value=lSelect.options[i].getAttribute('levelid');
						gEBI('DonationLevelMaxAmount_'+DID).value=lSelect.options[i].getAttribute('max_amount');		
						break;
					}
				}
			}
		else if(curAmount>parseFloat(gEBI('DonationLevelMaxAmount_'+DID).value) && gEBI('DonationLevelAFA_'+DID).value=='0')
			{
				pInput.value=gEBI('DonationLevelMaxAmount_'+DID).value;
			}
	}	
	gEBI('DonationsChk_'+DID).checked=true;
}

function UnselectOtherDonations(DID)
{
	var arrchk=gEBN('DonationsChk');
	for(var i=0;i<arrchk.length;i++)
	{
		arrchk[i].checked=false;
	}
	gEBI('DonationsChk_'+DID).checked=true;
}
//--------------------------------------------------------------------------------------

//---------------------------------:ItemList----------------------------------------
function IncrementItem(oImg,oTR,MinValue)
{
	if(oTR!=null) oImg.style.backgroundColor="blue";
	else oTR=oImg;

	var oInput=oTR.cells[3].childNodes[0];
	if(oInput.nodeType!= 1) oInput=getNextSibling(oInput);
	
	var oInput=oInput.rows[0].cells[1].childNodes[0];
	if(oInput.nodeType!= 1) oInput=getNextSibling(oInput);

	var value=oInput.value;
	if(value=='') 
	{
	if(MinValue!=null && MinValue!=0) value=MinValue;
	else value=1;
	}
	else value++;
	oInput.value=value;
	if(oTR!=oImg) oImg.style.backgroundColor="";
}

function DecrementItem(oTR,MinValue)
{
	//alert("DecrementItem" + String(oTR.cells.length-1) );
	
	var oInput=oTR.cells[oTR.cells.length-1].childNodes[0];
	if(oInput.nodeType!= 1) oInput=getNextSibling(oInput);
	
	//alert("DecrementItem 2");
	
	var oInput=oInput.rows[0].cells[1].childNodes[0];
	if(oInput.nodeType!= 1) oInput=getNextSibling(oInput);
	
	var value=oInput.value;
	
	//alert("DecrementItem 3 " + value);
	
	if((MinValue!=null && MinValue!=0 && value<=MinValue) || value=='1' || value=='' || value=='0') 
		value='';
	else 
		value--;
	
	//alert("DecrementItem 4 " + value);
	
	oInput.value=value;
	canInrement=false;
}

function MinItem(pInput,MinValue)
{
	if(MinValue!=0)	
	{
		var value=pInput.value;
		if(value!='' && value!='0' && value<MinValue) value=MinValue;
		pInput.value=value;
	}
}

function ChangeItem(oTR,event,MinValue)
{
	if(event==null) event=window.event;
	if (event.button==2) DecrementItem(oTR,MinValue);
	else IncrementItem(oTR,null,MinValue);
}

function ChangeDonation(oTR)
{
	var oInput=oTR.cells[0].childNodes[0];
	if(oInput.nodeType!= 1) oInput=getNextSibling(oInput);
	oInput.checked=!oInput.checked;
}


function NavigateMoveOverItem(oTR)
{
if(oTR.getAttribute('select')==null)
{
	oTR.style.backgroundColor='#D6D7DE'
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#16D7DE'
}
}

function NavigateMoveOutItem(oTR)
{
if(oTR.getAttribute('select')==null)
{
	if(oTR.className=='gridCell light') oTR.style.backgroundColor='#E8EDF3';
	else oTR.style.backgroundColor='#F5F5F5';
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#D6DFFE';
}
}

function ProcessItems()
{	
	ShowProgressbar();
	DoPostBack();
}

function checkDonation(oThis,Ordinal)
{	
	var hItemOrder =gEBI('hItemOrder_'+Ordinal);
	if(isNaN(parseFloat(oThis.value)) || parseFloat(oThis.value) < 0)
	{
		oThis.value = hItemOrder.getAttribute('ListPrice');
		return;
	}
	var lSelect =gEBI('selItemOrderDonationLevel_'+Ordinal);
	if(lSelect!=null)
	{
		var lDonationLevelMin = lSelect.value;
		var lDonationLevelMax = lSelect.options[lSelect.selectedIndex].getAttribute('max_amount');
		var lDonationLevelAllowOverFillAmount = lSelect.options[lSelect.selectedIndex].getAttribute('AFA');
		var curAmount=parseFloat(oThis.value);
		if(curAmount<parseFloat(lDonationLevelMin))
			oThis.value=lDonationLevelMin;
		if(curAmount>parseFloat(lDonationLevelMax))
			{
				if(lDonationLevelAllowOverFillAmount=='true')
				{
					for(var i=0;i<lSelect.options.length;i++)
					{
						if(curAmount>=parseFloat(lSelect.options[i].getAttribute('value')) && curAmount<=parseFloat(lSelect.options[i].getAttribute('max_amount')))
						{
							lSelect.options[i].selected=true;
							hItemOrder.setAttribute('DonationLevelID',lSelect.options[i].getAttribute('levelid'));						
							break;
						}
					}
				}
				else
				{
					oThis.value=lDonationLevelMax;
				}
			}
			
	}


	oThis.value = parseFloat(oThis.value).toFixed(2);
	hItemOrder.setAttribute('ListPrice',oThis.value);
	
	updateTotals();
}


function ChangeDonationLevel(oThis,Ordinal)
{	
	var hItemOrder =gEBI('hItemOrder_'+Ordinal);
	var IItemOrderPrice = gEBI('txtItemOrderPrice_'+Ordinal);
	IItemOrderPrice.value=parseFloat(oThis.value).toFixed(2);

	hItemOrder.setAttribute('ListPrice',IItemOrderPrice.value);
	hItemOrder.setAttribute('DonationLevelID',oThis.options[oThis.selectedIndex].getAttribute('levelid'));
	
	updateTotals();
}

function checkPledge(oThis,hItemOrder,ItemID)
{	
	if(isNaN(parseFloat(oThis.value)) || parseFloat(oThis.value) < 0)
	{
		oThis.value = hItemOrder.getAttribute('ListPrice');
		return;
	}
	oThis.value = parseFloat(oThis.value).toFixed(2);
	hItemOrder.setAttribute('Pledge',oThis.value);
}
function InspectMinQty(pInput,pobjInput,MinValue)
{
	if(MinValue!=0)	
	{
		var value=pInput.value;
		if(value!=''&& value!='0' && value<MinValue) value=MinValue;
		pInput.value=value;
	}
	pobjInput.setAttribute('Quantity',pInput.value)
}
//------------------------------------------------------------------------

//---------------------------------:HoldManager---------------------------------
function SetColor(oTD)
{
	var SampleTD=gEBI("HoldSampleDiv");
	SampleTD.style.backgroundColor=oTD.getAttribute("value");
	SampleTD.setAttribute("value",oTD.getAttribute("value"));
	SampleTD.style.color=InverseColor(oTD.getAttribute("value"));	
	SetCustomHoldBlock();
}

function More_colorsOver(oSpan)
{
	oSpan.style.color='#000000';
}

function More_colorsOut(oSpan)
{
	oSpan.style.color='Gray';
}

function UpdateHoldSymbol(oInput)
{
	var SampleTD=gEBI("HoldSampleDiv");
	SampleTD.innerText=oInput.value.toUpperCase();
	SetCustomHoldBlock();
}

function SetCustomHoldBlock()
{
	var Hold_Blocks_select= gEBI('HoldBlocks');
	for(var i=0;i<Hold_Blocks_select.options.length;i++)
		{
			if(Hold_Blocks_select.options[i].value=='0')
				{
					Hold_Blocks_select.options[i].selected=true;
					break;
				}
		}
}

function ChangeHoldBlock(oSelect)
{
	var PropStr = oSelect.value;
	if(PropArray!='0')
	{
		var PropArray = PropStr.split('|');
		var Hold_types_select= gEBI('HoldTypes');
		for(var i=0;i<Hold_types_select.options.length;i++)
		{
			if(Hold_types_select.options[i].value==PropArray[0])
				{
					Hold_types_select.options[i].selected=true;
					break;
				}
		}
		
		//check for undefined values (mainly on custom option)
		PropArray[1] = (PropArray[1] == undefined)?"":PropArray[1];
		PropArray[2] = (PropArray[2] == undefined)?"":PropArray[2];
		PropArray[3] = (PropArray[3] == undefined)?"#ffffff":PropArray[3];
		
		gEBI('HoldSymbol').value=PropArray[2];
		gEBI("HoldSampleDiv").innerText=PropArray[2];
		//UpdateHoldSymbol(gEBI('HoldSymbol'));
		gEBI('HoldName').value=PropArray[1];
		gEBI("HoldSampleDiv").style.backgroundColor=PropArray[3];
		gEBI("HoldSampleDiv").style.color=InverseColor(PropArray[3]);	
		gEBI("HoldSampleDiv").setAttribute("value",PropArray[3]);
	}
}

function SetHolds(oSpan,sPerfList)
{
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsId_sstr;
	if(arguments[2]!=null && arguments[3]!=null) 
	{
		SeatsId_sstr=arguments[2];
		var currentRequest= arguments[3];
	}
	var CountPerRequest=8000; // the max seatsIds length what will be transfer during one request (ex varchar - 8000)
	
	if("" == SeatsIdsstr)
		return;
	

	if(SeatsIdsstr.length>CountPerRequest && arguments[2]==null) SeatsId_sstr=PartialSeatString(SeatsIdsstr,0,CountPerRequest/8);
	else if(arguments[2]==null) SeatsId_sstr = SeatsIdsstr;	
	//build xml for HoldBlock
	var PropStr= gEBI('HoldBlocks').value;	
	var HoldBlockXML = "";
	if(PropStr=='0') // custom
		{
			HoldBlockXML = "<HoldBlock>";
			HoldBlockXML += "<HoldType><ID>"+gEBI('HoldTypes').value+"</ID></HoldType>";
			HoldBlockXML += "<HoldColor>"+gEBI('HoldSampleDiv').getAttribute("value")+"</HoldColor>";
			HoldBlockXML += "<DisplayCharacter>"+gEBI('HoldSymbol').value+"</DisplayCharacter>";
			HoldBlockXML += "<Name>"+gEBI('HoldName').value+"</Name>";
			HoldBlockXML += "</HoldBlock>";
		}
	else //not custom(only ID is needed)
		{
			var PropArray = PropStr.split('|');
			HoldBlockXML = "<HoldBlock><ID>"+PropArray[4]+"</ID></HoldBlock>";
		}
	

	//build xml for performances
	var xPerfList="";
    if(sPerfList=="") xPerfList = "<param type=\"Performance\"><Performance><ID>" + gCurrentPerformanceId + "</ID></Performance></param>";
	else xPerfList= "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
		
	//build request XML
	var strRequestXML = "<envelope><body>" +
						"<command name=\"InsertSingleHolds\">" +
						"<class name=\"" + 'HoldBlocks' + "\" />";

	strRequestXML += "<param type=\"" + "HoldBlock" + "\">" + HoldBlockXML + "</param>";
	
	strRequestXML += xPerfList;

	strRequestXML += "<param type=\"System.String\"><string>" + SeatsId_sstr + "</string></param>"; 
	strRequestXML += 	"</command>" +
						"<xslt>BuyTickets.xslt</xslt>" +
						"</body></envelope>";

	if(arguments[2]==null) ShowProgressbar();
	if(SeatsIdsstr.length>CountPerRequest && SeatsId_sstr.split(';').length==CountPerRequest/8+1)
	{
		if(arguments[3]==null) var currentRequest= 1; 
		else currentRequest++;
		SeatsId_sstr=PartialSeatString(SeatsIdsstr,currentRequest,CountPerRequest/8);
		
		if(SeatsId_sstr!="") 
		{
			$.post(gSOAPListenerURL, strRequestXML, function(data){
				SetHolds(oSpan, sPerfList, SeatsId_sstr, currentRequest);
			});	
			return;
		}
	}
	
	$.post(gSOAPListenerURL, strRequestXML, function(data){
		FillHoldsOnMap(data);
	});	
}

function ReleaseHolds(oSpan,sPerfList)
{
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsId_sstr;
	if(arguments[2]!=null && arguments[3]!=null) 
	{
		SeatsId_sstr=arguments[2];
		var currentRequest= arguments[3];
	}
	var CountPerRequest=8000; // the max seatsIds length what will be transfer during one request (ex varchar - 8000)
	
	if("" == SeatsIdsstr)
		return;
	

	if(SeatsIdsstr.length>CountPerRequest && arguments[2]==null) SeatsId_sstr=PartialSeatString(SeatsIdsstr,0,CountPerRequest/8);
	else if(arguments[2]==null) SeatsId_sstr = SeatsIdsstr;	
	//build xml for performances
	var xPerfList="";
    if(sPerfList=="") xPerfList = "<param type=\"Performance\"><Performance><ID>" + gCurrentPerformanceId + "</ID></Performance></param>";
	else xPerfList= "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
			
	//build request XML
	var strRequestXML = "<envelope><body>" +
						"<command name=\"Release\">" +
						"<class name=\"" + 'Holds' + "\" />";

	strRequestXML += xPerfList;

	strRequestXML += "<param type=\"System.String\"><string>" + SeatsId_sstr + "</string></param>"; 
	strRequestXML += 	"</command>" +
						"<xslt>BuyTickets.xslt</xslt>" +
						"</body></envelope>";

	if(arguments[2]==null) ShowProgressbar();
	if(SeatsIdsstr.length>CountPerRequest && SeatsId_sstr.split(';').length==CountPerRequest/8+1)
	{
		if(arguments[3]==null) var currentRequest= 1; 
		else currentRequest++;
		SeatsId_sstr=PartialSeatString(SeatsIdsstr,currentRequest,CountPerRequest/8);
		
		if(SeatsId_sstr!="") 
		{
			$.post(gSOAPListenerURL, strRequestXML, function(data){
				ReleaseHolds(oSpan, sPerfList, SeatsId_sstr, currentRequest);
			});	
			return;
		}
	}
	
	$.post(gSOAPListenerURL, strRequestXML, function(data){
		ReleaseHoldsOnMap(data);
	});	
}

function ReleaseHoldsOnMap(strResp)
{
	if( strResp == "") 
	{
	return false;
	ShowProgressbar();
	}
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsIds = oInput.value.split(';');
	for(var i = 0; i < SeatsIds.length; i++)
	{
		//test if the seatids are preceeded with 'st'
		var strSeatId = SeatsIds[i];
		if(SeatsIds[i]=="") continue;
		var oTD = document.getElementById(strSeatId);

		//get holds form inputs
		oColor = oTD.getAttribute("defCol");
		if(oColor==null) oColor = oTD.getAttribute("POLvlColor");
		oTD.setAttribute("defCol",oColor);
		oTD.style.backgroundColor = oColor;
		oTD.setAttribute("isSelected","0");
		//oTD.setAttribute("hold", "1");

		//change display character
		var oTextDiv = getChildByTagName(oTD, "DIV")
		if(oTextDiv != null)
		{
			oTextDiv.innerHTML = "";
		}
	}
	oInput.value="";
	ShowProgressbar();
}

function FillHoldsOnMap(strResp,sOrderId)
{
	if( strResp == "") 
	{
	return false;
	ShowProgressbar();
	}
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsIds = oInput.value.split(';');
	for(var i = 0; i < SeatsIds.length; i++)
	{		
		//test if the seatids are preceeded with 'st'
		var strSeatId = SeatsIds[i];
		if(SeatsIds[i]=="") continue;
		var oTD = document.getElementById(strSeatId);

		//get holds form inputs
		oColor = gEBI('HoldSampleDiv').getAttribute("value");
		oCharInput = gEBI('HoldSymbol').value;

		oTD.setAttribute("isSelected","0");
		oTD.style.backgroundColor = oTD.getAttribute("defCol")!=null?oTD.getAttribute("defCol"):'';
		oTD.setAttribute("defCol",getStyle(oTD,"background-color"));
		oTD.setAttribute("POLvlColor", getStyle(oTD,"background-color"));		
		oTD.style.backgroundColor = oColor;
		oTD.style.color=InverseColor(oColor);	
		//oTD.setAttribute("hold", "1");

		//change display character
		var oTextDiv = getChildByTagName(oTD, "DIV")
		if(oTextDiv != null)
		{
			oTextDiv.innerHTML = oCharInput;

			oTD.style.fontSize = "10px";
		}
	}
	oInput.value="";
	ShowProgressbar();
}


function HexToR(h) {
 return parseInt((cutHex(h)).substring(0,2),16)
}
function HexToG(h) {
 return parseInt((cutHex(h)).substring(2,4),16)
}
function HexToB(h) {
 return parseInt((cutHex(h)).substring(4,6),16)
}
function cutHex(h) {
 return (h.charAt(0)=="#") ? h.substring(1,7) : h
}


var hexbase = "0123456789ABCDEFabcdef";
function DecToHex(number) {
 return hexbase.charAt((number>> 4)& 0xf)+ hexbase.charAt(number& 0xf);
}

function InverseColor(strColor) {
 var r = 255 - HexToR(strColor);
 var g = 255 - HexToG(strColor);
 var b = 255 - HexToB(strColor);

 var ans = "#"+DecToHex(r).toString()+DecToHex(g).toString()+DecToHex(b).toString();
 return ans;
}
//------------------------------------------------------------------------

//----------------------:Quick_Sales-------------------------------------
function ShowHideQuickSales_Bar(ClId)
{
    var PerfID=GetCookie(ClId+'QSPerformance','/');
    if (PerfID != null)
        return NavOut('EventsPage.aspx?PerfID=' + PerfID + '&QuickSales=1');

    $("#QuickSales_Bar").toggle();
    return false;
}

function onQuickSaleAddToCart(PerfID,PolvlId,TicketTypeId,TicketCount,DeliveryMethodID,PaymentTypeID,SpanRows)
{
	if(TicketCount!=''&&TicketCount>0)
	{
		ShowProgressbar();
		window.location = "EventsPage.aspx?PerfID="+PerfID+"&PolvlId="+PolvlId+"&TicketTypeId="+TicketTypeId+"&DeliveryMethodID="+DeliveryMethodID+"&PaymentTypeID="+PaymentTypeID+"&TicketCount="+TicketCount+"&spanRows="+SpanRows;
	}
	else alert("Please fill the correct Quantity!");
}

//------------------------------------------------------------------------

function ChangeCountTicketsPerEvent(pTextBox)
{
	var lEvtID = pTextBox.getAttribute("EventID");
	var lArrTxtTicketDiscount = gEBN("txtTicketDiscount"+lEvtID);
	if(0 == lArrTxtTicketDiscount.length) return;
	
	var lOldCountTix = Number(pTextBox.getAttribute("QuantityF"));
	var lCountTix = Number(pTextBox.value);

	var lCntTicketsPerEvent = Number(lArrTxtTicketDiscount[0].getAttribute("cntTicketsPerEvent"))+(lCountTix-lOldCountTix);
	for(var i=0; i<lArrTxtTicketDiscount.length; i++)
	{
		lArrTxtTicketDiscount[i].setAttribute("cntTicketsPerEvent", lCntTicketsPerEvent);
	}
}

function DeleteAll() {
    window.onbeforeunload = null;
    var lRedirectUrl = 'EventsPage.aspx?TabMenu=5&RemoveAll=2';
    if ('string' == typeof(G_DeleteAllRedirectUrl))
    {
        if (0 < G_DeleteAllRedirectUrl.length) lRedirectUrl += "&redirect=" + encodeURI(G_DeleteAllRedirectUrl);
    }
	ShowProgressbar();
    window.location = lRedirectUrl; //this is remove all tix
}

function BuyMore()
{
	//check if tickets exist
	if(jQuery("#tblSeasonCart").length > 0)
	{
		window.location = SwitchProtocol(false, 'EventsPage.aspx?TabMenu=2'); //go to seasons
		return false;
	}
	
	window.location = SwitchProtocol(false, 'EventsPage.aspx');
	return false;
}

function AddOrderExtraFee(pDollarFee,pFeeID)
{
	var lOrderFees = gEBI("txtExtraOrderFees");
     
	if(null == lOrderFees) return;
	lOrderFees.setAttribute("ExtraFeeIDs", lOrderFees.getAttribute("ExtraFeeIDs")+pFeeID+",");
	lOrderFees.setAttribute("ExtraFeeAmount", Number(Number(lOrderFees.getAttribute("ExtraFeeAmount"))+Number(pDollarFee)));
}

function BalanceOrderFee(pThis)
{
	var lFeeID = pThis.getAttribute("feeID");
	var lBalanceOrderFees = gEBI("txtBalanceOrderFee");
	var lExtraOrderFees = gEBI("txtExtraOrderFees");
	if(null == lBalanceOrderFees || null == lExtraOrderFees) return;

	if(lExtraOrderFees.getAttribute("ExtraFeeIDs").indexOf(","+lFeeID + ",") == -1 && lExtraOrderFees.getAttribute("ExtraFeeIDs").indexOf(lFeeID + ",") != 0)
	{			
		lBalanceOrderFees.setAttribute("ExtraFeeIDs", lBalanceOrderFees.getAttribute("ExtraFeeIDs")+lFeeID+",");
		lExtraOrderFees.setAttribute("ExtraFeeIDs", lExtraOrderFees.getAttribute("ExtraFeeIDs")+lFeeID+",");
	}
	var lBalanceValue = Number(Number(lBalanceOrderFees.getAttribute("BalanceFeeAmount"))-Number(gEBI("txtTotal").value) );
	if(lBalanceValue < 0) lBalanceValue = 0;
	lBalanceOrderFees.setAttribute("BalanceFeeAmount", lBalanceValue);
	pThis.style.display = "none";
}
function ClearExtraFees()
{
	var lOrderFees = gEBI("txtExtraOrderFees");
	if(null == lOrderFees) return;
	lOrderFees.setAttribute("ExtraFeeIDs", "");
	lOrderFees.setAttribute("ExtraFeeAmount", 0.00);
}
//------------------------------------------------------------------------


//----------------------:AddressLookUp-------------------------------------
function UseInfo(id)
{
	var obj=gEBI(String('patron_salutation1_' + id));
	if(null != obj)
	{
	//add values to cart inputs
	salut = returnBlank(obj.value);
	firstnm = returnBlank(gEBI(String('patron_firstname1_' + id)).value);
	lastnm = returnBlank(gEBI(String('patron_lastname1_' + id)).value);
	spousesalut = returnBlank(gEBI(String('patron_salutation2_' + id)).value);
	spousefirstnm = returnBlank(gEBI(String('patron_firstname2_' + id)).value);
	spouselastnm = returnBlank(gEBI(String('patron_lastname2_' + id)).value);
	compny = returnBlank(gEBI(String('patron_company_' + id)).value);
	adr = returnBlank(gEBI(String('patron_address_' + id)).value);
	adr2 = returnBlank(gEBI(String('patron_address2_' + id)).value);
	cit = returnBlank(gEBI(String('patron_city_' + id)).value);
	stat = returnBlank(gEBI(String('patron_state_' + id)).value);
	zipcd = returnBlank(gEBI(String('patron_zip_' + id)).value);
	cntry = returnBlank(gEBI(String('patron_country_' + id)).value);
	regn = returnBlank(gEBI(String('patron_region_' + id)).value);
	phne = returnBlank(gEBI(String('patron_phone_' + id)).value);
	custom1 = returnBlank(gEBI(String('patron_custom1_' + id)).value);
	custom2 = returnBlank(gEBI(String('patron_custom2_' + id)).value);
	custom3 = returnBlank(gEBI(String('patron_custom3_' + id)).value);
	custom4 = returnBlank(gEBI(String('patron_custom4_' + id)).value);
	custom5 = returnBlank(gEBI(String('patron_custom5_' + id)).value);
	custom6 = returnBlank(gEBI(String('patron_custom6_' + id)).value);
	custom7 = returnBlank(gEBI(String('patron_custom7_' + id)).value);
	phnetyp = gEBI(String('patron_phonetypeid_' + id)).value;
	patronid = gEBI(String('patron_id_' + id)).value;
	email = returnBlank(gEBI(String('patron_email_' + id)).value);
	addressid = returnBlank(gEBI('patron_addressid_' + id).value);
	emailtyp = returnBlank(gEBI(String('patron_emailtypeid_' + id)).value);
	}
	if(null != window.opener && !window.opener.closed && null != window.opener.setFormVals)
	{			
		if(null != obj) window.opener.setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,patronid,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7);
		else window.opener.PatronLookUpById(id);
		window.opener.focus();
		window.close();
	}else
	{
		if(null != obj) setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,patronid,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7);
		else window.opener.PatronLookUpById(id);
		CloseAddressLookUp();
	}
}

function setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,id,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7)
{
	if(null !=	gEBI("patron_id") && ("patron"==gAddressFindType || "bill"==gAddressFindType ))
				gEBI("patron_id").value = unescape(id);
				
	if(null !=	gEBI("patron_salutation1"))
	{
				gEBI("patron_salutation1").value = unescape(salut);
				SetCustomCartFields("patron_salutation1",false);
	}
	if(null !=	gEBI("patron_firstname1"))
				gEBI("patron_firstname1").value = unescape(firstnm);
				
	if(null !=	gEBI("patron_lastname1"))
				gEBI("patron_lastname1").value = unescape(lastnm);
				
	if(null !=	gEBI("patron_salutation2"))
	{
				gEBI("patron_salutation2").value = unescape(spousesalut);
				SetCustomCartFields("patron_salutation2",false);
	}			
	if(null !=	gEBI("patron_firstname2"))
				gEBI("patron_firstname2").value = unescape(spousefirstnm);
				
	if(null !=	gEBI("patron_lastname2"))
				gEBI("patron_lastname2").value = unescape(spouselastnm);
				
	if(null !=	gEBI("patron_company"))
				gEBI("patron_company").value = unescape(compny);
				
	if(null !=	gEBI("patron_address"))
				gEBI("patron_address").value = unescape(adr);
				
	if(null !=	gEBI("patron_address2"))
				gEBI("patron_address2").value = unescape(adr2);
				
	if(null !=	gEBI("patron_city"))
				gEBI("patron_city").value = unescape(cit);
	var st = unescape(stat);
	st = st.replace(' ','');
	
	if(null !=	gEBI("patron_state"))
				gEBI('patron_state').value = st;
				
	if(null !=	gEBI("patron_zip"))
				gEBI("patron_zip").value = unescape(zipcd);
		
	if(("bill"==gAddressFindType || "shipp"==gAddressFindType) && "" == Trim(cntry))
		cntry = "USA";
					
	if(null !=	gEBI("patron_country"))
				gEBI("patron_country").value = unescape(cntry);
				
	if(null !=	gEBI("patron_region"))
				gEBI("patron_region").value = unescape(regn);
				
	if(null !=	gEBI("patron_phone"))
				gEBI("patron_phone").value = unescape(phne);

	if(null !=	gEBI("patron_email"))
				gEBI("patron_email").value = unescape(email);
				
	if(null !=	gEBI("patron_phonetype"))
		if(phnetyp != null && phnetyp != "")
			for(var i=0;i<gEBI('patron_phonetype').options.length;i++){
				if(gEBI('patron_phonetype').options[i].value==unescape(phnetyp))
					gEBI('patron_phonetype').selectedIndex = i;
			}
	if(null !=	gEBI("patron_emailtype"))
		if(emailtyp != null && emailtyp != "")
			for(var i=0;i<gEBI('patron_emailtype').options.length;i++){
				if(gEBI('patron_emailtype').options[i].value==unescape(emailtyp))
					gEBI('patron_emailtype').selectedIndex = i;
			}

	if(null != gEBI("patron_custom1"))
	{
		gEBI("patron_custom1").value = custom1;
		SetCustomCartFields("patron_custom1");
	}
	if(null != gEBI("patron_custom2"))
	{
		gEBI("patron_custom2").value = custom2;
		SetCustomCartFields("patron_custom2");
	}
	if(null != gEBI("patron_custom3"))
	{
		gEBI("patron_custom3").value = custom3;
		SetCustomCartFields("patron_custom3");
	}
	if(null != gEBI("patron_custom4"))
	{
		gEBI("patron_custom4").value = custom4;
		SetCustomCartFields("patron_custom4");
	}
	if(null != gEBI("patron_custom5"))
	{
		gEBI("patron_custom5").value = custom5;
		SetCustomCartFields("patron_custom5");
	}
	if(null != gEBI("patron_custom6"))
	{
		gEBI("patron_custom6").value = custom6;
		SetCustomCartFields("patron_custom6");
	}
	if(null != gEBI("patron_custom7"))
	{
		gEBI("patron_custom7").value = custom7;
		SetCustomCartFields("patron_custom7");
	}
	if(""!=id && "0"!=id)
	{
		gEBI("patron_billingaddressid").value = unescape(addressid);
		gEBI("patron_DIVupdateaddress").style.display = "block";
		gEBI("shipp_DIVupdateaddress").style.display = "block";
	}
	else
	{
		gEBI("patron_billingaddressid").value = "0";
		gEBI("patron_DIVupdateaddress").style.display = "none";
		gEBI("shipp_DIVupdateaddress").style.display = "none";
	}
	getPatronCoupons(); //todo: remove comments

	SetCountryAndState("patron");
	SetCountryAndState("shipping");
}
//------------------------------------------------------------------------


//----------------------:CartFields-------------------------------------
function AddNewShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return;

	lSelShippDetails.selectedIndex = -1;
	GetShippAddress();
}

function ToUpperCaseFirstChars(pSentence, pDelimiter)
{
	var lWords = pSentence.split(pDelimiter);
	pSentence = "";
	for(var i=0; i<lWords.length; i++)
	{
		lWord = lWords[i];
		pSentence += lWord.substr(0,1).toUpperCase()+lWord.substr(1);
		if(i < lWords.length-1) pSentence += pDelimiter;
	}
	return Trim(pSentence);
}

function CorrectName(pField)
{
	var lFV = pField.value;
	
	//if not all caps or all lower do not auto-format	
	if(lFV != lFV.toUpperCase() && lFV != lFV.toLowerCase()) return;

	lFV = Trim(lFV).toLowerCase();
	lFV = ToUpperCaseFirstChars(lFV," ");
	lFV = ToUpperCaseFirstChars(lFV,"-");
	lFV = ToUpperCaseFirstChars(lFV,".");
	
	pField.value = lFV;
}

function DeleteShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return;

	if(-1 != lSelShippDetails.selectedIndex)
		lSelShippDetails.remove(lSelShippDetails.selectedIndex)
	
	lSelShippDetails.selectedIndex = -1;
	if(0 == lSelShippDetails.options.length)
		lSelShippDetails.disabled = true;
	GetShippAddress();
}

function SetShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return false;
	
	var strShippXML = BuildShippingXML();
	if(false == strShippXML) return false;
	
	var lOptionInnerHTML = "";
	
	if(null !=	gEBI("shipping_firstname1"))
		lOptionInnerHTML += gEBI("shipping_firstname1").value;
	
	if(null !=	gEBI("shipping_lastname1"))
		lOptionInnerHTML += " "+ gEBI("shipping_lastname1").value;
	if("" == Trim(lOptionInnerHTML))
		lOptionInnerHTML = "NoName";
		
	var lOption = null;
	if(-1 == lSelShippDetails.selectedIndex)
	{
		lOption = document.createElement("OPTION");
		lSelShippDetails.options.add(lOption);
	}
	else
		lOption = lSelShippDetails.options[lSelShippDetails.selectedIndex];
	
	lOption.text = lOptionInnerHTML;
	lOption.selected = true;
	lOption.innerHTML = lOptionInnerHTML;
	lOption.setAttribute('ShippXML',strShippXML);
	lSelShippDetails.disabled = false;
	return true;
}

function BuildShippingXML()
{
		var strShippXML = "<PatronAddress>";
		
		strShippXML += "<Address>";
		strShippXML +=		"<ID>" + gEBI('patron_shippingaddressid').value + "</ID>";
		

		if("0" != buildCustomXML(gEBI("shipping_salutation1"),"Salutation")) strShippXML +=	buildCustomXML(gEBI("shipping_salutation1"),"Salutation");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_firstname1"),"FirstName")) strShippXML +=	buildCustomXML(gEBI("shipping_firstname1"),"FirstName");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_lastname1"),"Name")) strShippXML +=	buildCustomXML(gEBI("shipping_lastname1"),"Name");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_salutation2"),"PartnerSalutation")) strShippXML +=	buildCustomXML(gEBI("shipping_salutation2"),"PartnerSalutation");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_firstname2"),"PartnerFirstName")) strShippXML +=	buildCustomXML(gEBI("shipping_firstname2"),"PartnerFirstName");
		else return false;
		
		if("0" != buildCustomXML(gEBI("shipping_lastname2"),"PartnerLastName")) strShippXML +=	buildCustomXML(gEBI("shipping_lastname2"),"PartnerLastName");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_company"),"Company")) strShippXML +=	buildCustomXML(gEBI("shipping_company"),"Company");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_address"),"Street")) strShippXML +=	buildCustomXML(gEBI("shipping_address"),"Street");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_address2"),"Street2")) strShippXML +=	buildCustomXML(gEBI("shipping_address2"),"Street2");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_city"),"City")) strShippXML +=	buildCustomXML(gEBI("shipping_city"),"City");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_state"),"State")) strShippXML +=	buildCustomXML(gEBI("shipping_state"),"State");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_zip"),"ZIP")) strShippXML +=	buildCustomXML(gEBI("shipping_zip"),"ZIP");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_country"),"Country")) strShippXML +=	buildCustomXML(gEBI("shipping_country"),"Country");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_region"),"Region")) strShippXML +=	buildCustomXML(gEBI("shipping_region"),"Region");
		else return false;			
			
		if("0" != buildCustomXML(gEBI("shipping_phone"),"Phone")) strShippXML +=	buildCustomXML(gEBI("shipping_phone"),"Phone");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_email"),"EMail")) strShippXML +=	buildCustomXML(gEBI("shipping_email"),"EMail");
		else return false;

			
		var oSel = gEBI("shipping_phonetype");
		if(null != oSel)			
			strShippXML +=		"<PhoneType>" + String(oSel.options[oSel.selectedIndex].innerHTML) + "</PhoneType>";		
		oSel = gEBI("shipping_emailtype");
		if(null != oSel)
			strShippXML +=		"<EmailType>" + String(oSel.options[oSel.selectedIndex].innerHTML) + "</EmailType>";		
		strShippXML +=		"<AddressType><ID>1</ID></AddressType>";
		if("0" != buildCustomXML(gEBI("shipping_custom1"),"Custom1")) strShippXML +=	buildCustomXML(gEBI("shipping_custom1"),"Custom1");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom2"),"Custom2")) strShippXML +=	buildCustomXML(gEBI("shipping_custom2"),"Custom2");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom3"),"Custom3")) strShippXML +=	buildCustomXML(gEBI("shipping_custom3"),"Custom3");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom4"),"Custom4")) strShippXML +=	buildCustomXML(gEBI("shipping_custom4"),"Custom4");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom5"),"Custom5")) strShippXML +=	buildCustomXML(gEBI("shipping_custom5"),"Custom5");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom6"),"Custom6")) strShippXML +=	buildCustomXML(gEBI("shipping_custom6"),"Custom6");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom7"),"Custom7")) strShippXML +=	buildCustomXML(gEBI("shipping_custom7"),"Custom7");
		else return false;
		strShippXML += "</Address>";

		strShippXML += "<AddressType><ID>1</ID></AddressType>";
	strShippXML += "</PatronAddress>";
	return strShippXML;
}

function toggleRightSideDetails()
{
	var lCHSippAddress		= gEBI("chSippAddress");
	var lDIVShipDetails		  = gEBI("divShipDetails");
	
	if(	null == lCHSippAddress || null == lDIVShipDetails ) return;
	
	if(lCHSippAddress.checked)
		lDIVShipDetails.style.display = "block";
	else
		lDIVShipDetails.style.display = "none";
}

function SetCountryAndState(strDetailType)
{	
	if(null != gEBI("sel"+strDetailType+"_country"))
	{
		gEBI("sel"+strDetailType+"_country").value = gEBI(strDetailType+"_country").value
		if(gEBI("sel"+strDetailType+"_country").value != gEBI(strDetailType+"_country").value || gEBI(strDetailType+"_country").value =="")
		{
			gEBI("sel"+strDetailType+"_country").value = "other";
			gEBI(strDetailType+"_country").style.display = "block";
		}
		else 		
			gEBI(strDetailType+"_country").style.display = "none";
	}

	var lSelState = gEBI("sel"+strDetailType+"_state");
	
	if(null == lSelState) return;
	if(null != gEBI("sel"+strDetailType+"_country") && null != gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value))
	{
		var lSelHiddenState = gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value);
		var lLength = lSelState.options.length;
		for (var i=lLength-1; i>=0; i--)
			lSelState.removeChild(lSelState.options[i]);

		for (var i=0; i<lSelHiddenState.options.length; i++)
		{
			lSelState.options[lSelState.options.length] = new Option(lSelHiddenState.options[i].innerHTML,lSelHiddenState.options[i].value);
		}
			
		//gEBI("sel"+strDetailType+"_state").innerHTML = gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value).innerHTML;
		
		lSelState.value = String(gEBI(strDetailType+"_state").value).replace(" ","");
		lSelState.style.display = "block";
		gEBI(strDetailType+"_state").style.display = "none";
	}
	else{
		gEBI("sel"+strDetailType+"_state").style.display = "none";
		gEBI(strDetailType+"_state").style.display = "block";
	}

}

function ChangeCountry(oThis,strDetailType)// strDetailType: shipping, patron
{
	if(oThis.value == "other"){
		gEBI(strDetailType+"_country").style.display = "block";
		gEBI(strDetailType+"_country").value = "";
	}
	else{
		gEBI(strDetailType+"_country").style.display = "none";
		gEBI(strDetailType+"_country").value = oThis.value;
	}
	var lSelState = gEBI("sel"+strDetailType+"_state");
	if(lSelState!=null)
	{
		var lSelHiddenState = gEBI("sel"+strDetailType+"_state_"+oThis.value);
		if(lSelHiddenState !=null)
		{
			var lLength = lSelState.options.length;
			for (var i=lLength-1; i>=0; i--)
				lSelState.removeChild(lSelState.options[i]);


			for (var i=0; i<lSelHiddenState.options.length; i++)
			{
						var oOption = document.createElement("OPTION");
						lSelState.options.add(oOption);
						oOption.innerHTML = lSelHiddenState.options[i].innerHTML;
						oOption.value = lSelHiddenState.options[i].value;
			}
			gEBI(strDetailType+"_state").value = lSelState.value;
			lSelState.style.display = "block";
			gEBI(strDetailType+"_state").style.display = "none";
		}
		else
		{
			lSelState.style.display = "none";
			gEBI(strDetailType+"_state").style.display = "block";
			gEBI(strDetailType+"_state").value = "";
		}
	}
}

function resetAddress()
{
	//clear form
	$("#patron_salutation1").val("");
	$("#patron_firstname1").val("");
	$("#patron_lastname1").val("");
	
	$("#patron_salutation2").val("");
	$("#patron_firstname2").val("");
	$("#patron_lastname2").val("");
	
	$("#patron_company").val("");
	$("#patron_address").val("");
	$("#patron_address2").val("");
	$("#patron_city").val("");
	$("#patron_state").val("");
	
	$("#patron_zip").val("");
	$("#patron_country").val("");
	$("#patron_region").val("");
	$("#patron_phone").val("");
	$("#patron_phonetype").val("");
	$("#patron_email").val("");
	$("#patron_emailtype").val("");
	
	//custom fields
	for(var i=1;i<=7;i++)
	{
		if(null == gEBI("shipping_custom" + i))
			continue;
		
		$("#patron_custom" + i).val("");
		SetCustomCartFields("patron_custom" + i);
	}

	$("#patron_billingaddressid").val("");
	//clear patron
	//requesting a page
	var strUrl = gShoppingCartURL + "?clear=1";
	
	$.ajax({
				type: "POST",
				url: strUrl,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
}
  
function AddPhone()
{
	var oAddPhones = gEBI("addPhones");
	var oAddPhonesShippSpace = gEBI("addPhonesShippSpace");
	
	var oPhoneType = gEBI("patron_phonetype");
	var iPhone = gEBN("AdditionalPhones").length;
	var strPhone = "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhone"+iPhone+"'>";
	strPhone +="<TR><TD class='tdFieldLeft' align='right'>&nbsp;Phone Number</TD>";
	strPhone +="<TD class='tdFieldRight' align='center'>";
	strPhone +="<INPUT type='text' class='textfield' id='AdditionalPhone"+iPhone+"' name='AdditionalPhones' onFocus='select();' PatronPhoneId='0' PhoneId='0'>";
	strPhone +="</TD>";
	strPhone +="<TD><span onmouseover='this.style.color=\"#fc6600\";' onmouseout='this.style.color=\"#000000\";'  style='cursor: pointer;' onclick='DeletePhone("+iPhone+");'><IMG src='images/remove.gif' border='0'></span></TD>";
	strPhone +="</TR>";
	strPhone +="</TABLE>";
	
	var strPhoneShippSpace = "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneShippSpace"+iPhone+"'><TR><TD>&nbsp;</TD></TR></TABLE>";


	if(null != oPhoneType)
	{
		strPhone += "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneType"+iPhone+"'>";
		strPhone +="<TR><TD class='tdFieldLeft' align='right'>&nbsp;Phone Type</TD>";
		strPhone +="<TD class='tdFieldRight' align='center'>";
		strPhone +="<SELECT id='AdditionalPhoneType"+iPhone+"' name='AdditionalPhoneTypes' PhoneTypeID='0'>"+oPhoneType.innerHTML+"</SELECT>";
		strPhone +="</TD>";
		strPhone +="</TR>";
		strPhone +="</TABLE>";
		
		strPhoneShippSpace += "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneTypeShippSpace"+iPhone+"'><TR><TD>&nbsp;</TD></TR></TABLE>";
	}

	oAddPhones.innerHTML +=strPhone;
	oAddPhonesShippSpace.innerHTML +=strPhoneShippSpace;
}
function DeletePhone(iPhone)
{
	gEBI("AdditionalPhone"+iPhone).setAttribute('PhoneId','-1');
	gEBI("tblAdditionalPhone"+iPhone).style.display = "none";
	gEBI("tblAdditionalPhoneShippSpace"+iPhone).style.display = "none";
	if(null != gEBI("AdditionalPhoneType"+iPhone))
	{
		gEBI("AdditionalPhoneType"+iPhone).setAttribute('PhoneTypeID','-1');
		gEBI("tblAdditionalPhoneType"+iPhone).style.display = "none";
		gEBI("tblAdditionalPhoneTypeShippSpace"+iPhone).style.display = "none";
	}
}

function SetCustomCartFields(strHiddenName, bOther)
{
	var selName = gEBI("sel"+strHiddenName);
	var hName = gEBI(strHiddenName);
	
	if(null == selName && null != hName)
	{
		if("INPUT" == hName.tagName.toUpperCase())
		{
			if("CHECKBOX" == hName.type.toUpperCase())
			{
				try{
					hName.checked = eval(hName.value);
				}catch(e)
				{
					hName.checked = false;
				}
			}
		}
	}
	
	if(null == selName || null == hName) return false;
	
	if("SELECT" == selName.tagName.toUpperCase())
	{
		selName.value = hName.value
		if(selName.value != hName.value || Trim(hName.value) == "")
		{
			if(false == bOther)
			{
					if(Trim(hName.value) != "")
					{
						var oOption = document.createElement("OPTION");
						selName.options.add(oOption);
						oOption.innerHTML = hName.value;
						oOption.value = hName.value;
						selName.value = hName.value
					}
					hName.style.display = "none";
			}
			else
			{
				selName.value = "other";
				hName.style.display = "block";
			}
		}
		else 		
			hName.style.display = "none";
	}
	if("INPUT" == selName.tagName.toUpperCase())
	{
		if("CHECKBOX" == selName.type.toUpperCase())
		{
			try{
				selName.checked = eval(hName.value);
			}catch(e)
			{
				selName.checked = false;
			}
		}
		if("RADIO" == selName.type.toUpperCase())
		{
			var selN = gEBN("sel"+strHiddenName);
			for(var i=0; i<selN.length;i++)
				if(selN[i].value == hName.value)
					{
						selN[i].checked = true;
						break;
					}
		}
	}

}

function autoSelectCouponRadio(obj)
{
//auto-check radio button for code input when input is selected
try{
		//select radio button for code if code is entered
		var oParentTable = getParentNodeByTagName(obj, "TABLE");
		if(null != oParentTable)
		{
			var oChildren = getChildrenByPartialIdOrName(oParentTable, "RedeemedCoupon", true)
			if(null != oChildren && oChildren.length > 0)
			{
				oChildren[0].checked = true;	
			}
			
		}
		
	}catch(e){}
}

function checkCoupon(obj){
	var strCP = obj.value;
	var arrCP = strCP.split('-');
	var isValid = false;
	
	autoSelectCouponRadio(obj);
	
	if(arrCP.length >= 2)
	{
	var rcID = GetIntFromX(arrCP[0]);
	var cpID = GetIntFromX(arrCP[1]);
	getClientCoupon(rcID,cpID);
	for(var r=0;r<gClientCoupons.length;r++){
		if((gClientCoupons[r].ID==rcID)&&(null!=gClientCoupons[r].Coupon)&&(gClientCoupons[r].Coupon.ID==cpID)){
			isValid = true;
			obj.setAttribute('RedeemedCoupon',gClientCoupons[r].ID);
			obj.setAttribute('CouponValue',gClientCoupons[r].Coupon.CouponValue);
		}
	}
	}
	
	

	
	/*if(!isValid){
		obj.select();
		obj.focus();
		obj.value="";
		alert("You have entered an invalid Coupon Code.  Please try again.");
	}*/
}

function getCouponAmount(obj, nPayTypeNumber, bAsync)
{
	autoSelectCouponRadio(obj);
	//find coupon amount field input
	var oTable = jQuery(obj).parents("TABLE")[0];
	
	//var obbj = gEBI("pay_" + nPayTypeNumber + "_total");
	var obbj = jQuery(oTable).find("INPUT");
	if(obbj.length > 0)
		obbj = obbj[obbj.length-1]; //last input
	if(null == obbj)
		return;

	if(arguments[2] == null)
		bAsync = true;
		
	obj.value=Trim(obj.value);
	if(obj.value=="") return;
	var arrCouponCodeInputs = gEBN('pay_coupon_code');
	if(arrCouponCodeInputs!=null && arrCouponCodeInputs.length>1)
	{
		for(var i=0;i<arrCouponCodeInputs.length;i++)
		{
			if(arrCouponCodeInputs[i].id!=obj.id)
			{
				if(obj.value != "" 
					&& obj.value != GetTranslation("enter_code_here", "Enter Code Here") 
					&& obj.value == arrCouponCodeInputs[i].value)
				{
					alert("This coupon is already used");
					obj.value="";
					return;
				}
			}
		}
	}
	obbj.value = "Please wait";
	
	//check if we have cached result
	if(typeof(gCouponResponses) != "undefined")
		if(typeof(gCouponResponses[obj.value]) != "undefined")
		{
			ResponseCouponAmount(gCouponResponses[obj.value],obj,obbj);
			return;
		}
	
	
	var strUrl = "getCouponAmountByActivationCode.aspx?ac=" + obj.value;
	$.ajax({
				type: "POST",
				url: strUrl,
				data: "<a>a</a>",
				async: bAsync, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					ResponseCouponAmount(data, obj, obbj);
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
}


var gCouponResponses = new Array();
function ResponseCouponAmount(strResp,obj,obbj)
{
	if(null == strResp)
		return; 
	if("" == strResp)
		return;
	
	
    var str=strResp.split(";");

    if (isNaN(str[0]) )
      str[0]="0";
    if (isNaN(str[1]) )
      str[1]="0";
    if (isNaN(str[2]) )
      str[2]="0";
	obbj.value=str[0];
	obbj.setAttribute("limit",str[0]);
	obbj.setAttribute("qty",str[1]);
	gnCoupon=str[1];
	
	if(obbj.getAttribute("predefinedlimit")!=null && parseInt(obbj.getAttribute("predefinedlimit"))>0){
		if(parseInt(obbj.getAttribute("predefinedlimit"))<parseInt(strResp))
			{
				obbj.value=obbj.getAttribute("predefinedlimit");
			}
		else
			{
				obbj.value = strResp;
			}
	}
	else
	{
		obbj.value=strResp;
	}
	
	
	obbj.setAttribute("onchange", "ChangeCouponAmount(this)");
	
	CheckCurrency(obbj.value, obbj); 
	CheckTransactionTotals(obbj);
	
	//if value is from cache - dont call add coupon
	if(typeof(gCouponResponses[obj.value]) != "undefined")
		return;
	
	//save response in cache
	gCouponResponses[obj.value] = strResp;
	
	//check if the value of the coupon is more than 0, if so and if we still lack money, display confirmation
	var nAmount = parseFloat(obbj.value);
	if(isNaN(nAmount))
		return;
	if(nAmount <= 0)
		return;
	if(parseFloat(gEBI("displayOrderBalanceTotal").value) <= 0 )
		return;
	if(typeof(gConfirmCouponDialog) == "undefined")
		return;
	if(gConfirmCouponDialog.length <= 0)
		return;
		
	gConfirmCouponDialog.show();
	gConfirmCouponDialog.dialog("open");
		
}

function CouponConfirmOnAddCoupon()
{
	var oPM = gEBI(gEBI("paymentmethodUniqueId").value);
	AddPaymentType(oPM.value, oPM, null, true);
}

function CouponConfirmOnAddCC()
{
	var oPM = gEBI(gEBI("paymentmethodUniqueId").value);
	var oOpt = jQuery(oPM).find("option[value=credit]"); 
	
	//select first paymethod (CC)
	oPM.selectedIndex = 0;
	oPM.onchange();
	
	//AddPaymentType(oOpt.val(), oPM, null, true);
}

function HideConfirmation(ControlID) {
    if (jQuery("#" + ControlID).length == 0)
        return;

    jQuery('#' + ControlID).dialog("close");
}

function ChangeCouponAmount(pTotal){
    if(parseInt(pTotal.value)>parseInt(pTotal.getAttribute("limit")))
		pTotal.value = pTotal.getAttribute("limit");
}
function hidebuybtn(){
	$("#Process_Order").hide();
}
//---------------------------------------------------------------------------

//----------------------:DeliveryMethods-------------------------------------
function deliverymethod_onchange(oSelect)
{
	updateTotals();
}

function DefaultDeliveryMethod()
{
	var oDm = gEBI(gEBI("deliverymethodUniqueId").value);
	if(null == oDm) return;
	if(isWeb)
	{
		var gotMail = false;
		for(var i = 0; i<oDm.options.length; i++)
			if(oDm.options[i].innerHTML == "Take Tickets Now")
			{
				oDm.remove(i);
				break;
			}
			else if(oDm.options[i].innerHTML == "Mail")
				gotMail = true;
		
		oDm.selectedIndex = 0;
		oDm.onchange();
		if(!gotMail)
			if(gEBI("MesMail") != null)
				gEBI("MesMail").style.display = "inline";
			
	}
	else
	{	try{
			if(gClientId == 16)
			{
				oDm.selectedIndex = 0;
				oDm.onchange();
			}
			else
			{
				oDm.onchange();
			}
		}catch(e){}
	}
}
//---------------------------------------------------------------------------


//----------------------:Paymentypes-----------------------------------------
function AddPaymentType(pTyp, oType, bDontDraw,AppendPayment)
{
	if(AppendPayment==null) AppendPayment=false;
	if(isWeb && !AppendPayment)
	{
		SwitchWebPaymentType(pTyp, oType, bDontDraw);
		updateTotals();
		CheckTransactionTotals(null, false);
		return;
	}
	if(pTyp == "")
		return;

	var objNewPayType = null;
	var htmlstr = "";
	var newPT = null; //currently added paytype
	
	if ((pTyp != null)&&(pTyp != "undefined"))
	{
		var last = aryPayTypes.length;
		var initIndx = 0;
		
		for(var xx=0;xx<last;xx++)
			if(initIndx <= aryPayTypes[xx].initIndex)
				initIndx = aryPayTypes[xx].initIndex+1;
		
		//var selOption = oType.options[oType.selectedIndex]; 
		//select option by value
		var selOption = jQuery(oType).find("option[value=" + pTyp + "]")[0];
		aryPayTypes[last] = new Object();
		newPT = aryPayTypes[last];
		
		newPT.initIndex = initIndx; //used to handle cases when paytypes are added and deleted and it is impossible to get paytype by index in aryPayTypes
		newPT.Name = selOption.innerHTML;
		newPT.Value = pTyp;
		newPT.TransactionTypeId = selOption.getAttribute('TransactionTypeId');
		newPT.PaymenttypesClientId = selOption.getAttribute('PaymenttypesClientId');
		newPT.IsStandart = selOption.getAttribute('IsStandart');
		newPT.CCTYPES = selOption.getAttribute('CCTYPES'); //coded presentation of available CCTYPES in form ID:Name,ID:Name,ID:Name
	
		//get pay fee to current paymenttype
		//newPT.OrderFees	= selOption.getAttribute("orderfees");
		
		if("false" == aryPayTypes[last].IsStandart)
		{
			newPT.NameCustom1 = selOption.getAttribute('NameCustom1');
			newPT.NameCustom2 = selOption.getAttribute('NameCustom2');
			newPT.NameCustom3 = selOption.getAttribute('NameCustom3');
			newPT.NameCustom4 = selOption.getAttribute('NameCustom4');
			newPT.NameCustom5 = selOption.getAttribute('NameCustom5');
			newPT.TypeCustom1 = selOption.getAttribute('TypeCustom1');
			newPT.TypeCustom2 = selOption.getAttribute('TypeCustom2');
			newPT.TypeCustom3 = selOption.getAttribute('TypeCustom3');
			newPT.TypeCustom4 = selOption.getAttribute('TypeCustom4');
			newPT.TypeCustom5 = selOption.getAttribute('TypeCustom5');
			newPT.ValuesCustom1 = selOption.getAttribute('ValuesCustom1');
			newPT.ValuesCustom2 = selOption.getAttribute('ValuesCustom2');
			newPT.ValuesCustom3 = selOption.getAttribute('ValuesCustom3');
			newPT.ValuesCustom4 = selOption.getAttribute('ValuesCustom4');
			newPT.ValuesCustom5 = selOption.getAttribute('ValuesCustom5');
			newPT.IsEnabledCustom1 = selOption.getAttribute('IsEnabledCustom1');
			newPT.IsEnabledCustom2 = selOption.getAttribute('IsEnabledCustom2');
			newPT.IsEnabledCustom3 = selOption.getAttribute('IsEnabledCustom3');
			newPT.IsEnabledCustom4 = selOption.getAttribute('IsEnabledCustom4');
			newPT.IsEnabledCustom5 = selOption.getAttribute('IsEnabledCustom5');
		}
	}

	var curI = 0;
	if(true != bDontDraw)
	{
		curI = newPT.initIndex;
		
		var payType = newPT.Value;
		if (/*(pTyp == "credit")&&*/payType == "credit" || payType == "creditcardsave") {

			htmlstr += '<table id="tblPay' + curI + '" class="tblData">';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Credit_Card_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" class="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">';
			htmlstr += GetTranslation("Cardholder_s_Name");
			htmlstr += '<a href="javascript:doSwipe(' + curI + ');"><img class="ccSwipeImg" src="images/swipecard.gif" alt="';
			htmlstr += GetTranslation("swipe_credit_card");
			htmlstr += '" border="0" /></a><input type="text" style="color:#cc0000;background-color:#cc0000;width:8px;height:8px;" name="TrackData' + curI + '" id="TrackData' + curI + '" size="3" onfocus="startCheckLoop(' + curI + ');" onBlur="endCheckLoop(' + curI + ');" /><input type="hidden" name="CCwasSwiped' + curI + '" id="CCwasSwiped' + curI + '" value="false"></td>\n';
			htmlstr += '  <td class="tblDataTd" nowrap>\n';
			htmlstr += '  <input type="text" style="display:none" class="textfield" style="width:30px;" name="pay_' + curI + '_salutation" id="pay_' + curI + '_salutation" value="" onfocus="select();" />\n';
			htmlstr += '  <input type="text" class="textfield" style="width:66px;" name="pay_' + curI + '_firstname" id="pay_' + curI + '_firstname" value="" onfocus="select();" />\n';
			htmlstr += '  <input type="text" class="textfield" style="width:66px;" name="pay_' + curI + '_lastname" id="pay_' + curI + '_lastname" value="" onfocus="select();" />\n';
			htmlstr += '  <img style="cursor:pointer;" title="Paste Name" onclick="if(null != gEBI(\'pay_' + curI + '_firstname\')) gEBI(\'pay_' + curI + '_firstname\').value = gEBI(\'patron_firstname1\').value; if(gEBI(\'pay_' + curI + '_lastname\')) gEBI(\'pay_' + curI + '_lastname\').value = gEBI(\'patron_lastname1\').value;" src="images/paste.gif" />\n';

			if (!isWeb && typeof(gClientObj) != "undefined" && gClientObj.HasSignaturePad) {
			    htmlstr += '  <a href="#" onclick="return OpenSignatureForm(null, \'pay_' + curI + '_siginput\');" class="facebox" style="text-decoration:none;border:0px;" ><img border="0" src="images/pen.gif" /></a>'
			    htmlstr += '  <input type="hidden" name="pay_' + curI + '_siginput" id="pay_' + curI + '_siginput" value="" />';
			}
			
            htmlstr += '  </td>\n';
			htmlstr += ' </tr>\n';

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Card_Type")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><select class="textfield" name="pay_' + curI + '_cardtype" id="pay_' + curI + '_cardtype" />\n';
			
			if(newPT != null)
				if(null != newPT.CCTYPES && "" != newPT.CCTYPES)
				{
					var arrTypes = newPT.CCTYPES.split(",");
					for(var zz=0;zz<arrTypes.length;zz++)
					{
						var arrTypeData = arrTypes[zz].split(":");
						htmlstr += '	<option value="' + arrTypeData[0] + '">' + arrTypeData[1] + '</option>\n';
					}
				}
			htmlstr += '</select>\n';
			htmlstr += ' </td>\n';
			htmlstr += ' </tr>\n';

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Card_Number")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_cardnumber" id="pay_' + curI + '_cardnumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Expiration_Date")+'</td>\n';

			htmlstr += '  <td class="tblDataTd">\n';
			htmlstr += '   <select class="textfield" style="width:40px;" name="pay_' + curI + '_expmo" id="pay_' + curI + '_expmo" > \n';
			htmlstr += '   	<option VALUE="" SELECTED="">--</option> \n';
			htmlstr += '   	<option VALUE="01">01</option> \n';
			htmlstr += '   	<option VALUE="02">02</option> \n';
			htmlstr += '   	<option VALUE="03">03</option> \n';
			htmlstr += '   	<option VALUE="04">04</option> \n';
			htmlstr += '   	<option VALUE="05">05</option> \n';
			htmlstr += '   	<option VALUE="06">06</option> \n';
			htmlstr += '   	<option VALUE="07">07</option> \n';
			htmlstr += '   	<option VALUE="08">08</option> \n';
			htmlstr += '   	<option VALUE="09">09</option> \n';
			htmlstr += '   	<option VALUE="10">10</option> \n';
			htmlstr += '   	<option VALUE="11">11</option> \n';
			htmlstr += '   	<option VALUE="12">12</option> \n';
			htmlstr += '   </select> / \n';
			htmlstr += '   <select class="textfield" style="WIDTH: 40px" name="pay_' + curI + '_expyr" id="pay_' + curI + '_expyr" > \n';
			htmlstr += '   	<option VALUE="" SELECTED="">--</option> \n';
			htmlstr += '   	<option VALUE="11">11</option> \n';
			htmlstr += '   	<option VALUE="12">12</option> \n';
			htmlstr += '   	<option VALUE="13">13</option> \n';
			htmlstr += '   	<option VALUE="14">14</option> \n';
			htmlstr += '   	<option VALUE="15">15</option> \n';
			htmlstr += '   	<option VALUE="16">16</option> \n';
			htmlstr += '   	<option VALUE="17">17</option> \n';
			htmlstr += '   	<option VALUE="18">18</option> \n';
			htmlstr += '   	<option VALUE="19">19</option> \n';
			htmlstr += '   	<option VALUE="20">20</option> \n';
			htmlstr += '   	<option VALUE="21">21</option> \n';
			htmlstr += '   	<option VALUE="22">22</option> \n';
			htmlstr += '   </select> \n';
			htmlstr += '  </td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("CVV_Number")+' <a href="cvv_pop.htm" target="_blank">?</a></td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_cvvnumber" id="pay_' + curI + '_cvvnumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "cash")&&*/payType == "cash") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Cash_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Cash_Tendered")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "check")&&*/payType == "check") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Check_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Check_Number")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_checknumber" id="pay_' + curI + '_checknumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "travellers")&&*/payType == "travellers") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblDatad">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Travellers_Check_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();CheckCurrencyTemp=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (payType == "voucher") 
		{
			if(!isWeb)
			{
				htmlstr += '<table ptid="'+newPT.TransactionTypeId+'" ptname="'+newPT.Name+'" ptidx="'+newPT.initIndex+'" ptval="'+newPT.Value+'" paymentvalue="voucher" id="tblPay' + curI + '" class="tblData">\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Voucher_Coupon_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
				htmlstr += ' </tr>\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponCode'+ curI +'"/>'+GetTranslation("Code")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_coupon_code" id="pay_' + curI + '_code" value="" RedeemedCoupon="0" CouponValue="0" onclick="checkCoupon(this);" onblur="getCouponAmount(this,' + curI +');"  onfocus="select();" /></td>\n';
				htmlstr += ' </tr>\n';
				if(!isNaN(parseInt(gEBI('patron_id').value))&&(parseInt(gEBI('patron_id').value)>0)){
					htmlstr += ' <tr>\n';
					htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponPatron'+ curI +'" checked>'+GetTranslation("Patron_Coupons")+'</td>\n';
					htmlstr += '  <td class="tblDataTd"><select style="font: 7pt Arial;" id="selPatronCoupon' + curI + '" onchange="(this.selectedIndex>0)?gEBI(\'pay_' + curI + '_total\').value=this.options[this.selectedIndex].getAttribute(\'CouponValue\'):gEBI(\'pay_' + curI + '_total\').value=0;CheckTransactionTotals(gEBI(\'pay_' + curI + '_total\'));"><option>'+GetTranslation("Select_Coupon")+'</option>' + listCoupons() + '</select></td>\n';
					htmlstr += ' </tr>\n';
				}
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
				htmlstr += ' </tr>\n';
				htmlstr += '</table><br />\n';
			}
			else
			{
			
				var jqTmp = $("#divPayMethods > table[ptval = " + payType + "]");
				
				//change all index fields
				if(1 == jqTmp.length)
				{
					objNewPayType = jqTmp[0].cloneNode(true);
					
					objNewPayType.id = "tblPay" + curI;
					objNewPayType.setAttribute("ptidx", newPT.initIndex);
					
					var jqTmp = jQuery(objNewPayType).find("tbody > tr > th");
					if(jqTmp.length > 0)
						jqTmp[0].id = "thPay" + curI;
					
					//coupon code field
					var jqTmp = jQuery(objNewPayType).find("input[name=pay_coupon_code]");
					if(jqTmp.length > 0)
					{
						jqTmp[0].id = "pay_" + curI + "_code";
						jqTmp[0].value = GetTranslation("enter_code_here", "Enter Code Here");
					}
					
					//coupon amount field
					var jqTmp = jQuery(objNewPayType).find("input");
					if(jqTmp.length > 0)
					{
						jqTmp[jqTmp.length-1].id = "pay_" + curI + "_total";
						jqTmp[jqTmp.length-1].name = "pay_" + curI + "_total";
						
						jqTmp[jqTmp.length-1].value = "0.00";
					}
				
				}
				else
				{
					htmlstr += '<table ptid="'+newPT.TransactionTypeId+'" ptname="'+newPT.Name+'" ptidx="'+newPT.initIndex+'" ptval="'+newPT.Value+'" paymentvalue="voucher" id="tblPay' + curI + '" class="tblData">\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Voucher_Coupon_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
				htmlstr += ' </tr>\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponCode'+ curI +'"/>'+GetTranslation("Code")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_coupon_code" id="pay_' + curI + '_code" value="" RedeemedCoupon="0" CouponValue="0" onclick="checkCoupon(this);" onblur="getCouponAmount(this,' + curI +');"  onfocus="select();" /></td>\n';
				htmlstr += ' </tr>\n';
				if(!isNaN(parseInt(gEBI('patron_id').value))&&(parseInt(gEBI('patron_id').value)>0)){
					htmlstr += ' <tr>\n';
					htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponPatron'+ curI +'" checked>'+GetTranslation("Patron_Coupons")+'</td>\n';
					htmlstr += '  <td class="tblDataTd"><select style="font: 7pt Arial;" id="selPatronCoupon' + curI + '" onchange="(this.selectedIndex>0)?gEBI(\'pay_' + curI + '_total\').value=this.options[this.selectedIndex].getAttribute(\'CouponValue\'):gEBI(\'pay_' + curI + '_total\').value=0;"><option>'+GetTranslation("Select_Coupon")+'</option>' + listCoupons() + '</select></td>\n';
					htmlstr += ' </tr>\n';
				}
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
				htmlstr += ' </tr>\n';
				htmlstr += '</table><br />\n';
				}
			}
		} 
		else if (payType == "TPS"){
		
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("TPS_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("TPS_Tendered")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		
		} 
		else if (payType == "account")
		{
			if (null!=selOption)
			{
				htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Account_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
				htmlstr += ' </tr>\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Account_Tendered")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onkeyup="CheckAccount(this,\''+selOption.getAttribute('Amount')+'\');" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
				htmlstr += ' </tr>\n';
				htmlstr += '</table><br />\n';
			}
		
		}
		else if("false" == newPT.IsStandart)
		{
		
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+newPT.Name+' '+GetTranslation("Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			if("true" == newPT.IsEnabledCustom1)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom1+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield1", newPT.TypeCustom1, newPT.ValuesCustom1) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom2)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom2+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield2", newPT.TypeCustom2, newPT.ValuesCustom2) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom3)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom3+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield3", newPT.TypeCustom3, newPT.ValuesCustom3) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom4)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom4+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield4", newPT.TypeCustom4, newPT.ValuesCustom4) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom5)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom5+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield5", newPT.TypeCustom5, newPT.ValuesCustom5) + '</td>\n';
				htmlstr += ' </tr>\n';
			}

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		}
		else { //all other default types, payType == "comp", "prepaid", "accountsreceivable", "svnimportpayment", "paypal", "wire", "webmoney"
		
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation(payType) + "_" +GetTranslation("Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Note")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_note" id="pay_' + curI + '_note" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		}
		
		document.getElementById("divPayMethods").style.display = "block";
		var oPayDiv = document.getElementById("divPayMethods");
		
		if(null == objNewPayType)
		{
			objNewPayType = document.createElement("span");
			objNewPayType.innerHTML += htmlstr;
		}

		oPayDiv.appendChild(objNewPayType);
		
		//focus on newly added type
		var oInp = gEBI('pay_' + curI + '_total');
		if(null != oInp)
		{
			try{
				oInp.focus();
			}
			catch(e)
			{
			}
		}
	} //bDontDraw

	updateTotals();

	if((pTyp == "credit" || payType == "creditcardsave") && aryPayTypes.length > 0)
	{
		var lCCVal=	gOrderTotal-gTransactionTotal;
		if(lCCVal < 0) lCCVal = 0;
		gEBI('pay_' + curI + '_total').value = parseFloat(lCCVal).toFixed(2);
		gEBI('pay_' + curI + '_total').onblur();
		doSwipe(curI);
	}

	if(!isWeb)
		oType.selectedIndex=0;
}

function TotalDiscounts(oItDiscount,k)
{
       
	    var oNextItemDiscount = oItDiscount;
	    var nLimitMax=0;
	    var oItem=gEBI("hItemOrder_"+k);
	    var nDollarAmount;
	    var nPercentageAmount;
	    var TotalDiscounts=0;
	    var nDiscountAmount = 0;
	    do{
		oNextItemDiscount = getNextSibling(oNextItemDiscount);
		//alert("oNextItemDiscount=" + oNextItemDiscount);
		if(null == oNextItemDiscount)
			break;
		//alert("oNextItemDiscount.tagName=" + oNextItemDiscount.tagName);
		if("INPUT" != oNextItemDiscount.tagName)
			continue;
		//alert("oNextItemDiscount.type=" + oNextItemDiscount.type);
		if("hidden" != oNextItemDiscount.type)
			continue;
//		alert("oNextItemDiscount.name=" + oNextItemDiscount.name);
		var nDollarAmount = oNextItemDiscount.getAttribute("dollaramount");
		var nPercentageAmount = oNextItemDiscount.getAttribute("percentageamount");
		var nLimit = oNextItemDiscount.getAttribute("Limit");

		//alert(nLimit);
		if (oItem.getAttribute("Quantity")>=nLimit && nLimitMax<nLimit)
		{
		  if (nLimit>nLimitMax)
		     {nLimitMax=nLimit;
		      nDollarAmount = oNextItemDiscount.getAttribute("dollaramount");
		      nPercentageAmount = oNextItemDiscount.getAttribute("percentageamount");
		      
		      if (nDollarAmount!=null)
		        { TotalDiscounts=nLimitMax*nDollarAmount;
		          oItem.setAttribute("DiscountId",oNextItemDiscount.getAttribute("discountID"));
		          oItem.setAttribute("DiscountAmount",parseFloat(nDollarAmount).toFixed(2));
		          oItem.setAttribute("Limit",oNextItemDiscount.getAttribute("Limit"));
		        }
			  else
				 { TotalDiscounts=( (oItem.getAttribute("ListPrice")*nPercentageAmount)/100)*nLimitMax ;
				   oItem.setAttribute("DiscountId",oNextItemDiscount.getAttribute("discountID"));
		           oItem.setAttribute("DiscountAmount", parseFloat((oItem.getAttribute("ListPrice")*nPercentageAmount)/100).toFixed(2) );
		           oItem.setAttribute("Limit",oNextItemDiscount.getAttribute("Limit"));
				 }
		  
				gEBI("txtItemOrderDiscount_"+k).value=TotalDiscounts.toFixed(2);
		    
		     }
		   
		}
		}while(oNextItemDiscount != null);
		


		return TotalDiscounts;
}

function CheckTransactionTotals(id, bShowMsg) {
	if(bShowMsg == null)
		bShowMsg = true;
	gTransactionTotal = 0;
	//gTransactionTotalTPS=0;
	var thisTotal = 0;
  	var subTotal = parseFloat(gOrderTotal).toFixed(2);
  	//var subTotalTPS=parseFloat(gOrderTotalTPS).toFixed(2);
	if (!isWeb && aryPayTypes.length > 0) {//!isWeb
		for (pt=0;pt<aryPayTypes.length;pt++) {
			ptHTMLIdx = aryPayTypes[pt].initIndex;
			//paymetType=(aryPayTypes[pt].Value).replace(" ","");	
			
			var cpval = 0;
			if((null!=gEBI('RedeemedCouponPatron'+ptHTMLIdx))&&(gEBI('RedeemedCouponPatron'+ptHTMLIdx).checked)){
				cpval = gEBI('selPatronCoupon'+ptHTMLIdx).options[gEBI('selPatronCoupon'+ptHTMLIdx).selectedIndex].getAttribute('CouponValue');
			}
			else if((null!=gEBI('RedeemedCouponCode'+ptHTMLIdx))&&(gEBI('RedeemedCouponCode'+ptHTMLIdx).checked)){
				cpval = gEBI(String('pay_' + ptHTMLIdx + '_code')).getAttribute('CouponValue');
			}
			
			if(null != gEBI(String('pay_' + ptHTMLIdx + '_total')))
				thisTotal = Number(gEBI(String('pay_' + ptHTMLIdx + '_total')).value);
			
			gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
		}
	}else{//isWeb
		var cnt = 0;
		var oTable = gEBI('tblPay'+cnt);
		while(oTable != null)
		{
			if(oTable.style.display != "none" && null != gEBI('pay_' + cnt + '_total'))
			{
				thisTotal = Number(gEBI(String('pay_' + cnt + '_total')).value);
				gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
			}
			
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
	}
	
	gTransactionTotal=NumAccuracy(gTransactionTotal, 2);
	if(null == gEBI("displayOrderBalanceTotal")) 
		return;

	gEBI("displayOrderBalanceTotal").value = FormatCurrency(subTotal - gTransactionTotal,2);
	//check balance; set tdBalance.innerHTML = to appropriate wording (overpayment,etc.) and if donations or PWYC exist then pop-up confirmation to do with balance
	if (gTransactionTotal < subTotal ) {//check if undefined discount exists
		//processAnyway = confirm("Payment transactions are not sufficient for order total.\n\nAre you sure you wish to continue?");
		//return processAnyway;
		//if(bShowMsg)
		//	alert(GetTranslation("Payment_transactions_are_not_order_total")+".");
			return false;   //
	} else if (gTransactionTotal > subTotal) {//check if donation exists
		/*if(bShowMsg)
			alert("Current payments are $ " + FormatCurrency(gTransactionTotal-subTotal,2) + " greater than the order total. Please correct payments before completing the order.")
		*/ return true;
	} else {
			gEBI("displayOrderBalanceTotal").value = FormatCurrency(subTotal - gTransactionTotal,2);
		return true;
	}
	
	
}

function RemovePaymentType(pType, pTypIndex)
{
	var nAry = aryPayTypes;
	var bWasRemoved = false;
	
	for (var i=0; i<nAry.length; i++)
	{
		if (nAry[i].initIndex == pTypIndex)
		{
			nAry.splice(i, 1);
			bWasRemoved = true;
			bTPSTransaction=false;
			break;
		}
	}

	if(bWasRemoved)
	{
		aryPayTypes = nAry;
		//removing table for this method
		var oTbl = gEBI('tblPay' + pTypIndex);
		if(null != oTbl)
		{
			var oBR = getNextSibling(oTbl);
			oTbl.parentNode.removeChild(oTbl);
			if(oBR)
				oBR.parentNode.removeChild(oBR);
		}
		updateTotals();
	}
}

function CreatePayTypeControl(p,sSubName,sType,sValues)
{
	if("input" == sType)
		return '<input type="text" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="" onfocus="select();" />';
	if("checkbox" == sType)
		return '<input type="checkbox" onclick="gEBI(\'pay_' + p + sSubName+ '\').value=this.checked;">'+
			'<input type="text" style="display:none" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="false" onfocus="select();" />';
	if("dropdown" == sType)
	{
		var arrValues = sValues.split(";");
		strValues = '<select name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '">';
		for(var i=0; i<arrValues.length-1;i++)
			strValues +='<option value="'+arrValues[i]+'" >'+arrValues[i];
		strValues += '</select>';		
		return strValues;
	}
	if("radiobutton" == sType)
	{
		var arrValues = sValues.split(";");
		strValues = '<table>';
		for(var i=0; i<arrValues.length-1;i++)
			strValues +='<tr><td>'+ arrValues[i] +'</td><td><input type="radio" value="'+arrValues[i]+'" name="selPay_' + p + sSubName+ '" id="selPay_' + p + sSubName+ '" onclick="gEBI(\'pay_' + p + sSubName+ '\').value=this.value;"></td></tr>';
		strValues += '</table>';
		strValues += '<input type="text" style="display:none" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="" onfocus="select();" />';
		return strValues;
	}
}

function setDefaultPaymentType(DefaultPaymentTypeId)
{
	if (null!=gEBI("paymentmethodUniqueId"))
	 {
	    var obj=gEBI(gEBI("paymentmethodUniqueId").value);	
	    if(obj==null) 
			obj=gEBN(gEBI("paymentmethodUniqueId").value)[0];
	    
	    for(var i = 0; i<obj.options.length; i++)
	    {
	    if (null!=obj.options[i].getAttribute("PaymenttypesClientId"))
	       if ( obj.options[i].getAttribute("PaymenttypesClientId")==DefaultPaymentTypeId)
			   {
			     AddPaymentType(obj.options[i].value,obj);
			     if(gEBI('pay_0_total') != null)
					window.setTimeout(function(){gEBI('pay_0_total').value = parseFloat(gOrderTotal).toFixed(2)}, 100);
			     return;
			   }
			  
	    }
	 }
}
//---------------------------------------------------------------------------

//----------------------:Registeredpatron---------------------------------------------------------
function checkRegisteredpatron()
 {
 	if (checkoutway==1 || checkoutway==3)
	{
		if (null!=gEBI("txtLoginEmail"))
		   if ((gEBI("txtLoginEmail").value).length==0)
		   {
		     alert('Please enter email address');
		      return false;
		   }
				if (null!=gEBI("txtLoginPassword"))
		   if ((gEBI("txtLoginPassword").value).length==0)
		   {
		      alert('Please enter your password');
		      return false;
		   }
	}
	return true;
	
 }
//-------------------------------------------------------------------------------------------------

//----------------------:ProcessOrder--------------------------------------------------------------
function Wait(ContainPrintAtHome)
{    
	ShowProgressbarDark();

	if (!checkRegisteredpatron())
	{
		HideProgressbarDark();
		return false;
	}
	
	if(!setWebTransactions()) 
	{
		HideProgressbarDark();
		return false;
	}
	
	if (!checkDueTransaction())
	{
		if(!isWeb)
		{
			alert("You cannot process an order with balance due.  Please make adequate payment for this order.");
			HideProgressbarDark();
			return false;
		}
		if(isWeb)
		{
			alert("You cannot process an order with balance due.  Please make adequate payment for this order.")
			HideProgressbarDark();
			return false;
		}
	}

    var lWinOnBeforeUnload = window.onbeforeunload;
    window.onbeforeunload = null;

	flag = OnOrderPay(ContainPrintAtHome);
	
	if(!flag) {
	    window.onbeforeunload = lWinOnBeforeUnload;
		HideProgressbarDark();
		return false;
	}
	
	return true;
}

function EraseOrderData(pOrderOnly)
{
	gOrder["TicketsXML"] = gOrder["SubscriptionsXML"] = gOrder["CouponOrdersXML"]
				= gOrder["CouponPackageOrdersXML"]= gOrder["ItemOrdersXML"] = "";
	
	if(null == pOrderOnly || false == pOrderOnly)
	{
		//erase payment options for previous order			
		aryPayTypes = new Array();
		htmlstr = "";
	}
}

function EnableDisableTransaction()
{
	if(!(isWeb)) return;
	
	var oSel = gEBI(gEBI("paymentmethodUniqueId").value);
	if(null == oSel) return;
	
	var cnt = 0;
	var oTable = gEBI('tblPay'+cnt);
	
	if(gOrderTotal <= 0)
	{
		oSel.disabled = true;
		while(oTable != null)
		{
			oTable.style.display = "none";
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
	}
	else
	{
		oSel.disabled = false;
		SwitchWebPaymentType(null,oSel, null,true);
	}
}

function SwitchWebPaymentType(pTyp, oType, bDontDraw,DontBuildArray)
{
	//hide all transaction tables besides the one selected
	//var cnt = 0;
	//var oTable = gEBI('tblPay'+cnt);
		
	if(DontBuildArray == null) DontBuildArray=false;
	
	if(!DontBuildArray) aryPayTypes = new Array();	
	
	var oTables = $("#divPayMethods table[id^=tblPay]");
	
	//loop in reverse order so that we process CC as last
	for(var i=oTables.length-1;i>=0;i--)
	{
		var oTable = oTables[i];
		var cnt = i;
		
		var oSpanPayRemove = gEBI("spanPayRemove"+cnt);
		if(oType.selectedIndex != cnt && oTable.getAttribute("paymentvalue")!=oType.value)
		{
			//hide logic to remove tables for now, AJFF
			if(oTable.getAttribute("paymentvalue") != "voucher"
			&& oTable.getAttribute("ptval") != "voucher") //dont hide multiple vouchers on web
			{
				oTable.style.display = "none";
				if(null != oSpanPayRemove)
					oSpanPayRemove.style.display = "inline";
			}
		}
		else
		{
			oTable.style.display = "block";
		}
			
		if(oTable.style.display == "block")
		{	
			var curVal = parseFloat(gEBI('pay_'+cnt+'_total').value);
			
			if(oTable.getAttribute("ptval") != "voucher")
				gEBI('pay_'+cnt+'_total').value="0.00";

			CheckTransactionTotals(null, false);
			
			if(oTable.getAttribute("ptval") != "voucher") 
				toggleWebStuff(cnt);
			else 
				getCouponAmount(gEBI('pay_'+cnt+'_code'), gEBI('pay_'+cnt+'_total'), false);

		}
		if(null != gEBI("pay_"+cnt+"_code") && gEBI("pay_"+cnt+"_code").value == "")
		{	
			gEBI("pay_"+cnt+"_code").value = GetTranslation("enter_code_here", "Enter Code Here");
			try{
				gEBI("pay_"+cnt+"_code").focus();
			}
			catch(e)
			{
			}
		}
		if(null != oSpanPayRemove)
		{
			oSpanPayRemove.style.display = "none";
		}

		if(!DontBuildArray)
			{
				aryPayTypes[cnt] = new Array();	
				var newPT = new Object();
				var selOption = oType.options[oType.selectedIndex];
				newPT.initIndex = cnt; //used to handle cases when paytypes are added and deleted and it is impossible to get paytype by index in aryPayTypes
				newPT.Name = selOption.innerHTML;
				newPT.Value = oType.value;
				newPT.TransactionTypeId = selOption.getAttribute('TransactionTypeId');
				newPT.PaymenttypesClientId = selOption.getAttribute('PaymenttypesClientId');
				newPT.IsStandart = selOption.getAttribute('IsStandart');
				newPT.CCTYPES = selOption.getAttribute('CCTYPES'); //coded presentation of available CCTYPES in form ID:Name,ID:Name,ID:Name
				aryPayTypes.push(newPT);
			}
	} //end for
	
}

function toggleWebStuff(pCnt){
	if(null == gEBI('divPayMethods')) return;
	if(isWeb){
		var lCCVal=	parseFloat(gEBI('txtTotal').value)-gTransactionTotal;
		if(lCCVal < 0) 
			lCCVal = 0;
		
		gEBI('pay_'+pCnt+'_total').value = parseFloat(lCCVal).toFixed(2);
		gEBI('divPayMethods').style.display = 'inline';
	}
}

function updateTotalItems()
{
  var tCount=0
  var tAmount=0; 
  var sCount=0
  var amountAmount=0; 
  
  if("undefined" != typeof(arguments[0]))
      tCount=arguments[0];
  if("undefined" != typeof(arguments[1]))
      tAmount=arguments[1];
  if("undefined" != typeof(arguments[2]))
      sCount=arguments[2];
  if("undefined" != typeof(arguments[3]))
      amountAmount=arguments[3];

  var  itemsCount=0;
  var  itemsAmount=0;
  for(var i=0;i<arrItems.length;i++)
	{
		if (null == arrItems[i])
			continue; 
		 
		itemsCount += parseInt(arrItems[i]["nTixQty"]);
		itemsAmount += itemsCount*parseFloat(arrItems[i]["nBaseAmount"]);
	}
	
  var wasPaid=0;
  if ( null!=gEBI('txtWasPaid') )
    wasPaid=parseFloat(gEBI('txtWasPaid').value);
  var grandTotal=0;
  if ( null!=gEBI('txtTotal') )
    grandTotal=parseFloat(gEBI('txtTotal').value);
    
  
  if( gEBI("itemsCount")!=null)
  {
  gEBI("itemsCount").innerHTML=itemsCount+" "+GetTranslation("Items");
  gEBI("ticketCount").innerHTML=tCount + " "+GetTranslation("Tickets1");
  gEBI("SeasonCount").innerHTML=sCount + " "+GetTranslation("SeasonTickets");
  gEBI("itemsAmount").innerHTML=GetTranslation("subtotal")+" $ "+FormatCurrency(grandTotal,2);
  //FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount)- wasPaid,2);
  //alert(itemsCount+GetTranslation("Items"));
  //alert(GetTranslation("SubTotal")+"_$ "+FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount),2));
   if (itemsCount<=0)
    gEBI("itemsCount").style.display="none";
  else
    gEBI("itemsCount").style.display="block";

  if (tCount<=0)
    gEBI("ticketCount").style.display="none";
  else
   { gEBI("ticketCount").style.display="block";
  
   }  
  if (sCount<=0)
    gEBI("SeasonCount").style.display="none";
  else
    gEBI("SeasonCount").style.display="block";
  
  if (FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount),2)<=0)
    gEBI("itemsAmount").style.display="none";
  else
    gEBI("itemsAmount").style.display="block";
    }

}

function OrderBuildTransactionsXML()
{
	//build xml for billing address
	var strBillingAddress = OrderBuildBillingAddressXML();
	//build xml for each payment type
	var nTotal = gOrderTotal;
	var bHasCashTransaction = false;

	strTransXML += "<Trnxs>";
	
	if (null!=gEBI("txtTotalTPS") && gEBI("txtTotalTPS").value>0){
		strTransXML += "<Transaction>" +
		    			"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
						"<TransactionType>" +
						"<ID>33</ID>" +
						"<Name>"+GetTranslationPaymentTypes("PaymentTypes_TPS")+"</Name>" +
						"</TransactionType>" +
						"<Amount>" + gEBI("txtTotalTPS").value  + "</Amount>";
		strTransXML += "</Transaction>";
	}
	for(var i=0; i<aryPayTypes.length;i++)
	{
		var curI = aryPayTypes[i].initIndex;
		
		switch(String(aryPayTypes[i].Value).toLowerCase())
		{
			case 'credit':
			case 'creditcardsave':
				var oInpCCNumber = gEBI(String('pay_' + curI + '_cardnumber'));
				var oInpExpMM = gEBI(String('pay_' + curI + '_expmo'));
				var oInpExpYY = gEBI(String('pay_' + curI + '_expyr'));
				var oInpCVV = gEBI(String('pay_' + curI + '_cvvnumber'));
				var oSelectCCType = gEBI(String('pay_' + curI + '_cardtype'));
				var oCardFirstName = gEBI(String('pay_' + curI + '_firstname'));
				var oCardLastName = gEBI(String('pay_' + curI + '_lastname'));
				var oInpCCwasSwiped = gEBI(String('CCwasSwiped' + curI));
				var oSig = gEBI(String('pay_' + curI + '_siginput'));
				var sSig = (oSig != null && oSig != "undefined")?oSig.value:"";
				
				var ccwasSwiped = "false";
				if(oInpCCwasSwiped != null)
					ccwasSwiped = oInpCCwasSwiped.value;

				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;


				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" +
									"<TransactionType>" +
										"<ID>"+aryPayTypes[i].TransactionTypeId+"</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_Credit Card")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount + "</Amount>" +
									strBillingAddress;
				//must check validity of ccnumber
						IsCCValid = validCCForm(Number(oSelectCCType.value), oInpCCNumber, oInpExpMM, oInpExpYY);
						var IsCVVValid =  (oInpCVV != null && oInpCVV.value.indexOf('.') < 0)?true:false;
						if(!IsCVVValid)
						{
							alert("Credit Card CVV Incorrect")
							return false;
						}		
						if(!IsCCValid)
						{
							//alert("Credit Card Incorrect")
							return false;
						}

						strTransXML += 	"<CreditCard>" +
											"<CCTYPE>" +
												"<ID>" + Number(oSelectCCType.value) + "</ID>" +
												"<Name>" + oSelectCCType[oSelectCCType.selectedIndex].innerHTML +"</Name>" +
											"</CCTYPE>" +
											"<Number>" + oInpCCNumber.value + "</Number>" +
											"<SigString><![CDATA[" + sSig + "]]></SigString>" +
											"<ExpiryMonth>" + oInpExpMM.value + "</ExpiryMonth>" +
											"<ExpiryYear>" + oInpExpYY.value + "</ExpiryYear>" + 
											"<WasSwiped>" + ccwasSwiped + "</WasSwiped>";
						
						if(oCardFirstName != null && oCardLastName != null)
							strTransXML += 	"<FirstName><![CDATA["+oCardFirstName.value+"]]></FirstName>"+
											"<LastName><![CDATA["+oCardLastName.value+"]]></LastName>";
							
						var anum=/(^\d+$)|(^\d+\.\d+$)/
						if(Trim(oInpCVV.value) != "" && !anum.test(Trim(oInpCVV.value)))
						{
							alert("CVV is incorrect.  Please click the ? link next to CVV Number for an explanation on what a CVV is.")
							return false;
						}
						if(Trim(oInpCVV.value) != "")
							strTransXML += "<CVV>" + oInpCVV.value + "</CVV>";

						strTransXML += "</CreditCard>";
						
					if(oCardFirstName != null && oCardLastName != null)
					{
						strTransXML += "<CheckNumber><![CDATA[" + oCardFirstName.value + " " + oCardLastName.value + "]]></CheckNumber>";
					}
				strTransXML += "</Transaction>";
				break;

			case 'cash':
				bHasCashTransaction = true;
				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>1</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_cash")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount  + "</Amount>";

				strTransXML += "</Transaction>";
				break;

			case 'check':
				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>3</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_check")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount  + "</Amount>" +
									"<CheckNumber>" + gEBI(String('pay_' + curI + '_checknumber')).value + "</CheckNumber>";

				strTransXML += "</Transaction>";
				break;

			case 'travellers':
				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>6</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_travellers")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + gEBI(String('pay_' + curI + '_total')).value  + "</Amount>";

				strTransXML += "</Transaction>";
				break;

			case 'voucher':
						var rcID = 0;
						var cpval = 0;
						var nVoucherAmount = gEBI(String('pay_' + curI + '_total')).value
					if(isNaN(nVoucherAmount) || nVoucherAmount == '')
						nVoucherAmount  = nTotal;
					if(isNaN(nVoucherAmount) || nVoucherAmount == '')
						nVoucherAmount = 0;
						try{
						if(gEBI('RedeemedCouponPatron'+curI).checked){
							rcID = gEBI('selPatronCoupon'+curI).options[gEBI('selPatronCoupon'+curI).selectedIndex].getAttribute('RedeemedCoupon');
							cpval = gEBI('selPatronCoupon'+curI).options[gEBI('selPatronCoupon'+curI).selectedIndex].getAttribute('CouponValue');
						}
						else{
							rcID = gEBI(String('pay_' + curI + '_code')).getAttribute('RedeemedCoupon');
							cpval = gEBI(String('pay_' + curI + '_code')).getAttribute('CouponValue');
						}
						}
						catch(e)
						{
							cpval = gEBI(String('pay_' + curI + '_total')).value
							rcID = 0;
						}
						if(parseFloat(cpval) < parseFloat(gEBI(String('pay_' + curI + '_total')).value))
						{	
							strAlert ="The amount due is $"+parseFloat(gEBI(String('pay_' + curI + '_total')).value).toFixed(2)+" which is greater than the coupon '"+gEBI(String('pay_' + curI + '_code')).value+"' amount ($"+parseFloat(cpval).toFixed(2)+"). \n\tPlease add another coupon, cash or creditcard transaction."
							//alert(strAlert);
							//return false;
						}
				if(rcID == null || rcID == "null")
					rcID = 0;
				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>7</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_voucher")+"</Name>" +
									"</TransactionType>" +
									"<RedeemedCouponId>" + rcID + "</RedeemedCouponId>" +
									"<Amount>" + nVoucherAmount  + "</Amount>";
				//alert(nVoucherAmount)
				if(rcID == 0)
					strTransXML += "<CheckNumber>" + gEBI(String('pay_' + curI + '_code')).value + "</CheckNumber>";
				strTransXML += "</Transaction>";
				break;

			case 'comp':
			var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>4</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_comp")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>" +
									"<CompNote>" + gEBI(String('pay_' + curI + '_note')).value + "</CompNote>";

				strTransXML += "</Transaction>";
				break;
				
			case 'prepaid':
				var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>9</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_prepaid")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>" +
									"<Note>" + gEBI(String('pay_' + curI + '_note')).value + "</Note>";

				strTransXML += "</Transaction>";
				break;
			default:
				//PayPal, WebMoney, Wire Transfer are processed just as custom paytypes
				var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>"+aryPayTypes[i].TransactionTypeId+"</ID>" +
										"<Name><![CDATA["+GetTranslationPaymentTypes("PaymentTypes_"+aryPayTypes[i].Name)+"]]></Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>";
									if("true" == aryPayTypes[i].IsEnabledCustom1)
										strTransXML += "<CustomField1>"+ gEBI(String('pay_' + curI + '_customfield1')).value +"</CustomField1>";
									if("true" == aryPayTypes[i].IsEnabledCustom2)
										strTransXML += "<CustomField2>"+ gEBI(String('pay_' + curI + '_customfield2')).value +"</CustomField2>";
									if("true" == aryPayTypes[i].IsEnabledCustom3)
										strTransXML += "<CustomField3>"+ gEBI(String('pay_' + curI + '_customfield3')).value +"</CustomField3>";
									if("true" == aryPayTypes[i].IsEnabledCustom4)
										strTransXML += "<CustomField4>"+ gEBI(String('pay_' + curI + '_customfield4')).value +"</CustomField4>";
									if("true" == aryPayTypes[i].IsEnabledCustom5)
										strTransXML += "<CustomField5>"+ gEBI(String('pay_' + curI + '_customfield5')).value +"</CustomField5>";
				strTransXML += "</Transaction>";
				break;
		}

	}//end Transaction for loop
	
	//check for overpayment with cash and do auto cash trans for change given back
	if(bHasCashTransaction && parseFloat(gEBI("displayOrderBalanceTotal").value) < 0)
	{
		strTransXML += "<Transaction>" +
			"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
			"<TransactionType>" +
				"<ID>1</ID>" +
				"<Name>"+GetTranslationPaymentTypes("PaymentTypes_cash")+"</Name>" +
			"</TransactionType>" +
			"<Amount>" + parseFloat(gEBI("displayOrderBalanceTotal").value)  + "</Amount>";
			strTransXML += "</Transaction>";
	}

	/*check for preloaded payment data*/
	if ($("#divPreloadedPayment input") != null) {
	    strTransXML += $("#divPreloadedPayment input").val() ;
	}

	strTransXML += "</Trnxs>";
	gCurrentPaymentXML = strTransXML;
	return strTransXML;
}

function validCCForm(nCcType,ccNumField,ccExpFieldMM,ccExpFieldYY)
{
	var result = isValidCreditCardNumber(ccNumField, nCcType, "Credit Card Number", true)
			&& isValidExpDate(ccExpFieldMM, ccExpFieldYY,"Expiration Date",true);

	return result;
}

function validRequired(formField,fieldLabel)
{
	var result = true;

	if (formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}

	return result;
}

function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;

	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}

	return result;
}

function validateCCNum(cardType,cardNum)
{
	var result = false;
	//cardType = cardType.toUpperCase();

	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case 1: //"VISA"
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case 2: //"MASTERCARD"
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case 3: //"DISCOVER"
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case 4: //"AMEX"
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case 5: //"DINERS"
			var validNums = "068";
			result = (cardLen == 14) && (first4digs == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case 6: //"Bankcard"
			//var validNums = "068";
			result = (cardLen == 16) ;//&& (first4digs == "5610"); //&& (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function isValidExpDate(formFieldMM, formFieldYY,fieldLabel,required)
{
	var result = true;

	if (required && !validRequired(formFieldMM,fieldLabel))
		return false;

	if(required && !validRequired(formFieldYY,fieldLabel))
		return false;

 	if (result &&
 		(formFieldMM.value.length>0) &&
 		(formFieldYY.value.length>0))
 	{
 		var elems = new Array();
 		elems[0] = formFieldMM.value;
 		elems[1] = formFieldYY.value;

 		result = (elems.length == 2); // should be two components
 		var expired = false;

 		var month = parseInt(elems[0],10);
 		var year = parseInt(elems[1],10);

 		if (elems[1].length == 2)
 			year += 2000;

 		var now = new Date();

 		var nowMonth = now.getMonth() + 1;
 		var nowYear = now.getFullYear();

 		expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));

		result = allDigits(elems[0]) && (month > 0) && (month < 13);

 		if (!result)
 		{
 			alert('Please enter a date in the format MM for the "' + fieldLabel +'" field.');
			formFieldMM.focus();
			return result;
		}

		//YY field
		result = allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
		if (!result)
 		{
 			alert('Please enter a date in the format YY or YYYY for the "' + fieldLabel +'" field.');
			formFieldYY.focus();
			return result;
		}

		if (expired)
		{
 			result = false;
 			alert('The date for "' + fieldLabel +'" has expired.');
			formFieldMM.focus();
		}
	}

	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;

  	if (result && (formField.value.length>0))
 	{
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}

		if (result)
 		{

 			if (!validateCCNum(ccType,ccNum) || !LuhnCheck(ccNum))
 			{
 				alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}
		}

	}

	return result;
}

function LuhnCheck(str)
{
  var result = true;

  var sum = 0;
  var mul = 1;
  var strLen = str.length;

  for (i = 0; i < strLen; i++)
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;

  return result;
}

function UpdateTotalForWeb(amount)
{
	var countPayments = 0;
	try{
		var oPaymentTables = $("#divPayMethods table[id^=tblPay]");
		if(oPaymentTables != null)
			countPayments = oPaymentTables.length;
	}catch(e){}
	
	if(isWeb || (gQuickSaleMode && countPayments == 1))
	{
		//update all trans types totals
		var cnt = 0;
		var oTot = gEBI('pay_' + cnt + '_total');
		do{
			if(oTot != null)
				{					
					if(oTot.getAttribute("predefinedlimit")!=null && parseInt(oTot.getAttribute("predefinedlimit"))>0){
						if(parseInt(oTot.getAttribute("predefinedlimit"))<amount)
							{
								oTot.value=oTot.getAttribute("predefinedlimit");
							}
						else
							{
								oTot.value = amount;
							}
					}
					else
					{
						oTot.value = amount;
						}
				}
				
				
			cnt++;
			oTot = gEBI('pay_' + cnt + '_total');
		}
		while(oTot != null)
	
		
	}
}

function checkDueTransaction(){
    oModeSelect=gEBI("UserModeSelect"); 		
    if(null == oModeSelect)
    {
		oModesDiv = gEBI("BoxRightDiv");
		oModeSelects = getChildrenByPartialIdOrName(oModesDiv, "ModesDropDown", true, true);
		if(null != oModeSelects && oModeSelects.length > 0)
			oModeSelect = oModeSelects [0];
    }
    
    if (null!=oModeSelect)
    {
		var isDueAttrib = oModeSelect.getAttribute("isduetransaction");
		if(isDueAttrib == null)
			isDueAttrib = oModeSelect.getAttribute("isDueTransaction");
		if(isDueAttrib == null)
			isDueAttrib = "false";
			
		var bIsDueTransaction = ( isDueAttrib.toLowerCase() == "true")?true:false;		
		if(bIsDueTransaction) 
			return true;
	}
	else
	{
		if(!isWeb)
			return true;
	}


	tempSubTotal=0;
	gTransactionTotal = 0; 
	var thisTotal = 0;
  	var subTotal = parseFloat(gOrderTotal).toFixed(2);
	if (aryPayTypes.length > 0) 
	{
		for (var pt=0;pt<aryPayTypes.length;pt++) 
		{	
			var paymentType=(aryPayTypes[pt].Value).replace(" ","");
			var idx = aryPayTypes[pt].initIndex;
			var cpval = 0;
			if((null!=gEBI('RedeemedCouponPatron'+idx))&&(gEBI('RedeemedCouponPatron'+idx).checked))
				cpval = gEBI('selPatronCoupon'+idx).options[gEBI('selPatronCoupon'+idx).selectedIndex].getAttribute('CouponValue');
			else if((null!=gEBI('RedeemedCouponCode'+idx))&&(gEBI('RedeemedCouponCode'+idx).checked))
				cpval = gEBI(String('pay_' + idx + '_code')).getAttribute('CouponValue');
				
			if(null != gEBI(String('pay_' + idx + '_total')))
				thisTotal = Number(gEBI(String('pay_' + idx + '_total')).value + cpval);
			if (paymentType != "TPS")	
				gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
		}
	}
	if ( NumAccuracy(gTransactionTotal, 2)<subTotal)
		return false;
	else 
		return true;
}

function setWebTransactions()
{
	//if it's web trans, then we should build aryPayTypes manually from available HTML
	if(isWeb)
	{
		aryPayTypes = new Array();
		var cnt = 0;
		var oTable = gEBI('tblPay'+cnt);
		while(oTable != null)
		{
			if(oTable.style.display != "none")
			{
				var oTr = new Object();
				oTr.TransactionTypeId = oTable.getAttribute("ptid");
				oTr.Name = oTable.getAttribute("ptname");
				oTr.initIndex = oTable.getAttribute("ptidx");
				oTr.Value = oTable.getAttribute("ptval");
				aryPayTypes.push(oTr);
				//break;
			}
		
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
		if(0 == aryPayTypes.length && gOrderTotal > 0)
		{
			alert("Do not have any transactions in web mode");
			return false;
		}
		if(null != gEBI("displayOrderBalanceTotal"))
		{
			if(Number(gEBI("displayOrderBalanceTotal").value) > 0)
			{
				alert("You cannot process an order with balance due.  Please make adequate payment for this order.");
				return false;
			}
		}	
	}
	return true;
}

function Barcode(obj, e) {
    if (!e)
        e = window.event;
    if (e.keyCode == 13) {
        var strSoapMessage = '<Envelope><Body><Item><BarCode>' + obj.value + '</BarCode></Item></Body></Envelope>';

        ShowProgressbar();
        $.post("Sales_LookupItemByBarCode.aspx", strSoapMessage, function (data) {
            BarcodeComplete(data, obj);
        });

    }
}

function BarcodeComplete(strInnerResp, obj) {
    obj.value = "";
    if ("" == strInnerResp) {
        ShowProgressbar();
        return;
    }

    var itemId = $($(strInnerResp).find('Item')).find('ID').text();
    if (itemId != null && !isNaN(itemId))
        addOneItemToBasket(itemId);
    else
        HideProgressbar();
}

function addOneItemToBasket(itemID, nCategoryType)
{
	var str = "<Order>\r\n";
	str += "<Items>\r\n";
	str += "<Item ID=\"" + itemID + "\" Count=\"1\">";
	/*Add category type if passed*/
	if(nCategoryType != null)
		str += "<Category><CategoryType>" + nCategoryType + "</CategoryType></Category>";
	str += "</Item> \r\n";
	str += "</Items>\r\n";
	str += "</Order>";
	
	submitformtocart(str);
	return false;
}

function addOneCouponToBasket(couponID)
{
	var str = "<Order>\r\n";
	str += "<Coupons>\r\n";
	str += "<Coupon ID=\"" + couponID + "\" Count=\"1\" />\r\n";
	str += "</Coupons>\r\n";
	str += "</Order>";
	
	submitformtocart(str);
	return false;
}

function submitformtocart(formXML)
{
	var myform=document.createElement("form");
	
	myform.action = "EventsPage.aspx";
	if(window.location.protocol != 'https:' && gIsHttpsSwitchRequired)
	{
		var strPath = window.location.pathname;
		strPath = strPath.substr(0, strPath.lastIndexOf("/") + 1);
		myform.action = 'https://'+ window.location.host + strPath + "EventsPage.aspx"; 
	}
	myform.method = "POST";
	
	//add hidden input with some xml
	var hiddenXML = document.createElement("input");
	hiddenXML.name = "ShoppingCartXML";
	hiddenXML.type = "hidden";
	hiddenXML.value = formXML;
	myform.appendChild(hiddenXML);
	
	//append it to body and post
	document.body.appendChild(myform);

	//disable unload page warning
	if('function'==typeof(disableUnloadPageWarning)) disableUnloadPageWarning();

	myform.submit();
}

var gbCanSubmitShoppingCart=false;

function OnOrderPay(ContainPrintAtHome)
{
	var strOrderXML=GenerateOrderXML(ContainPrintAtHome);
		
	if(strOrderXML == false) 
		return false;
	if(strOrderXML == "") 
		return false;

	gCurrentOrderXML = strOrderXML;
		
	$("#divProcessOrderXML > input").val(strOrderXML);
	
	if($("#selSuperUserInventories").length > 0)
		$("#divInventory_Input > input").val(  $("#selSuperUserInventories").val()  );
	
	gbCanSubmitShoppingCart = true;
	
	//$("#Process_Order_Div > input").click();
	
	//var evTarget = $("#Process_Order_Div > input").attr("name");
	//var evArgument = "";
	
	SubmitOrder(); //this function is dynamically generated in eventspage.aspx
	
	return true;
}

function CanSubmitShoppingCart()
{
	return gbCanSubmitShoppingCart;
}

function ConfirmPrintOrder(nID)
{
	if(null != gEBI("orderConf_amountDue") && parseFloat(gEBI("orderConf_amountDue").value) <= 0)
		if(confirm(GetTranslation("Would_you_like_to_print")))
			DoQuickPrintNewWay(nID);
}

function ShowPrintWindowPAH(url,strXML,clid)
{
	if(strXML==null) 
		strXML="<a>a</a>";
		
	var curFrameHTML= '<iframe name="PAHiframe" id="PAHiframe" src="'+url+'" frameBorder="2" width="96%" height="590px" scrolling="auto" /></iframe>';
	//var PrinterHTML='<span id="printicon" class="Printer" onclick="PrintAllInFramePAH();"><img src="images/print-now.gif"></span>'; 
		
	var curHTML = '<DIV class="SectionDivContent">';
	curHTML +=	curFrameHTML;
	curHTML += '</DIV>';
	
	$('#divCart').html(curHTML);
	
	modaldialogfromdiv("divCart", 800, "auto", false, "Print Form");
	
	//if($("#printicon").length <= 0)
	//	$('.ui-dialog-titlebar-close').parent().append(PrinterHTML);
	
	return false;
}
function PrintAllInFramePAH()
{
	window.frames["PAHiframe"].focus();
	window.frames["PAHiframe"].print();
	return;	
}
function DoPrintAtHome(sOrderId)
{
	ShowPrintWindowPAH("PrintAtHomeStandard.aspx?showImg=1&oid=" + sOrderId, null, gClientId)
	return;
	
	/*var bpopUp=0;
	
	if(arguments[1] == null) bpopUp = 1;
	else bpopUp=arguments[1];
	
	if(bpopUp == 1)
		window.open("PrintAtHomeStandard.aspx?oid=" + sOrderId, "_blank","menubar=yes,status=no,location=no,scrollbars=yes,titlebar=yes,top=0,left=0,directories=no");
	else
		window.location.url = "PrintAtHomeStandard.aspx?oid=" + sOrderId ;
	*/
}

function ShowConfirmation(strOrderXML)
{
	//hide all DIVs except cart page
	document.getElementById("divCart").style.display = "none";
	if(document.getElementById("divServerCart")!=null) document.getElementById("divServerCart").style.display = "none";
	document.getElementById("divConfirm").style.display = "inline";
	embedHTTPPage("OrderConfirmation.aspx?checkoutway="+checkoutway, strOrderXML, "divConfirm");
	gEBI('divConfirm').innerHTML = unescape(gEBI('divConfirm').innerHTML);
	try{
		window.scrollTo(0,0);
		//gEBI("TopGoButton1").focus();
	}
	catch(e){}	
}

//-------------------------------------------------------------------------------------------------

function HtmlDecode(s)
{
	var out = "";
	if (s==null) return;
	var l = s.length;
	for (var i=0; i<l; i++)
	{
		var ch = s.charAt(i);
		if (ch == '&')
		{
			var semicolonIndex = s.indexOf(';', i+1);
			if (semicolonIndex > 0)
			{
				var entity = s.substring(i + 1, semicolonIndex);
				if (entity.length > 1 && entity.charAt(0) == '#')
				{
					if (entity.charAt(1) == 'x' || entity.charAt(1) == 'X')
						ch = String.fromCharCode(eval('0'+entity.substring(1)));
					else
						ch = String.fromCharCode(eval(entity.substring(1)));
				}
				else
				{
					switch (entity)
					{
						case 'quot': ch = String.fromCharCode(0x0022); break;
						case 'amp': ch = String.fromCharCode(0x0026); break;
						case 'lt': ch = String.fromCharCode(0x003c); break;
						case 'gt': ch = String.fromCharCode(0x003e); break;
						case 'nbsp': ch = String.fromCharCode(0x00a0); break;
						case 'iexcl': ch = String.fromCharCode(0x00a1); break;
						case 'cent': ch = String.fromCharCode(0x00a2); break;
						case 'pound': ch = String.fromCharCode(0x00a3); break;
						case 'curren': ch = String.fromCharCode(0x00a4); break;
						case 'yen': ch = String.fromCharCode(0x00a5); break;
						case 'brvbar': ch = String.fromCharCode(0x00a6); break;
						case 'sect': ch = String.fromCharCode(0x00a7); break;
						case 'uml': ch = String.fromCharCode(0x00a8); break;
						case 'copy': ch = String.fromCharCode(0x00a9); break;
						case 'ordf': ch = String.fromCharCode(0x00aa); break;
						case 'laquo': ch = String.fromCharCode(0x00ab); break;
						case 'not': ch = String.fromCharCode(0x00ac); break;
						case 'shy': ch = String.fromCharCode(0x00ad); break;
						case 'reg': ch = String.fromCharCode(0x00ae); break;
						case 'macr': ch = String.fromCharCode(0x00af); break;
						case 'deg': ch = String.fromCharCode(0x00b0); break;
						case 'plusmn': ch = String.fromCharCode(0x00b1); break;
						case 'sup2': ch = String.fromCharCode(0x00b2); break;
						case 'sup3': ch = String.fromCharCode(0x00b3); break;
						case 'acute': ch = String.fromCharCode(0x00b4); break;
						case 'micro': ch = String.fromCharCode(0x00b5); break;
						case 'para': ch = String.fromCharCode(0x00b6); break;
						case 'middot': ch = String.fromCharCode(0x00b7); break;
						case 'cedil': ch = String.fromCharCode(0x00b8); break;
						case 'sup1': ch = String.fromCharCode(0x00b9); break;
						case 'ordm': ch = String.fromCharCode(0x00ba); break;
						case 'raquo': ch = String.fromCharCode(0x00bb); break;
						case 'frac14': ch = String.fromCharCode(0x00bc); break;
						case 'frac12': ch = String.fromCharCode(0x00bd); break;
						case 'frac34': ch = String.fromCharCode(0x00be); break;
						case 'iquest': ch = String.fromCharCode(0x00bf); break;
						case 'Agrave': ch = String.fromCharCode(0x00c0); break;
						case 'Aacute': ch = String.fromCharCode(0x00c1); break;
						case 'Acirc': ch = String.fromCharCode(0x00c2); break;
						case 'Atilde': ch = String.fromCharCode(0x00c3); break;
						case 'Auml': ch = String.fromCharCode(0x00c4); break;
						case 'Aring': ch = String.fromCharCode(0x00c5); break;
						case 'AElig': ch = String.fromCharCode(0x00c6); break;
						case 'Ccedil': ch = String.fromCharCode(0x00c7); break;
						case 'Egrave': ch = String.fromCharCode(0x00c8); break;
						case 'Eacute': ch = String.fromCharCode(0x00c9); break;
						case 'Ecirc': ch = String.fromCharCode(0x00ca); break;
						case 'Euml': ch = String.fromCharCode(0x00cb); break;
						case 'Igrave': ch = String.fromCharCode(0x00cc); break;
						case 'Iacute': ch = String.fromCharCode(0x00cd); break;
						case 'Icirc': ch = String.fromCharCode(0x00ce ); break;
						case 'Iuml': ch = String.fromCharCode(0x00cf); break;
						case 'ETH': ch = String.fromCharCode(0x00d0); break;
						case 'Ntilde': ch = String.fromCharCode(0x00d1); break;
						case 'Ograve': ch = String.fromCharCode(0x00d2); break;
						case 'Oacute': ch = String.fromCharCode(0x00d3); break;
						case 'Ocirc': ch = String.fromCharCode(0x00d4); break;
						case 'Otilde': ch = String.fromCharCode(0x00d5); break;
						case 'Ouml': ch = String.fromCharCode(0x00d6); break;
						case 'times': ch = String.fromCharCode(0x00d7); break;
						case 'Oslash': ch = String.fromCharCode(0x00d8); break;
						case 'Ugrave': ch = String.fromCharCode(0x00d9); break;
						case 'Uacute': ch = String.fromCharCode(0x00da); break;
						case 'Ucirc': ch = String.fromCharCode(0x00db); break;
						case 'Uuml': ch = String.fromCharCode(0x00dc); break;
						case 'Yacute': ch = String.fromCharCode(0x00dd); break;
						case 'THORN': ch = String.fromCharCode(0x00de); break;
						case 'szlig': ch = String.fromCharCode(0x00df); break;
						case 'agrave': ch = String.fromCharCode(0x00e0); break;
						case 'aacute': ch = String.fromCharCode(0x00e1); break;
						case 'acirc': ch = String.fromCharCode(0x00e2); break;
						case 'atilde': ch = String.fromCharCode(0x00e3); break;
						case 'auml': ch = String.fromCharCode(0x00e4); break;
						case 'aring': ch = String.fromCharCode(0x00e5); break;
						case 'aelig': ch = String.fromCharCode(0x00e6); break;
						case 'ccedil': ch = String.fromCharCode(0x00e7); break;
						case 'egrave': ch = String.fromCharCode(0x00e8); break;
						case 'eacute': ch = String.fromCharCode(0x00e9); break;
						case 'ecirc': ch = String.fromCharCode(0x00ea); break;
						case 'euml': ch = String.fromCharCode(0x00eb); break;
						case 'igrave': ch = String.fromCharCode(0x00ec); break;
						case 'iacute': ch = String.fromCharCode(0x00ed); break;
						case 'icirc': ch = String.fromCharCode(0x00ee); break;
						case 'iuml': ch = String.fromCharCode(0x00ef); break;
						case 'eth': ch = String.fromCharCode(0x00f0); break;
						case 'ntilde': ch = String.fromCharCode(0x00f1); break;
						case 'ograve': ch = String.fromCharCode(0x00f2); break;
						case 'oacute': ch = String.fromCharCode(0x00f3); break;
						case 'ocirc': ch = String.fromCharCode(0x00f4); break;
						case 'otilde': ch = String.fromCharCode(0x00f5); break;
						case 'ouml': ch = String.fromCharCode(0x00f6); break;
						case 'divide': ch = String.fromCharCode(0x00f7); break;
						case 'oslash': ch = String.fromCharCode(0x00f8); break;
						case 'ugrave': ch = String.fromCharCode(0x00f9); break;
						case 'uacute': ch = String.fromCharCode(0x00fa); break;
						case 'ucirc': ch = String.fromCharCode(0x00fb); break;
						case 'uuml': ch = String.fromCharCode(0x00fc); break;
						case 'yacute': ch = String.fromCharCode(0x00fd); break;
						case 'thorn': ch = String.fromCharCode(0x00fe); break;
						case 'yuml': ch = String.fromCharCode(0x00ff); break;
						case 'OElig': ch = String.fromCharCode(0x0152); break;
						case 'oelig': ch = String.fromCharCode(0x0153); break;
						case 'Scaron': ch = String.fromCharCode(0x0160); break;
						case 'scaron': ch = String.fromCharCode(0x0161); break;
						case 'Yuml': ch = String.fromCharCode(0x0178); break;
						case 'fnof': ch = String.fromCharCode(0x0192); break;
						case 'circ': ch = String.fromCharCode(0x02c6); break;
						case 'tilde': ch = String.fromCharCode(0x02dc); break;
						case 'Alpha': ch = String.fromCharCode(0x0391); break;
						case 'Beta': ch = String.fromCharCode(0x0392); break;
						case 'Gamma': ch = String.fromCharCode(0x0393); break;
						case 'Delta': ch = String.fromCharCode(0x0394); break;
						case 'Epsilon': ch = String.fromCharCode(0x0395); break;
						case 'Zeta': ch = String.fromCharCode(0x0396); break;
						case 'Eta': ch = String.fromCharCode(0x0397); break;
						case 'Theta': ch = String.fromCharCode(0x0398); break;
						case 'Iota': ch = String.fromCharCode(0x0399); break;
						case 'Kappa': ch = String.fromCharCode(0x039a); break;
						case 'Lambda': ch = String.fromCharCode(0x039b); break;
						case 'Mu': ch = String.fromCharCode(0x039c); break;
						case 'Nu': ch = String.fromCharCode(0x039d); break;
						case 'Xi': ch = String.fromCharCode(0x039e); break;
						case 'Omicron': ch = String.fromCharCode(0x039f); break;
						case 'Pi': ch = String.fromCharCode(0x03a0); break;
						case ' Rho ': ch = String.fromCharCode(0x03a1); break;
						case 'Sigma': ch = String.fromCharCode(0x03a3); break;
						case 'Tau': ch = String.fromCharCode(0x03a4); break;
						case 'Upsilon': ch = String.fromCharCode(0x03a5); break;
						case 'Phi': ch = String.fromCharCode(0x03a6); break;
						case 'Chi': ch = String.fromCharCode(0x03a7); break;
						case 'Psi': ch = String.fromCharCode(0x03a8); break;
						case 'Omega': ch = String.fromCharCode(0x03a9); break;
						case 'alpha': ch = String.fromCharCode(0x03b1); break;
						case 'beta': ch = String.fromCharCode(0x03b2); break;
						case 'gamma': ch = String.fromCharCode(0x03b3); break;
						case 'delta': ch = String.fromCharCode(0x03b4); break;
						case 'epsilon': ch = String.fromCharCode(0x03b5); break;
						case 'zeta': ch = String.fromCharCode(0x03b6); break;
						case 'eta': ch = String.fromCharCode(0x03b7); break;
						case 'theta': ch = String.fromCharCode(0x03b8); break;
						case 'iota': ch = String.fromCharCode(0x03b9); break;
						case 'kappa': ch = String.fromCharCode(0x03ba); break;
						case 'lambda': ch = String.fromCharCode(0x03bb); break;
						case 'mu': ch = String.fromCharCode(0x03bc); break;
						case 'nu': ch = String.fromCharCode(0x03bd); break;
						case 'xi': ch = String.fromCharCode(0x03be); break;
						case 'omicron': ch = String.fromCharCode(0x03bf); break;
						case 'pi': ch = String.fromCharCode(0x03c0); break;
						case 'rho': ch = String.fromCharCode(0x03c1); break;
						case 'sigmaf': ch = String.fromCharCode(0x03c2); break;
						case 'sigma': ch = String.fromCharCode(0x03c3); break;
						case 'tau': ch = String.fromCharCode(0x03c4); break;
						case 'upsilon': ch = String.fromCharCode(0x03c5); break;
						case 'phi': ch = String.fromCharCode(0x03c6); break;
						case 'chi': ch = String.fromCharCode(0x03c7); break;
						case 'psi': ch = String.fromCharCode(0x03c8); break;
						case 'omega': ch = String.fromCharCode(0x03c9); break;
						case 'thetasym': ch = String.fromCharCode(0x03d1); break;
						case 'upsih': ch = String.fromCharCode(0x03d2); break;
						case 'piv': ch = String.fromCharCode(0x03d6); break;
						case 'ensp': ch = String.fromCharCode(0x2002); break;
						case 'emsp': ch = String.fromCharCode(0x2003); break;
						case 'thinsp': ch = String.fromCharCode(0x2009); break;
						case 'zwnj': ch = String.fromCharCode(0x200c); break;
						case 'zwj': ch = String.fromCharCode(0x200d); break;
						case 'lrm': ch = String.fromCharCode(0x200e); break;
						case 'rlm': ch = String.fromCharCode(0x200f); break;
						case 'ndash': ch = String.fromCharCode(0x2013); break;
						case 'mdash': ch = String.fromCharCode(0x2014); break;
						case 'lsquo': ch = String.fromCharCode(0x2018); break;
						case 'rsquo': ch = String.fromCharCode(0x2019); break;
						case 'sbquo': ch = String.fromCharCode(0x201a); break;
						case 'ldquo': ch = String.fromCharCode(0x201c); break;
						case 'rdquo': ch = String.fromCharCode(0x201d); break;
						case 'bdquo': ch = String.fromCharCode(0x201e); break;
						case 'dagger': ch = String.fromCharCode(0x2020); break;
						case 'Dagger': ch = String.fromCharCode(0x2021); break;
						case 'bull': ch = String.fromCharCode(0x2022); break;
						case 'hellip': ch = String.fromCharCode(0x2026); break;
						case 'permil': ch = String.fromCharCode(0x2030); break;
						case 'prime': ch = String.fromCharCode(0x2032); break;
						case 'Prime': ch = String.fromCharCode(0x2033); break;
						case 'lsaquo': ch = String.fromCharCode(0x2039); break;
						case 'rsaquo': ch = String.fromCharCode(0x203a); break;
						case 'oline': ch = String.fromCharCode(0x203e); break;
						case 'frasl': ch = String.fromCharCode(0x2044); break;
						case 'euro': ch = String.fromCharCode(0x20ac); break;
						case 'image': ch = String.fromCharCode(0x2111); break;
						case 'weierp': ch = String.fromCharCode(0x2118); break;
						case 'real': ch = String.fromCharCode(0x211c); break;
						case 'trade': ch = String.fromCharCode(0x2122); break;
						case 'alefsym': ch = String.fromCharCode(0x2135); break;
						case 'larr': ch = String.fromCharCode(0x2190); break;
						case 'uarr': ch = String.fromCharCode(0x2191); break;
						case 'rarr': ch = String.fromCharCode(0x2192); break;
						case 'darr': ch = String.fromCharCode(0x2193); break;
						case 'harr': ch = String.fromCharCode(0x2194); break;
						case 'crarr': ch = String.fromCharCode(0x21b5); break;
						case 'lArr': ch = String.fromCharCode(0x21d0); break;
						case 'uArr': ch = String.fromCharCode(0x21d1); break;
						case 'rArr': ch = String.fromCharCode(0x21d2); break;
						case 'dArr': ch = String.fromCharCode(0x21d3); break;
						case 'hArr': ch = String.fromCharCode(0x21d4); break;
						case 'forall': ch = String.fromCharCode(0x2200); break;
						case 'part': ch = String.fromCharCode(0x2202); break;
						case 'exist': ch = String.fromCharCode(0x2203); break;
						case 'empty': ch = String.fromCharCode(0x2205); break;
						case 'nabla': ch = String.fromCharCode(0x2207); break;
						case 'isin': ch = String.fromCharCode(0x2208); break;
						case 'notin': ch = String.fromCharCode(0x2209); break;
						case 'ni': ch = String.fromCharCode(0x220b); break;
						case 'prod': ch = String.fromCharCode(0x220f); break;
						case 'sum': ch = String.fromCharCode(0x2211); break;
						case 'minus': ch = String.fromCharCode(0x2212); break;
						case 'lowast': ch = String.fromCharCode(0x2217); break;
						case 'radic': ch = String.fromCharCode(0x221a); break;
						case 'prop': ch = String.fromCharCode(0x221d); break;
						case 'infin': ch = String.fromCharCode(0x221e); break;
						case 'ang': ch = String.fromCharCode(0x2220); break;
						case 'and': ch = String.fromCharCode(0x2227); break;
						case 'or': ch = String.fromCharCode(0x2228); break;
						case 'cap': ch = String.fromCharCode(0x2229); break;
						case 'cup': ch = String.fromCharCode(0x222a); break;
						case 'int': ch = String.fromCharCode(0x222b); break;
						case 'there4': ch = String.fromCharCode(0x2234); break;
						case 'sim': ch = String.fromCharCode(0x223c); break;
						case 'cong': ch = String.fromCharCode(0x2245); break;
						case 'asymp': ch = String.fromCharCode(0x2248); break;
						case 'ne': ch = String.fromCharCode(0x2260); break;
						case 'equiv': ch = String.fromCharCode(0x2261); break;
						case 'le': ch = String.fromCharCode(0x2264); break;
						case 'ge': ch = String.fromCharCode(0x2265); break;
						case 'sub': ch = String.fromCharCode(0x2282); break;
						case 'sup': ch = String.fromCharCode(0x2283); break;
						case 'nsub': ch = String.fromCharCode(0x2284); break;
						case 'sube': ch = String.fromCharCode(0x2286); break;
						case 'supe': ch = String.fromCharCode(0x2287); break;
						case 'oplus': ch = String.fromCharCode(0x2295); break;
						case 'otimes': ch = String.fromCharCode(0x2297); break;
						case 'perp': ch = String.fromCharCode(0x22a5); break;
						case 'sdot': ch = String.fromCharCode(0x22c5); break;
						case 'lceil': ch = String.fromCharCode(0x2308); break;
						case 'rceil': ch = String.fromCharCode(0x2309); break;
						case 'lfloor': ch = String.fromCharCode(0x230a); break;
						case 'rfloor': ch = String.fromCharCode(0x230b); break;
						case 'lang': ch = String.fromCharCode(0x2329); break;
						case 'rang': ch = String.fromCharCode(0x232a); break;
						case 'loz': ch = String.fromCharCode(0x25ca); break;
						case 'spades': ch = String.fromCharCode(0x2660); break;
						case 'clubs': ch = String.fromCharCode(0x2663); break;
						case 'hearts': ch = String.fromCharCode(0x2665); break;
						case 'diams': ch = String.fromCharCode(0x2666); break;
						default: ch = ''; break;
					}
				}
				i = semicolonIndex;
			}
		}
		out += ch;
	}
	return out;
}

function InvertObjectVisibility(obj, strShow)
{
	if(arguments[1] != null)
	{
		obj.style.display = strShow;
		return;
	}
	
	obj.style.display = obj.style.display=='none'?'':'none';
}
//---------------------------------------------------------------------------

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function onMarkAsScanned(nPerfId, strSeatsTableName)
{	
	var jsInputSeats = $("#divSeatsIds > input");
	
	var arrSelSeatIds = jsInputSeats.val().split(";");
	
	//get seat string
	var strSeats = "";
	for(var i=0;i<arrSelSeatIds.length;i++)
	{
		if("" == arrSelSeatIds[i])
			continue;
		
		var nSeatId = parseInt(arrSelSeatIds[i]);
		if(isNaN(nSeatId))
			continue;
		
		strSeats += nSeatId + ";";
	}
	
	if("" == strSeats)
	{
		alert("No seats selected");
		return false;
	}
	
	var oParams = { strSeats: strSeats, PerformanceId : nPerfId }
	var JSONparams = JSON.encode(oParams);

	//here we make AJAX call
	//call ajax
	$.ajax({
		type: "POST",
		url: "svc/svcSales.aspx/MarkTixAsScanned",
		data: JSONparams,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data, textStatus) {
			//var oRespData = eval(data);
			
			$("#" + strSeatsTableName + " td").each(
				function(){
					
					var nId = parseInt($(this).attr("id"));
					if(isNaN(nId))
						return;
					if(nId <= 0)
						return;
					
					//check if current seat is part of our hash
					for(var i=0;i<arrSelSeatIds.length;i++)
						if(nId == arrSelSeatIds[i])
						{
							//mark seat as scanned and clear onclick
							var oColor = $("#POLHeld").css("backgroundColor");
							$(this).css("backgroundColor", oColor);
							
							$(this).attr("onclick", "");
							
							return;
						}
					
					}
				);
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
		
			var oException = null;
			eval("oException = " + XMLHttpRequest.responseText);
			if (null != oException)
				if (typeof (oException.Message) != "undefined")
					alert(oException.Message);
		}
	});
	
	return false;
} 
 /*
 * jQuery UI Draggable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._trigger("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			this._trigger('drag', event, ui);
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._trigger("stop", event);
				self._clear();
			});
		} else {
			this._trigger("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs, //deprecated
			offset: this.positionAbs
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.7.1",
	eventPrefix: "drag",
	defaults: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		cancel: ":input,option",
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = o.stack.min + i;
		});

		this[0].style.zIndex = o.stack.min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);
 
 /*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox()
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    jQuery.facebox('some html')
 *    jQuery.facebox('some html', 'my-groovy-style')
 *
 *  The above will open a facebox with "some html" as the content.
 *
 *    jQuery.facebox(function($) {
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page, an image, or the contents of a div:
 *
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
 *    jQuery.facebox({ image: 'stairs.jpg' })
 *    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
 *    jQuery.facebox({ div: '#box' })
 *    jQuery.facebox({ div: '#box' }, 'my-groovy-style')
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *    afterClose.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage: 'js/jqueryplugins/facebox/loading.gif',
      closeImage: 'js/jqueryplugins/facebox/closelabel.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <div class="content"> \
        </div> \
        <a href="#" class="close"><img src="js/jqueryplugins/facebox/closelabel.png" title="close" class="close_image" /></a> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	$(window).width() / 2 - 205
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return

    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.bind('click.facebox', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }

  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#facebox_overlay').length == 0)
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide")
      $("#facebox_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      $('#facebox .loading').remove()
      $(document).trigger('afterClose.facebox')
    })
    hideOverlay()
  })

})(jQuery);
 
 var MessAdmin=new Array();MessAdmin["capl_viewid"]="View ID";
MessAdmin["Select_a_Section"]="Select a Section";
MessAdmin["Cash_Tendered"]="Cash Tendered";
MessAdmin["capl_showmap"]="Show Map";
MessAdmin["capl_transactions"]="Transactions";
MessAdmin["Travellers_Check_Transaction"]="Travellers Check Transaction";
MessAdmin["American_Express"]="American Express";
MessAdmin["subtotal"]="Subtotal";
MessAdmin["Monday_full"]="Monday";
MessAdmin["capl_edit"]="Edit";
MessAdmin["capl_copy"]="Copy";
MessAdmin["Coupons_Redeemer"]="Coupons Redeemer";
MessAdmin["Avgust"]="A";
MessAdmin["August"]="August";
MessAdmin["Friday"]="F";
MessAdmin["Tuesday"]="T";
MessAdmin["Would_you_like_to_print"]="Would you like to print the tickets for this order now?";
MessAdmin["PaymentTypes_kdtickets"]="Kingdom Tickets";
MessAdmin["Monday"]="M";
MessAdmin["Thursday"]="T";
MessAdmin["Cash_Transaction"]="Cash Transaction";
MessAdmin["allcaps_zip"]="ZIP";
MessAdmin["Bankcard"]="Bankcard";
MessAdmin["Insert"]="Insert";
MessAdmin["PaymentTypes_srecovery"]="Service Recovery";
MessAdmin["Transaction"]="Transaction";
MessAdmin["EnabledIn"]="EnabledIn";
MessAdmin["PaymentTypes_ct2"]="CustomTest2";
MessAdmin["PaymentTypes_TBM"]="TBM";
MessAdmin["Update"]="Update";
MessAdmin["PaymentTypes_voucher"]="VoucherCoupon";
MessAdmin["Tickets1"]="Tickets";
MessAdmin["Noiabri"]="N";
MessAdmin["Card_Number"]="Card Number";
MessAdmin["forward_one_month"]="Go forward one month";
MessAdmin["December"]="December";
MessAdmin["Ticket"]="Ticket";
MessAdmin["exchange_ticket"]="Exchange ticket";
MessAdmin["Region"]="Region";
MessAdmin["Sunday"]="S";
MessAdmin["capl_please_confirm"]="Please Confirm";
MessAdmin["Street"]="Street";
MessAdmin["Thursday_full"]="Thursday";
MessAdmin["Mastercard"]="Mastercard";
MessAdmin["November"]="November";
MessAdmin["ShoppingCart"]="Shopping Cart";
MessAdmin["capl_pricesheet_item_info"]="Pricesheet Item Info";
MessAdmin["loading_section"]="Loading Section";
MessAdmin["PaymentTypes_svnimportpayment"]="svnImportPayment";
MessAdmin["capl_tickets"]="Tickets";
MessAdmin["PaymentTypes_Account"]="Account";
MessAdmin["back_one_month"]="Go back one month";
MessAdmin["Company"]="Company";
MessAdmin["seat_is_held_shopping_cart"]="Seat is held in shopping cart";
MessAdmin["Country"]="Country";
MessAdmin["September"]="September";
MessAdmin["Wednesday_full"]="Wednesday";
MessAdmin["Select_date"]="Select a date";
MessAdmin["PaymentTypes_ct"]="CustomTest1";
MessAdmin["Patron_Coupons"]="Patron\'s Coupons";
MessAdmin["RequiredIn"]="RequiredIn";
MessAdmin["cannot_be_empty"]="cannot be empty";
MessAdmin["update_all_orders_for_this_patron"]="update all orders for this patron";
MessAdmin["Wednesday"]="W";
MessAdmin["Partner"]="Partner";
MessAdmin["PaymentTypes_check"]="Check";
MessAdmin["Cardholder_s_Name"]="Cardholders Name";
MessAdmin["Card_Type"]="Card Type";
MessAdmin["January"]="January";
MessAdmin["Payment_transactions_are_not_order_total"]="Payment transactions are not sufficient for order total";
MessAdmin["ticket_history"]="ticket history";
MessAdmin["allcaps_ok"]="OK";
MessAdmin["select_performances"]="Select performances";
MessAdmin["Friday_full"]="Friday";
MessAdmin["PaymentTypes_credit"]="CreditCard";
MessAdmin["capl_all"]="All";
MessAdmin["capl_new"]="New";
MessAdmin["capl_map"]="Map";
MessAdmin["PaymentTypes_Room_sp_Charge"]="Room Charge";
MessAdmin["D"]="D";
MessAdmin["F"]="F";
MessAdmin["A"]="A";
MessAdmin["M"]="M";
MessAdmin["O"]="O";
MessAdmin["J"]="J";
MessAdmin["S"]="S";
MessAdmin["no"]="no";
MessAdmin["on"]="on";
MessAdmin["ID"]="ID";
MessAdmin["October"]="October";
MessAdmin["Comp_Transaction"]="Comp Transaction";
MessAdmin["close"]="close";
MessAdmin["today"]="today";
MessAdmin["all"]="all";
MessAdmin["yes"]="yes";
MessAdmin["Aug"]="Aug";
MessAdmin["Apr"]="Apr";
MessAdmin["Fee"]="Fee";
MessAdmin["Feb"]="Feb";
MessAdmin["Fri"]="Fri";
MessAdmin["Dec"]="Dec";
MessAdmin["Mon"]="Mon";
MessAdmin["Mai"]="M";
MessAdmin["May"]="May";
MessAdmin["Mar"]="Mar";
MessAdmin["Nov"]="Nov";
MessAdmin["Oct"]="Oct";
MessAdmin["Jan"]="Jan";
MessAdmin["Jun"]="Jun";
MessAdmin["Jul"]="Jul";
MessAdmin["Wed"]="Wed";
MessAdmin["Tue"]="Tue";
MessAdmin["Thu"]="Thu";
MessAdmin["Sun"]="Sun";
MessAdmin["Sep"]="Sep";
MessAdmin["Sat"]="Sat";
MessAdmin["Event"]="Event";
MessAdmin["April"]="April";
MessAdmin["March"]="March";
MessAdmin["Items"]="Items";
MessAdmin["forward_one_year"]="Go forward one year";
MessAdmin["Total"]="Total";
MessAdmin["State"]="State";
MessAdmin["Price"]="Extended";
MessAdmin["PaymentTypes_Channel"]="Channel";
MessAdmin["Discount"]="Discount";
MessAdmin["Discover"]="Discover";
MessAdmin["show_all"]="show all";
MessAdmin["February"]="February";
MessAdmin["PaymentTypes_Mashr_789_76"]="Mashreq";
MessAdmin["Voucher_Coupon_Transaction"]="Voucher/Coupon Transaction";
MessAdmin["Check_Number"]="Check Number";
MessAdmin["Exchange"]="Exchange";
MessAdmin["PaymentTypes_prepaid"]="Prepaid";
MessAdmin["Expiration_Date"]="Expiration Date";
MessAdmin["DeliveryMethods_taketicketsnow"]="Take Tickets Now";
MessAdmin["Sunday_full"]="Sunday";
MessAdmin["Credit_Card_Transaction"]="Credit Card Transaction";
MessAdmin["Mon_abr"]="Mon";
MessAdmin["All_Selected"]="All Selected";
MessAdmin["back_one_year"]="Go back one year";
MessAdmin["Saturday"]="S";
MessAdmin["Tuesday_full"]="Tuesday";
MessAdmin["set_date"]="Set date to";
MessAdmin["capl_delete"]="Delete";
MessAdmin["enter_code_here"]="Enter Code Here";
MessAdmin["PaymentTypes_clicknbuy"]="ClickandBuy";
MessAdmin["edit_sql"]="Edit SQL";
MessAdmin["PaymentTypes_Credit_sp_Card"]="Credit Card";
MessAdmin["Check_Transaction"]="Check Transaction";
MessAdmin["Saturday_full"]="Saturday";
MessAdmin["PaymentTypes_travellers"]="TravellersCheck";
MessAdmin["capl_showperffgl"]="Show Performance FGL";
MessAdmin["new_address"]="new address";
MessAdmin["swipe_credit_card"]="swipe credit card";
MessAdmin["cancel"]="cancel";
MessAdmin["Additional_Fees_sl_Discounts"]="Disc./Fees";
MessAdmin["Reg_dot__Price"]="Price";
MessAdmin["No_records_found"]="No records found";
MessAdmin["capl_apply"]="Apply";
MessAdmin["capl_performance_limit"]="Performance Limit";
MessAdmin["SeasonTickets"]="Season Tickets";
MessAdmin["CVV_Number"]="CVV Number";
MessAdmin["PaymentTypes_cash"]="Cash";
MessAdmin["PaymentTypes_comp"]="Comp";
MessAdmin["PaymentTypes_ceca"]="CECA";
MessAdmin["PaymentTypes_wire"]="Bank Transfer";
MessAdmin["PaymentTypes_test"]="Test";
MessAdmin["capl_venueeditor"]="Venue Editor";
MessAdmin["Select_Coupon"]="Select Coupon";
MessAdmin["wire"]="wire";
MessAdmin["EDIT"]="EDIT";
MessAdmin["Date"]="Date";
MessAdmin["Code"]="Code";
MessAdmin["City"]="City";
MessAdmin["COPY"]="COPY";
MessAdmin["Iuli"]="J";
MessAdmin["Iuni"]="J";
MessAdmin["Note"]="Note";
MessAdmin["Name"]="Name";
MessAdmin["July"]="July";
MessAdmin["June"]="June";
MessAdmin["VISA"]="VISA";
MessAdmin["Type"]="Type";
MessAdmin["Show"]="Show";
MessAdmin["Year"]="Year";
MessAdmin["Please_wait"]="Please wait...";
MessAdmin["PaymentTypes_accountsreceivable"]="AccountsReceivable";
MessAdmin["remove"]="remove";

