
/********************************
/cms/resources/javascript/soapclient.js
********************************/
/*****************************************************************************\

 Javascript "SOAP Client" library
 
 @version: 2.4 - 2007.12.21
 @author: Matteo Casati - http://www.guru4.net/
 
\*****************************************************************************/

function SOAPClientParameters()
{
	var _pl = new Array();
	this.add = function(name, value) 
	{
		_pl[name] = value; 
		return this; 
	}
	this.toXml = function()
	{
		var xml = "";
		for(var p in _pl)
		{
			switch(typeof(_pl[p])) 
			{
                case "string":
                case "number":
                case "boolean":
                case "object":
                    xml += "<" + p + ">" + SOAPClientParameters._serialize(_pl[p]) + "</" + p + ">";
                    break;
                default:
                    break;
            }
		}
		return xml;	
	}
}
SOAPClientParameters._serialize = function(o)
{
    var s = "";
    switch(typeof(o))
    {
        case "string":
            s += o.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); break;
        case "number":
        case "boolean":
            s += o.toString(); break;
        case "object":
            // Date
            if(o.constructor.toString().indexOf("function Date()") > -1)
            {
        
                var year = o.getFullYear().toString();
                var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
                var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
                var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
                var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
                var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
                var milliseconds = o.getMilliseconds().toString();
                var tzminutes = Math.abs(o.getTimezoneOffset());
                var tzhours = 0;
                while(tzminutes >= 60)
                {
                    tzhours++;
                    tzminutes -= 60;
                }
                tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
                tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
                var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
                s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
            }
            // Array
            else if(o.constructor.toString().indexOf("function Array()") > -1)
            {
                for(var p in o)
                {
                    if(!isNaN(p))   // linear array
                    {
                        (/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
                        var type = RegExp.$1;
                        switch(type)
                        {
                            case "":
                                type = typeof(o[p]);
                            case "String":
                                type = "string"; break;
                            case "Number":
                                type = "int"; break;
                            case "Boolean":
                                type = "bool"; break;
                            case "Date":
                                type = "DateTime"; break;
                        }
                        s += "<" + type + ">" + SOAPClientParameters._serialize(o[p]) + "</" + type + ">"
                    }
                    else    // associative array
                        s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">"
                }
            }
            // Object or custom function
            else
                for(var p in o)
                    s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">";
            break;
        default:
            break; // throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
    }
    return s;
}

function SOAPClient() {}

SOAPClient.username = null;
SOAPClient.password = null;

SOAPClient.invoke = function(url, method, parameters, async, callback)
{
	//alert("ViewStateUserKey: " + document.getElementById("ViewStateUserKey").value);
	var ViewStateUserKey = document.getElementById("ViewStateUserKey");
	if (ViewStateUserKey)
		parameters.add("ViewStateUserKey", ViewStateUserKey.value);
	
	if(async)
		SOAPClient._loadWsdl(url, method, parameters, async, callback);
	else
		return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}

// private: wsdl cache
SOAPClient_cacheWsdl = new Array();

// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
	// load from cache?
	var wsdl = SOAPClient_cacheWsdl[url];
	if (wsdl) //if (wsdl + "" != "" && wsdl + "" != "undefined")   <---- That doesn't work on MSIE 9
		return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
	// get wsdl
	var xmlHttp = SOAPClient._getXmlHttp(url);
	xmlHttp.open("GET", url + "?wsdl", async);
	if(async) 
	{
		xmlHttp.onreadystatechange = function() 
		{
		    if (xmlHttp.readyState == 4)
				SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
		}
	}
	xmlHttp.send(null);
	if (!async)
		return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
	var wsdl = req.responseXML;
	SOAPClient_cacheWsdl[url] = wsdl;	// save a copy in cache
	return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
	// get namespace
	var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
	// build SOAP request
	var sr = 
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
				"<soap:Envelope " +
				"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
				"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
				"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
				"<soap:Body>" +
				"<" + method + " xmlns=\"" + ns + "\">" +
				parameters.toXml() +
				"</" + method + "></soap:Body></soap:Envelope>";
	// send request
	var xmlHttp = SOAPClient._getXmlHttp(url);
	var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;

	if (async) {
	    xmlHttp.onreadystatechange = function () {
	        if (xmlHttp.readyState == 4)
	            SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
	    }
	}

	if (SOAPClient.userName && SOAPClient.password) {
	    xmlHttp.open("POST", url, async, SOAPClient.userName, SOAPClient.password);
	    // Some WS implementations (i.e. BEA WebLogic Server 10.0 JAX-WS) don't support Challenge/Response HTTP BASIC, so we send authorization headers in the first request
	    xmlHttp.setRequestHeader("Authorization", "Basic " + SOAPClient._toBase64(SOAPClient.userName + ":" + SOAPClient.password));
	}
	else {
	    if (!xmlHttp.setRequestHeader)
	    {
	        var action = soapaction.split("/");
	        url += "/" + action[action.length - 1];
	    }
	    xmlHttp.open("POST", url, async);
	}
	if (xmlHttp.setRequestHeader) {
	    xmlHttp.setRequestHeader("SOAPAction", soapaction);
	    xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	}
	xmlHttp.send(sr);
	if (!async)
		return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}

SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req) 
{
	var o = null;
	var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
	if(nd.length == 0)
		nd = SOAPClient._getElementsByTagName(req.responseXML, "return");	// PHP web Service?
	if(nd.length == 0)
	{
		if(req.responseXML.getElementsByTagName("faultcode").length > 0)
		{
		    if(async || callback)
		        o = new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
			else
			    throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);			
		}
	}
	else
		o = SOAPClient._soapresult2object(nd[0], wsdl);
	if(callback)
		callback(o, req.responseXML);
	if(!async)
		return o;
}
SOAPClient._soapresult2object = function(node, wsdl)
{
    var wsdlTypes = SOAPClient._getTypesFromWsdl(wsdl);
    return SOAPClient._node2object(node, wsdlTypes);
}
SOAPClient._node2object = function(node, wsdlTypes)
{
	// null node
	if(node == null)
		return null;
	// text node
	if(node.nodeType == 3 || node.nodeType == 4)
		return SOAPClient._extractValue(node, wsdlTypes);
	// leaf node
	if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
		return SOAPClient._node2object(node.childNodes[0], wsdlTypes);
	var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdlTypes).toLowerCase().indexOf("arrayof") != -1;
	// object node
	if(!isarray)
	{
		var obj = null;
		if(node.hasChildNodes())
			obj = new Object();
		var anonymousChunks = (node.childNodes.length > 1 && (node.childNodes[0].nodeName == node.childNodes[1].nodeName));
		if (anonymousChunks)
			obj = "";
		for(var i = 0; i < node.childNodes.length; i++)
		{
			var p = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
			if (anonymousChunks)
				obj += p
			else
				obj[node.childNodes[i].nodeName] = p;
		}
		return obj;
	}
	// list node
	else
	{
		// create node ref
		var l = new Array();
		for(var i = 0; i < node.childNodes.length; i++)
			l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
		return l;
	}
	return null;
}
SOAPClient._extractValue = function(node, wsdlTypes)
{
	var value = node.nodeValue;
	switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdlTypes).toLowerCase())
	{
		default:
		case "s:string":			
			return (value != null) ? value + "" : "";
		case "s:boolean":
			return value + "" == "true";
		case "s:int":
		case "s:long":
			return (value != null) ? parseInt(value + "", 10) : 0;
		case "s:double":
			return (value != null) ? parseFloat(value + "") : 0;
		case "s:datetime":
			if(value == null)
				return null;
			else
			{
				value = value + "";
				value = value.substring(0, (value.lastIndexOf(".") == -1 ? value.length : value.lastIndexOf(".")));
				value = value.replace(/T/gi," ");
				value = value.replace(/-/gi,"/");
				var d = new Date();
				d.setTime(Date.parse(value));										
				return d;				
			}
	}
}
SOAPClient._getTypesFromWsdl = function(wsdl)
{
	var wsdlTypes = new Array();
	// IE
	var ell = wsdl.getElementsByTagName("s:element");	
	var useNamedItem = true;
	// MOZ
	if(ell.length == 0)
	{
		ell = wsdl.getElementsByTagName("element");	     
		useNamedItem = false;
	}
	for(var i = 0; i < ell.length; i++)
	{
		if(useNamedItem)
		{
			if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("type") != null) 
				wsdlTypes[ell[i].attributes.getNamedItem("name").nodeValue] = ell[i].attributes.getNamedItem("type").nodeValue;
		}	
		else
		{
			if(ell[i].attributes["name"] != null && ell[i].attributes["type"] != null)
				wsdlTypes[ell[i].attributes["name"].value] = ell[i].attributes["type"].value;
		}
	}
	return wsdlTypes;
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdlTypes)
{
    var type = wsdlTypes[elementname] + "";
    return (type == "undefined") ? "" : type;
}
// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
	try
	{
		// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
		return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
	}
	catch (ex) {}
	// old XML parser support
	return document.getElementsByTagName(tagName);
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function(url) 
{
	try
	{
        /*
	    if (window.XDomainRequest) {
	        var req = new XDomainRequest();
	        req.readyState = 4;
	        req.onload = function () {
	            var dom = new ActiveXObject("Microsoft.XMLDOM");
	            dom.async = false;
	            dom.loadXML(req.responseText);
	            req.responseXML = dom;
                req.onreadystatechange();
	        }
	        req.onerror = function (ex) {
	            alert("error calling: " + url);
	        };
	        return req;
	    }
	    else */ if (window.XMLHttpRequest) {
	        var req = new XMLHttpRequest();
	        // some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
	        if (req.readyState == null) {
	            req.readyState = 1;
	            req.addEventListener("load",
									function () {
									    req.readyState = 4;
									    if (typeof req.onreadystatechange == "function")
									        req.onreadystatechange();
									},
									false);
	        }
	        return req;
	    }
		if(window.ActiveXObject) 
			return new ActiveXObject(SOAPClient._getXmlHttpProgID());
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
	if(SOAPClient._getXmlHttpProgID.progid)
		return SOAPClient._getXmlHttpProgID.progid;
	var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	var o;
	for(var i = 0; i < progids.length; i++)
	{
		try
		{
			o = new ActiveXObject(progids[i]);
			return SOAPClient._getXmlHttpProgID.progid = progids[i];
		}
		catch (ex) {};
	}
	throw new Error("Could not find an installed XML parser");
}

SOAPClient._toBase64 = function(input)
{
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
		keyStr.charAt(enc3) + keyStr.charAt(enc4);
	} while (i < input.length);

	return output;
}

String.format = function()
{
    if( arguments.length == 0 )
        return null;

    var str = arguments[0];
    for(var i=1;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }

    return str;
}
;

/********************************
/cms/resources/accountingJS/accounting.min.js
********************************/
/*!
 * accounting.js v0.3.2, copyright 2011 Joss Crowcroft, MIT license, http://josscrowcroft.github.com/accounting.js
 */
(function(p,z){function q(a){return!!(""===a||a&&a.charCodeAt&&a.substr)}function m(a){return u?u(a):"[object Array]"===v.call(a)}function r(a){return"[object Object]"===v.call(a)}function s(a,b){var d,a=a||{},b=b||{};for(d in b)b.hasOwnProperty(d)&&null==a[d]&&(a[d]=b[d]);return a}function j(a,b,d){var c=[],e,h;if(!a)return c;if(w&&a.map===w)return a.map(b,d);for(e=0,h=a.length;e<h;e++)c[e]=b.call(d,a[e],e,a);return c}function n(a,b){a=Math.round(Math.abs(a));return isNaN(a)?b:a}function x(a){var b=c.settings.currency.format;"function"===typeof a&&(a=a());return q(a)&&a.match("%v")?{pos:a,neg:a.replace("-","").replace("%v","-%v"),zero:a}:!a||!a.pos||!a.pos.match("%v")?!q(b)?b:c.settings.currency.format={pos:b,neg:b.replace("%v","-%v"),zero:b}:a}var c={version:"0.3.2",settings:{currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}}},w=Array.prototype.map,u=Array.isArray,v=Object.prototype.toString,o=c.unformat=c.parse=function(a,b){if(m(a))return j(a,function(a){return o(a,b)});a=a||0;if("number"===typeof a)return a;var b=b||".",c=RegExp("[^0-9-"+b+"]",["g"]),c=parseFloat((""+a).replace(/\((.*)\)/,"-$1").replace(c,"").replace(b,"."));return!isNaN(c)?c:0},y=c.toFixed=function(a,b){var b=n(b,c.settings.number.precision),d=Math.pow(10,b);return(Math.round(c.unformat(a)*d)/d).toFixed(b)},t=c.formatNumber=function(a,b,d,i){if(m(a))return j(a,function(a){return t(a,b,d,i)});var a=o(a),e=s(r(b)?b:{precision:b,thousand:d,decimal:i},c.settings.number),h=n(e.precision),f=0>a?"-":"",g=parseInt(y(Math.abs(a||0),h),10)+"",l=3<g.length?g.length%3:0;return f+(l?g.substr(0,l)+e.thousand:"")+g.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+e.thousand)+(h?e.decimal+y(Math.abs(a),h).split(".")[1]:"")},A=c.formatMoney=function(a,b,d,i,e,h){if(m(a))return j(a,function(a){return A(a,b,d,i,e,h)});var a=o(a),f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format);return(0<a?g.pos:0>a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal))};c.formatColumn=function(a,b,d,i,e,h){if(!a)return[];var f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format),l=g.pos.indexOf("%s")<g.pos.indexOf("%v")?!0:!1,k=0,a=j(a,function(a){if(m(a))return c.formatColumn(a,f);a=o(a);a=(0<a?g.pos:0>a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal));if(a.length>k)k=a.length;return a});return j(a,function(a){return q(a)&&a.length<k?l?a.replace(f.symbol,f.symbol+Array(k-a.length+1).join(" ")):Array(k-a.length+1).join(" ")+a:a})};if("undefined"!==typeof exports){if("undefined"!==typeof module&&module.exports)exports=module.exports=c;exports.accounting=c}else"function"===typeof define&&define.amd?define([],function(){return c}):(c.noConflict=function(a){return function(){p.accounting=a;c.noConflict=z;return c}}(p.accounting),p.accounting=c)})(this);;

/********************************
/cms/js/lib/crockford/json2.js
********************************/
/*
    json2.js
    2012-10-08

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, regexp: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf())
                ? this.getUTCFullYear()     + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate())      + 'T' +
                    f(this.getUTCHours())     + ':' +
                    f(this.getUTCMinutes())   + ':' +
                    f(this.getUTCSeconds())   + 'Z'
                : null;
        };

        String.prototype.toJSON      =
            Number.prototype.toJSON  =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string'
                ? c
                : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? '[]'
                    : gap
                    ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                    : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? '{}'
                : gap
                ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
;

/********************************
/cms/js/lib/masonry-site/jquery.masonry.min.js
********************************/
/**
 * jQuery Masonry v2.1.0
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2011 David DeSandro
 */
(function(a,b,c){var d=b.event,e;d.special.smartresize={setup:function(){b(this).bind("resize",d.special.smartresize.handler)},teardown:function(){b(this).unbind("resize",d.special.smartresize.handler)},handler:function(a,b){var c=this,d=arguments;a.type="smartresize",e&&clearTimeout(e),e=setTimeout(function(){jQuery.event.handle.apply(c,d)},b==="execAsap"?0:100)}},b.fn.smartresize=function(a){return a?this.bind("smartresize",a):this.trigger("smartresize",["execAsap"])},b.Mason=function(a,c){this.element=b(c),this._create(a),this._init()};var f=["position","height"];b.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1},b.Mason.prototype={_filterFindBricks:function(a){var b=this.options.itemSelector;return b?a.filter(b).add(a.find(b)):a},_getBricks:function(a){var b=this._filterFindBricks(a).css({position:"absolute"}).addClass("masonry-brick");return b},_create:function(c){this.options=b.extend(!0,{},b.Mason.settings,c),this.styleQueue=[],this.reloadItems();var d=this.element[0].style;this.originalStyle={};for(var e=0,g=f.length;e<g;e++){var h=f[e];this.originalStyle[h]=d[h]||""}this.element.css({position:"relative"}),this.horizontalDirection=this.options.isRTL?"right":"left",this.offset={x:parseInt(this.element.css("padding-"+this.horizontalDirection),10),y:parseInt(this.element.css("padding-top"),10)},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var i=this;setTimeout(function(){i.element.addClass("masonry")},0),this.options.isResizable&&b(a).bind("smartresize.masonry",function(){i.resize()})},_init:function(a){this._getColumns(),this._reLayout(a)},option:function(a,c){b.isPlainObject(a)&&(this.options=b.extend(!0,this.options,a))},layout:function(a,b){for(var c=0,d=a.length;c<d;c++)this._placeBrick(a[c]);var e={};e.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var f=0,c=this.cols;while(--c){if(this.colYs[c]!==0)break;f++}e.width=(this.cols-f)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:e});var g=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",h=this.options.animationOptions,i;for(c=0,d=this.styleQueue.length;c<d;c++)i=this.styleQueue[c],i.$el[g](i.style,h);this.styleQueue=[],b&&b.call(a),this.isLaidOut=!0},_getColumns:function(){var a=this.options.isFitWidth?this.element.parent():this.element,b=a.width();this.columnWidth=this.isFluid?this.options.columnWidth(b):this.options.columnWidth||this.$bricks.outerWidth(!0)||b,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((b+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(a){var c=b(a),d,e,f,g,h;d=Math.ceil(c.outerWidth(!0)/(this.columnWidth+this.options.gutterWidth)),d=Math.min(d,this.cols);if(d===1)f=this.colYs;else{e=this.cols+1-d,f=[];for(h=0;h<e;h++)g=this.colYs.slice(h,h+d),f[h]=Math.max.apply(Math,g)}var i=Math.min.apply(Math,f),j=0;for(var k=0,l=f.length;k<l;k++)if(f[k]===i){j=k;break}var m={top:i+this.offset.y};m[this.horizontalDirection]=this.columnWidth*j+this.offset.x,this.styleQueue.push({$el:c,style:m});var n=i+c.outerHeight(!0),o=this.cols+1-l;for(k=0;k<o;k++)this.colYs[j+k]=n},resize:function(){var a=this.cols;this._getColumns(),(this.isFluid||this.cols!==a)&&this._reLayout()},_reLayout:function(a){var b=this.cols;this.colYs=[];while(b--)this.colYs.push(0);this.layout(this.$bricks,a)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(a){this.reloadItems(),this._init(a)},appended:function(a,b,c){if(b){this._filterFindBricks(a).css({top:this.element.height()});var d=this;setTimeout(function(){d._appended(a,c)},1)}else this._appended(a,c)},_appended:function(a,b){var c=this._getBricks(a);this.$bricks=this.$bricks.add(c),this.layout(c,b)},remove:function(a){this.$bricks=this.$bricks.not(a),a.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var c=this.element[0].style;for(var d=0,e=f.length;d<e;d++){var g=f[d];c[g]=this.originalStyle[g]}this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),b(a).unbind(".masonry")}},b.fn.imagesLoaded=function(a){function h(){--e<=0&&this.src!==f&&(setTimeout(g),d.unbind("load error",h))}function g(){a.call(b,d)}var b=this,d=b.find("img").add(b.filter("img")),e=d.length,f="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";e||g(),d.bind("load error",h).each(function(){if(this.complete||this.complete===c){var a=this.src;this.src=f,this.src=a}});return b};var g=function(a){this.console&&console.error(a)};b.fn.masonry=function(a){if(typeof a=="string"){var c=Array.prototype.slice.call(arguments,1);this.each(function(){var d=b.data(this,"masonry");if(!d)g("cannot call methods on masonry prior to initialization; attempted to call method '"+a+"'");else{if(!b.isFunction(d[a])||a.charAt(0)==="_"){g("no such method '"+a+"' for masonry instance");return}d[a].apply(d,c)}})}else this.each(function(){var c=b.data(this,"masonry");c?(c.option(a||{}),c._init()):b.data(this,"masonry",new b.Mason(a,this))});return this}})(window,jQuery);
;

/********************************
/cms/js/mosaic/platform.js
********************************/
/** @namespace */
var AdeoApp = function() {};


/** 
	@class Contains all the App workers  
*/
AdeoApp.AppFactory = function() {
	this.AppList = {};
	this.ConstructorList = {};
};

/*
	@description A facility for apps to call in order to self-register
	@param {String} AppGuid The Guid for the application
	@param {function} Constructor An inline-function that will create the app
*/
AdeoApp.AppFactory.prototype.Register = function(AppGuid, Constructor) {
	this.ConstructorList[AppGuid.toLowerCase()] = Constructor;
	this.GetApp(AppGuid);
}

/*
	@description Gets an instance of the app.
	@param {String} AppGuid The Guid for the application
	@returns {AdeoApp.App}
*/
AdeoApp.AppFactory.prototype.GetApp = function(AppGuid)
{
	AppGuid = AppGuid.toLowerCase();
	var constructor = this.ConstructorList[AppGuid];
	var app = this.AppList[AppGuid];
	if (!app)
	{
		if (constructor)
		{
			app = constructor();
		}
		else
		{
			//alert("Unable to get app by id: " + AppGuid);
			app = new AdeoApp.AjaxApp();
		}
		this.AppList[AppGuid] = app;
	}
	return app;
}

/*
	@description Some applications might want to lazy-load. This checks if the constructor is ready.
	@param {String} AppGuid The Guid for the application
	@returns {Bool}
*/
AdeoApp.AppFactory.prototype.Ready = function(Guid) {
	if (this.ConstructorList[Guid.toLowerCase()])
		return true;
	else
		return false;
};

/**
	@class The main platform class. Contains an instance of Factory
	@augments AdeoApp.AppFactory
*/
AdeoApp.Platform = function() { 
	this.Factory = new AdeoApp.AppFactory();
};

AdeoApp.Platform.prototype.SOAP_URL = "/cms/lib/soap/ApplicationData.asmx";
//AdeoApp.Platform.prototype.SOAP_URL = [SEE MINIFIED];
AdeoApp.Platform.prototype.DefaultsContentGuid = "33617462-a38d-4354-a6a4-3a8a347e93ab";

/*
	@description Calls the GetData Service
*/
AdeoApp.Platform.prototype.GetData = function(ModuleName, ContentGuid, LayoutGuid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("ContentGuid", ContentGuid);
	parameters.add("LayoutGuid", LayoutGuid);
	SOAPClient.invoke(this.SOAP_URL, "GetData", parameters, true, Callback);
}

/*
	@description Calls the GetData Service
*/
AdeoApp.Platform.prototype.GetDataPreview = function(ModuleName, ContentGuid, LayoutGuid, ClonedLayoutGuid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("ContentGuid", ContentGuid);
	parameters.add("LayoutGuid", LayoutGuid);
	parameters.add("ClonedLayoutGuid", ClonedLayoutGuid);
	SOAPClient.invoke(this.SOAP_URL, "GetDataPreview", parameters, true, Callback);
}

/*
	@description Calls the SaveData Service
*/
AdeoApp.Platform.prototype.SaveData = function(ModuleName, ContentGuid, LayoutGuid, Data, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("ContentGuid", ContentGuid);
	parameters.add("LayoutGuid", LayoutGuid);
	//alert(JSON.stringify(Data)); //Debug!
	parameters.add("Data", JSON.stringify(Data));
	SOAPClient.invoke(this.SOAP_URL, "SaveData", parameters, true, Callback);
}

/*
	@description Calls the DeleteData Service
*/
AdeoApp.Platform.prototype.DeleteData = function(ModuleName, ContentGuid, LayoutGuid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("ContentGuid", ContentGuid);
	parameters.add("LayoutGuid", LayoutGuid);
	SOAPClient.invoke(this.SOAP_URL, "DeleteData", parameters, true, Callback);
}

/*
	@description Creates a dialog box
	@param {String} DialogID Unique identifier for the dialog (allows it to be re-used without recreating)
*/
AdeoApp.Platform.prototype.CreateDialog = function(DialogID)
{
	if (!DialogID)
		DialogID = "divDialog";
	var dialog = document.getElementById(DialogID);
	if (!dialog)
	{
		dialog = document.createElement("div");
		dialog.id = DialogID;
		dialog.innerHTML = "<span></span>";
	}
	return dialog;
}

/*
	@description Opens a confirmation dialog
	@param {String} Title
	@param {String} Message
	@param {Function} Callback
*/
AdeoApp.Platform.prototype.ShowConfirm = function(Title, Message, Callback)
{
	this.ShowDialog(Title, Message, true, Callback);
}

/*
	@description Opens an alert dialog
	@param {String} Title
	@param {String} Message
	@param {Function} Callback
*/
AdeoApp.Platform.prototype.ShowAlert = function(Title, Message, Callback)
{
	this.ShowDialog(Title, Message, false, Callback);
}

/*
	@description Opens a dialog with all the options
	@param {String} Title
	@param {String} Message
	@param {Bool} CanCancel
	@param {Function} CallbackCancel
	@param {Bool} NoOkClose
	@param {String} DialogID Unique identifier for the dialog (allows it to be re-used without recreating)
*/
AdeoApp.Platform.prototype.ShowDialog = function(Title, Message, CanCancel, CallbackOk, CallbackCancel, NoOkClose, DialogID)
{
	var dialog = this.CreateDialog(DialogID);
	$(dialog).html(Message);

	var buttons = {};
	buttons[AdeoPlatform.Resource("OK")] = function() {
		if (!NoOkClose)
			$( this ).dialog( "close" );
		if (CallbackOk)
			CallbackOk(dialog);
	}
	if (CanCancel)
	{
		buttons[AdeoPlatform.Resource("Cancel")] = function() {
			$( this ).dialog( "close" );
			if (CallbackCancel)
				CallbackCancel();
		}
	}

	var selector = ".ui-button:contains('" + AdeoPlatform.Resource("OK") + "')";
	var options = {
		"modal": true,
		"title": Title,
		"buttons": buttons,
		 position: "top"
	}
	var minWidth = 520;
	var documentWidth = $(document).width();
	if (minWidth < documentWidth)
		options["minWidth"] = minWidth;
	else
		options["maxWidth"] = documentWidth;
	$(dialog).dialog(options);
		
	$(dialog).parents(".ui-dialog").find(selector).addClass("btnOk");
	
	return dialog;
}

AdeoApp.Platform.prototype.ResourceTypes = {
	"JavaScript": "js",
	"CascadingStyleSheet": "css"
};

AdeoApp.Platform.prototype.Properties = {
	"IconWidth": 36,
	"TabHeight": 36
}

/*
	@description Lazy-load a resource file
	@param {String} FileName
	@param {String} FileType ResourceTypes.JavaScript | ResourceTypes.CascadingStyleSheet
	@param {Bool} CanCancel
	@param {Object} Windo	document.window (optional)
*/
AdeoApp.Platform.prototype.LoadResource = function(FileName, FileType, Windo)
{
	if (!Windo)
		Windo = window;
	var isJavascript = (FileType == this.ResourceTypes.JavaScript);
	var isCss = (FileType == this.ResourceTypes.CascadingStyleSheet);
	var fileref = null;
	if (isJavascript) //if FileName is a external JavaScript file
	{
		fileref = Windo.document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", FileName);
	}
	else if (isCss) //if FileName is an external CSS file
	{ 
		fileref = Windo.document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", FileName);
	}
	if (fileref)
	{
		var head = Windo.document.getElementsByTagName("head")[0];
		var duplicate = false;
		for (var i = 0; i < head.childNodes.length; i++)
		{
			if (head.childNodes[i].tagName == fileref.tagName)
			{
				var regexStr = FileName + "$";
				var regex = new RegExp(regexStr);
				if (isJavascript && (head.childNodes[i].src.match(regex)))
				{
					duplicate = true;
				}
				else if (isCss && (head.childNodes[i].href == FileName))
				{
					duplicate = true;
				}
			}
		}
		if (!duplicate)
		{
			head.appendChild(fileref);
		}
	}
}

/*
	@description Increments a jQuery progress bar (calculates percentage)
	@param {Number} Progress
	@param {Number} TotalProgress
	@param {HTMLElement} DivSaveProgress
*/
AdeoApp.Platform.prototype.ShowProgress = function(Progress, TotalProgress, DivSaveProgress)
{
	if (!DivSaveProgress)
		DivSaveProgress = document.getElementById("divSaveProgress");
	DivSaveProgress.style.display = "inline-block";
	$(DivSaveProgress).progressbar({
		"value": Progress * 100 / TotalProgress
	});
}

/*
	@description Returns the total number of properties in a JSON object
	@param {JSON} FileName
*/
AdeoApp.Platform.prototype.CountProperties = function(json) 
{
	var prop;
	var propCount = 0;
	
	for (prop in json) {
		propCount++;
	}
	return propCount;
}

/*
	@description Gets the translation for the current languguage (Window.Culture)
	@param {String} Name
	@returns {String}
*/

AdeoApp.Platform.prototype.Resource = function(Name) 
{
	var resource = Name;
	var defaultCulture = "en-US";
	/*
	if (Resources[window.Culture] && Resources[window.Culture][Name])
	{
		resource = Resources[window.Culture][Name];
	}
	else if (Resources[defaultCulture] && Resources[defaultCulture][Name])
	{
		resource = Resources[defaultCulture][Name];
	}
	*/
	return resource;
}


var AdeoPlatform = new AdeoApp.Platform();



//-----------------------------------------------
//
//	App base class
//
//-----------------------------------------------


/** 
	@class Base class for all applications 
	*/
AdeoApp.App = function(Settings) {
	this.Settings = {};
	var defaultSettings = AdeoApp.App.prototype.DefaultSettings;
	for (var key in defaultSettings)
		this.Settings[key] = defaultSettings[key]; //defaults
	if (Settings)
	{
		for (var key in Settings)
			this.Settings[key] = Settings[key];
	}
	this.LoadResources();
};

AdeoApp.App.prototype.DefaultSettings = {
	"Name": "Untitled App"
}

/*
	@description Lazy-loads the resources listed in the Options array
*/
AdeoApp.App.prototype.LoadResources = function() {
	if (this.Settings.Resources)
	{
		for (var i = 0; i < this.Settings.Resources.length; i++)
		{
			AdeoPlatform.LoadResource(this.Settings.Resources[i].url, this.Settings.Resources[i].type);
		}
	}
}

/**
    @param {String} Guid
    @param {HTMLElement} Container
    @param {function} Callback
*/
AdeoApp.App.prototype.AdminLoad = function(ContentGuid, LayoutGuid, ClonedLayoutKey, Container, Callback) {
	var span = document.createElement("i");
	span.innerHTML = "There are no admin options for this app";
	$(Container).append(span);
	if (Callback)
		Callback(true); //nothing to validate, therefore it's valid
}

/*
	@description Nothing to validate by default, therefore it's valid
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.App.prototype.AdminValidate = function(Container, Callback) {
	if (Callback)
		Callback(true);
}

/*
	@description Nothing to save by default, this is the responsibility of child classes
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.App.prototype.AdminSave = function(ContentGuid, LayoutGuid, Container, Callback) {
	if (Callback)
		Callback(true); //nothing to do
}

/*
	@description Nothing to delete by default, this is the responsibility of child classes
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.App.prototype.AdminDelete = function(ContentGuid, LayoutGuid, Callback) {
	if (Callback)
		Callback(true); //nothing to do	
}

/*
	@description Nothing to delete by default, this is the responsibility of child classes
	@param {HTMLElement} Container
	@param {String} ContentGuid
	@param {String} ClonedLayoutGuid
	@param {String} LayoutGuid
*/
AdeoApp.App.prototype.Preview = function(Container, ContentGuid, ClonedLayoutGuid, LayoutGuid) {
	//nothing to do	
}

/*
	@description Nothing to delete by default, this is the responsibility of child classes
	@param {String} ContentGuid
	@param {String} LayoutGuid
	@param {HTMLElement} Container
	@param {Number} Width
	@param {Number} Height
	@param {Function} Callback
*/
AdeoApp.App.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	Container.innerHTML = this.Settings.Name;
}

AdeoApp.App.prototype.GetProperties = function() {
	return {};
}

//-----------------------------------------------
//
//	Untrusted application (runs in an iFrame)
//
//-----------------------------------------------

/**
	@class There is a facility for apps to run entirely in a iFrame. 
	The concept is that franchisees would be allowed to develop their own apps 
	(although at this point it is unsupported and untested, it is part of the design, just not the original mandate)
	@augments AdeoApp.App
	*/
AdeoApp.UntrustedApp = function(Settings) {
	if (!Settings)
		Settings = {};
	if (!Settings.AdminURL || !Settings.FrontURL)
		throw "AdminURL and FrontURL are required settings for untrusted apps";
	if (!Settings.Name)
		Settings.Name = "Untitled untrusted app"; 
	this.constructor(Settings);
};

AdeoApp.UntrustedApp.prototype = new AdeoApp.App();

AdeoApp.UntrustedApp.prototype.BindCallback = function(iframe, ContentGuid, LayoutGuid, Callback)
{
	$(iframe).unbind("load"); 
    if (Callback)
    {
    	$(iframe).load(function() {
			Callback(true);
		});
    }
    
}

/*
	@description Loads the apps display URL in an iFrame
	@param {String} ContentGuid
	@param {String} LayoutGuid
	@param {HTMLElement} Container
	@param {String} URL
	@param {Bool} ForAdmin
	@param {Function} Callback
*/
AdeoApp.UntrustedApp.prototype.SecureLoad = function(ContentGuid, LayoutGuid, Container, URL, ForAdmin, Callback) {
	var iframe  = document.createElement("iframe");
	var properties = this.GetProperties();
	iframe.style.width = "100%";
	iframe.style.border = "0";
	iframe.frameBorder = "0";
	if (ForAdmin)
	{
		if (properties.admin)
		{
			if (properties.admin.height)
				iframe.style.height = properties.admin.height;
			if (properties.admin.width)
				iframe.style.width = properties.admin.width;
		}
	}
	else
	{
		iframe.style.height = $(Container).height() + "px";
	}
	iframe.style.border = "0";
	Container.appendChild(iframe);
	this.BindCallback(iframe, ContentGuid, LayoutGuid, Callback);
	var iDoc = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
    iDoc.document.open();
    iDoc.document.write("<html><body onload='document.forms[0].submit();'> \
     <form action='" + URL + "#' method='post'> \
     <input type='hidden' name='ContentGuid' value='" + ContentGuid + "' />\
     <input type='hidden' name='LayoutGuid' value='" + LayoutGuid + "' />\
     </form>");
    iDoc.document.close();
}

AdeoApp.UntrustedApp.prototype.AdminLoad = function(ContentGuid, LayoutGuid, ClonedLayoutKey, Container, Callback) {
	this.SecureLoad(ContentGuid, LayoutGuid, Container, this.Settings.AdminURL, true, Callback);
}

AdeoApp.UntrustedApp.prototype.AdminValidate = function(Container, Callback) {
	var iframe = $(Container).find("iframe");
	this.BindCallback(iframe, null, null, Callback);
	iframe.attr("src", this.Settings.AdminURL + "#!/validate/" + escape(new Date()));
}

AdeoApp.UntrustedApp.prototype.AdminSave = function(ContentGuid, LayoutGuid, Container, Callback) {
	var iframe = $(Container).find("iframe");
	this.BindCallback(iframe, ContentGuid, LayoutGuid, Callback);
	iframe.attr("src", this.Settings.AdminURL + "#!/save/" + escape(new Date()));
}

AdeoApp.UntrustedApp.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	this.SecureLoad(ContentGuid, LayoutGuid, Container, this.Settings.FrontURL, false, Callback);
}


/** 
	@class Most of the original apps are ajax apps because they we're developped in house and trusted.
	@augments AdeoApp.App
  */
AdeoApp.AjaxApp = function(Settings) {
	if (!Settings)
		Settings = {};
	if (!Settings.Name)
		Settings.Name = "Untitled AJAX app"; 
	this.constructor(Settings);
};

AdeoApp.AjaxApp.prototype = new AdeoApp.App();

/*
	@description Makes an AJAX request to the app's admin URL and displays it in a DIV container
	@param {String} ContentGuid
	@param {String} LayoutGuid
	@param {String} ClonedLayoutKey
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.AjaxApp.prototype.AdminLoad = function(ContentGuid, LayoutGuid, ClonedLayoutKey, Container, Callback) {
//document.location = this.Settings.AdminURL + "?ContentGuid=" + ContentGuid + "&LayoutGuid=" + LayoutGuid;
	var returnValue = true;
	if (this.Settings.AdminURL)
	{
		var Me = this;
		var settings = this.Settings;
		
		var keyName = eval(formName).Fields[0][0];
		var key = $("#ctl00_MainPlaceHolder_lstsbfield_rptFields_ctl01_" + keyName).val();

		if (key)
		{
			$.ajax({
			  url: settings.AdminURL,
			  cache: false,
			  data: {"ContentGuid": ContentGuid, "LayoutGuid": LayoutGuid, "ClonedLayoutKey": ClonedLayoutKey, "table": formName, "key": key },
			  success: function(html){
			  	html = html.replace(/<form/g, "<span").replace(/<\/form/g, "</span"); //MSIE fix. form tag in general though is bad!
			    Container.innerHTML += html;
			    if (ContentGuid != AdeoApp.Platform.prototype.DefaultsContentGuid)
			    {
			    	var resetClassName = "lnkResetDefault";
					var aReset = document.createElement("a");
					aReset.className = resetClassName;
					aReset.innerHTML = "Reset to defaults";
					aReset.href = "javascript:void(0)";
					aReset.onclick = function() {
						var resetLink = $(Container).find("." + resetClassName).detach();
						Container.innerHTML = "";
						Me.AdminLoad(AdeoApp.Platform.prototype.DefaultsContentGuid, LayoutGuid, ClonedLayoutKey, Container, function() {
							$(Container).prepend(resetLink);
						});
					};
					$(Container).prepend(aReset);
				}
			    Me.PostAdminLoad(ContentGuid, LayoutGuid, Container);
			    if (Callback)
			    	Callback(true);
			  },
			  error: function (err) {
			  	if (Callback)
			    	Callback(false);
			  }
			});
		}
		else
		{
			AdeoPlatform.ShowAlert("Error", "You have to save the form before configuring.");
			returnValue = false;
		}
	}
	else
		AdeoApp.App.prototype.AdminLoad(ContentGuid, LayoutGuid, ClonedLayoutKey, Container, Callback);
		
	return returnValue;
}

AdeoApp.AjaxApp.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	//nothing to do by default
}

AdeoApp.AjaxApp.prototype.PostAdminValidate = function(Container) {
	return true; //nothing to do by default
}

/*
	@description Pulls out everything marked with a "required" class and checks the .val(). When value required, marks it with "missing" class.
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.AjaxApp.prototype.AdminValidate = function(Container, Callback) {
	if (Callback)
	{
		var passed = true;
		var dataItems = $(Container).find(".required").not(".divSubOptions .required"); //ignore sub options since they will be saved separatly
		if (dataItems.length == 0)
			dataItems = $(Container).find(".required");
		dataItems.each(function() {
			var thisPassed = $(this).val() != "";
			passed = passed && thisPassed;
			if (thisPassed)
				$(this).removeClass("missing");
			else
				$(this).addClass("missing");
		});
		passed = passed && this.PostAdminValidate(Container);
		Callback(passed);
	}
}

AdeoApp.AjaxApp.prototype.PerformSave = function(ContentGuid, LayoutGuid, Container, Callback, Data) {
	AdeoPlatform.SaveData(this.Settings.ModuleName, ContentGuid, LayoutGuid, Data, function(Response, e) {
		//if (Response != "0")
		//	alert("PerformSave error: " + Response);//debug
		if (Callback)
			Callback(true);
	});
}

AdeoApp.AjaxApp.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	return Data;
}

/*
	@description Makes an AJAX request to the app's admin URL and displays it in a DIV container
	@param {String} ContentGuid
	@param {String} LayoutGuid
	@param {HTMLElement} Container
	@param {Function} Callback
*/
AdeoApp.AjaxApp.prototype.AdminSave = function(ContentGuid, LayoutGuid, Container, Callback) {
	var Me = this;
	this.AdminValidate(Container, function(Success) {
		if (Success)
		{
			var data = {};
			
			/* Simple data */
			var dataItems = $(Container).find(".data").not(".divSubOptions .data"); //ignore sub options since they will be saved separatly
			if (dataItems.length == 0)
				dataItems = $(Container).find(".data");
			dataItems.each(function() {
				if ($(this).is(':checkbox'))
					data[this.id] = this.checked ? -1 : 0;
				else
					data[this.id] = $(this).val();
			});
			
			/* Complex data, but standard accross most apps */
			if ($(Container).find(".rdoSource").length)
			{
				data["dataSource"] = -1;
				if(!$(Container).find(".rdoDataSource")[0].checked)
					data["dataSource"] = 0;
			}
			
			/* Custom complex data */
			data = Me.PreAdminSave(ContentGuid, LayoutGuid, Container, data);
			
			//alert(JSON.stringify(data)); //debug
			
			if (AdeoPlatform.CountProperties(data) > 0)
				Me.PerformSave(ContentGuid, LayoutGuid, Container, Callback, data);
			else if (Callback)
				Callback(true);
		}
		else
			Callback(false);
	});
}

AdeoApp.AjaxApp.prototype.PostLoad = function(ContentGuid, LayoutGuid, Container, Width, Height) {
	//do nothing by default. Base classes will override
}


AdeoApp.AjaxApp.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	var Me = this;
	if (this.Settings.FrontURL)
	{
		$.ajax({
		  url: this.Settings.FrontURL,
		  data: {"ContentGuid": ContentGuid, "LayoutGuid": LayoutGuid},
		  success: function(html){
		    $(Container).append(html);
		    Me.PostLoad(ContentGuid, LayoutGuid, Container, Width, Height);
		    if (Callback)
		    	Callback();
		  }
		});
	}
	else
	{
		if (Callback)
			Callback();
	}
}

AdeoApp.Platform.prototype.PrintStackTrace = function () 
{
  var callstack = [];
  var isCallstackPopulated = false;
  try {
    i.dont.exist+=0; //doesn't exist- that's the point
  } catch(e) {
    if (e.stack) { //Firefox
      var lines = e.stack.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          callstack.push(lines[i]);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
    else if (window.opera && e.message) { //Opera
      var lines = e.message.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          var entry = lines[i];
          //Append next line also since it has the file info
          if (lines[i+1]) {
            entry += ' at ' + lines[i+1];
            i++;
          }
          callstack.push(entry);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
  }
  if (!isCallstackPopulated) { //IE and Safari
    var currentFunction = arguments.callee.caller;
    while (currentFunction) {
      var fn = currentFunction.toString();
      var fname = fn.substring(fn.indexOf('function') + 8, fn.indexOf('')) || 'anonymous';
      callstack.push(fname);
      currentFunction = currentFunction.caller;
    }
  }
  this.Output(callstack);
}

AdeoApp.Platform.prototype.Output = function (arr) {
  //Optput however you want
  alert(arr.join('\n\n'));
};

/********************************
/cms/app/TableAppBase.js
********************************/
AdeoApp.AjaxApp.prototype.SetHidden = function(Sender) {
	var value = $(Sender).val();
	var id = "#" + Sender.id.replace("sel_", "");
	$(Sender.parentNode).find(id).val(value);
}

AdeoApp.AjaxApp.prototype.GetHidden = function(Sender) {
	var value = $(Sender).val();
	var id = "#" + Sender.id.replace("sel_", "");
	return $(Sender.parentNode).find(id).val();
}

AdeoApp.AjaxApp.prototype.NewOption = function(Value, Name) {
	var option = document.createElement("option");
	option.text  = Name;
	option.value  = Value;
	return option;
}

AdeoApp.AjaxApp.prototype.LoadTableDrops = function(sender) {
	this.LoadRewrites(sender);
	this.LoadFields(sender);
}

AdeoApp.AjaxApp.prototype.LoadRewrites = function(sender) {
	this.LoadOptions(sender, "sbRewrite", "tableKey", "drpRewrite");
}

AdeoApp.AjaxApp.prototype.LoadFields = function(sender) {
	this.LoadOptions(sender, "sbField", "sbTableKey", "drpField");
}

AdeoApp.AjaxApp.prototype.LoadOptions = function(sender, TableName, TableKey, DropDowns) {
	var pl = new SOAPClientParameters();
	pl.add("TableName", TableName);
	pl.add("FilterField", TableKey);
	pl.add("FilterValue", $(sender).val());
	var Me = this;
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "FillDropFilter", pl, true, function(Data) {
		var data = eval(Data);
		$(sender.parentNode).find("." + DropDowns).each(function() {
			this.options.length = 0;
			var val = Me.GetHidden(this);
			this.add(Me.NewOption(-1, SBPhrases["NOSEL"]));
			for (var i = 0; i < data.length; i++)
			{
				var item = data[i];
				var option = Me.NewOption(item.value, item.label);
				option.selected = (val == option.value);
				this.add(option);
			}
			Me.SetHidden(this);
		});
	});
}

var AjaxApp = new AdeoApp.AjaxApp();;

/********************************
/cms/js/mosaic/layout.js
********************************/
AdeoApp.Layout = function() {
	this.Guid = $(".hidLayoutGuid").val();
};

AdeoApp.Layout.prototype.installApp = function(Sender, Width, Height)
{
	var placeholder = $( this.makePlaceholder() );
	var layoutContainer = $(Sender).parents(".divContainer").find(".layoutContainer");
	layoutContainer.masonry('destroy');
	layoutContainer.append( placeholder );
	this.NumberPlaceholders(layoutContainer);
	if (Sender)
		Sender.className = Sender.className.replace("txtRequired", "");
	placeholder.width(Width);
	placeholder.height(Height);
	placeholder.find(".selSize").val(Width + "," + Height);	
	$(placeholder).find("#currentSize").html($(placeholder).width() + " x " + $(placeholder).height());
	$(placeholder).find("input[type=button]").button();
	Layout.InitMasonry(layoutContainer);
	return placeholder;
}

AdeoApp.Layout.prototype.OpenDefaults = function(Sender)
{
	var item = document.getElementById("divDefault");
	item.innerHTML = "";
	var id = $(Sender.parentNode).find(".selectApp").val();
	var layoutKey = $(Sender.parentNode).find(".hidLayoutKey").val();
	var clonedFrom = $(Sender.parentNode).find(".hidClonedFrom").val();
	//alert(clonedFrom);
	//alert(AdeoPlatform.DefaultsContentGuid + ", " + layoutKey);
	if (layoutKey)
	{
		var app = AdeoPlatform.Factory.GetApp(id);
		if (app.AdminLoad(AdeoPlatform.DefaultsContentGuid, layoutKey, clonedFrom, item))
		{
			$(item).dialog({
				"modal": true,
				"position": "top",
				"title": "Set app options",
				"buttons": {
					"Save": function() {
						app.AdminValidate(item, function(IsValid) {
							if (IsValid)
							{
								app.AdminSave(AdeoPlatform.DefaultsContentGuid, layoutKey, item, function() {
									$( item ).dialog( "close" );
								});
							}
						});
					},
					"Cancel": function() {
						$( this ).dialog( "close" );
					}
				},
				"minWidth": 520
			});
		}
	}
	else
	{
		AdeoPlatform.ShowAlert("Error", "You must save the layout before you can change the defaults.")
	}
}

AdeoApp.Layout.prototype.makePlaceholder = function()
{
	var placeholder = document.createElement("div");
	placeholder.className = "item itemData";
	placeholder.innerHTML = document.getElementById("placeholderTemplate").innerHTML;
	$(placeholder).resizable({ distance: 4});
	$(placeholder).bind( "resize", function(event, ui) {
		var layoutContainer = $(this).parents(".layoutContainer");
		layoutContainer.masonry('reload');
		$(placeholder).find(".selSize").val("x");				
		$(placeholder).find("#currentSize").html($(placeholder).width() + " x " + $(placeholder).height());
	});
	return placeholder;
}

AdeoApp.Layout.prototype.SetSize = function(Sender)
{
	var dimensions = Sender.value.split(",");
	$(Sender.parentNode.parentNode).width(dimensions[0]);
	$(Sender.parentNode.parentNode).height(dimensions[1]);	
	$(Sender).parents(".layoutContainer").masonry('reload');	
	$(Sender.parentNode.parentNode).find("#currentSize").html($(Sender.parentNode.parentNode).width() + " x " + $(Sender.parentNode.parentNode).height());
}

AdeoApp.Layout.prototype.removePlaceholder = function(target)
{
	var layoutContainer = $(target).parents(".layoutContainer")[0];
	$(target.parentNode.parentNode).remove();
	$(layoutContainer).masonry('reload');
	this.NumberPlaceholders(layoutContainer);
}

AdeoApp.Layout.prototype.NumberPlaceholders = function(layoutContainer)
{
	var index = 1;
	$(layoutContainer).find(".item .lblNumber").each(function() {
		this.innerHTML = index;
		index++;
	});
}

AdeoApp.Layout.prototype.movePlaceholder = function(target, reIndex)
{
	var layoutContainer = $(target).parents(".layoutContainer")[0];
	var placeholders = $(layoutContainer).find(".item");
	var targetIndex = placeholders.index(target) + reIndex;
	if (targetIndex >= 0 || targetIndex < placeholders.length)
	{
		layoutContainer.removeChild(target);
		$(layoutContainer).masonry('destroy');
		placeholders = $(layoutContainer).find(".item");
		placeholders = placeholders.detach();
		var targetAdded = false;	
		for (var i = 0; i < placeholders.length; i++)
		{
			if (i == targetIndex)
			{
				targetAdded = true;
				layoutContainer.appendChild(target);
			}
			layoutContainer.appendChild(placeholders[i]);
		}
		if (!targetAdded)
		{
			layoutContainer.appendChild(target);
		}
		Layout.InitMasonry($(layoutContainer));
		this.NumberPlaceholders(layoutContainer);
	}
}

AdeoApp.Layout.prototype.changeResolution = function(Sender, width)		
{
	var layoutContainer = $(Sender).parents(".divContainer").find(".layoutContainer");
	layoutContainer.css("width", width);
	layoutContainer.masonry('reload');
}

AdeoApp.Layout.prototype.initResolution = function(layoutContainer, width)		
{	
	layoutContainer.css("width", width);
	/*layoutContainer.masonry('reload');*/
}

AdeoApp.Layout.prototype.clearStyle = function(sender)
{
	sender.className = "";
}

AdeoApp.Layout.prototype.FormValid = function(ContainerId)
{
	var placeholders = $(ContainerId).find(".itemData");
	var txtName = document.getElementById("txtName");
	var txtCode = document.getElementById("txtCode");
	
	if (!txtName.value)
	{
		txtName.className = "txtRequired";
		AdeoPlatform.ShowAlert("Can't save template", "A name is required for the layout template", function() {
			txtName.focus();
		});
	}
	else if (!txtSort.value || isNaN(txtSort.value))
	{
		txtSort.className = "txtRequired";
		AdeoPlatform.ShowAlert("Can't save template", "Sort order must be a numeric value", function() {
			txtName.focus();
		});
	}
	else if (placeholders.length == 0)
	{
		var install = document.getElementById("install");
		install.className = "txtRequired";
		AdeoPlatform.ShowAlert("Can't save template", "You must install at least 1 app", function() {
			install.focus();
		});
	}
	else
	{
		return true;
	}
}

function getRadioValue(name)
{
    for (var i = 0; i < document.getElementsByName('rdoView').length; i++)
    {
        if (document.getElementsByName('rdoView')[i].checked)
        {
                return document.getElementsByName('rdoView')[i].value;
        }
    }
}


AdeoApp.Layout.prototype.Save = function(ContainerId)
{
	var result = false;
	ContainerId = "#" + ContainerId;
	var placeholders = $(ContainerId).find(".itemData");
	var txtName = document.getElementById("txtName");
	var txtClassname = document.getElementById("txtClassname");
	var txtSort = document.getElementById("txtSort");
	
	var rdoDesktop = document.getElementById("rdoDesktop");
	var rdoInner = document.getElementById("rdoInner");
	var rdoMobile = document.getElementById("rdoMobile");
	var rdoLarge = document.getElementById("rdoLarge");
	
	if (this.FormValid(ContainerId))
	{
		var saveData = {};
		saveData.name = txtName.value;
		saveData.classname = txtClassname.value;
		saveData.sortOrder = txtSort.value;
		saveData.siteKey = board_site_key;
		
		saveData.view = "DESKTOP";
		
		if (rdoDesktop.checked)
		{
			saveData.view = rdoDesktop.value;
		}
		else if (rdoMobile.checked)
		{
			saveData.view = rdoMobile.value;
		}
		
		if (rdoInner) { 
			if (rdoInner.checked)
			{
				saveData.view = rdoInner.value;
			}
		}	
		
		if (rdoLarge) { 
			if (rdoLarge.checked)
			{
				saveData.view = rdoLarge.value;
			}
		}			
		
		var Me = this;
		//AdeoPlatform.ShowProgress(0);
		var totalProgress = placeholders.length + 1;
		var progress = 1;
		Layout.DeleteData("WebLayoutItem", Me.Guid, function(returnValue)
		{
			//alert(returnValue);
			AdeoPlatform.ShowProgress(progress, totalProgress);
			var placeHolderIndex = 0;
			var callback = function(returnValue) 
			{
				
				//alert("placeHolderIndex: " + placeHolderIndex + ", " + returnValue);
				if (placeHolderIndex > 0)
					$(placeholders[placeHolderIndex - 1]).find(".hidLayoutKey").val(returnValue);
				progress++;
				AdeoPlatform.ShowProgress(progress, totalProgress);
				if (placeHolderIndex < placeholders.length)
				{
					var appKey = $(placeholders[placeHolderIndex]).find(".selectApp").val();
					var guidKey = $(placeholders[placeHolderIndex]).find(".hidLayoutKey").val();
					var title = $(placeholders[placeHolderIndex]).find(".txtTitle").val();
					var width = $(placeholders[placeHolderIndex]).width();
					var height = $(placeholders[placeHolderIndex]).height();
					var classname = $(placeholders[placeHolderIndex]).find(".txtClassname").val();
					saveData = {
						"layoutKey": Me.Guid,
						"appkey": appKey,
						"position": placeHolderIndex,
						"height": height,
						"width": width,
						"title": title,
						"classname": classname
					};
					placeHolderIndex++;					
					Layout.SaveData("WebLayoutItem", guidKey, saveData, callback);
				}
				else
				{
					//AdeoPlatform.ShowAlert("Success", "Save complete");
					setTimeout(function () {
						document.getElementById("divSaveProgress").style.display ="";
					}, 2000);
				}
			}
			Layout.SaveData("WebLayout", Me.Guid, saveData, callback);
		});	
		result = true;		
	}
	return result;
}

AdeoApp.Layout.prototype.ReLoad = function(Sender)
{
	var ContainerId = $(Sender).parents(".divContainer").attr('id');
	this.Guid = $(Sender).val();
	this.Load(ContainerId);
}

AdeoApp.Layout.prototype.InitMasonry = function(Container) {
	try
	{
	Container.masonry('remove');
	}
	catch (ex)
	{
	}
	Container.masonry({
		itemSelector: '.item',
		columnWidth: 1
	});
}

AdeoApp.Layout.prototype.Load = function(ContainerId)
{
	ContainerId = "#" + ContainerId;
	var Me = this;
	var layoutContainer = $(ContainerId).find(".layoutContainer");
	//init is required
	Layout.InitMasonry(layoutContainer);
	layoutContainer.html("");
	$(".divAdminCenter input[type=button]").button();
	Layout.GetData("WebLayout", this.Guid, function(data) {
		var json = null;
		
		// Default values
		document.getElementById("txtName").value = "";
		document.getElementById("txtClassname").value = "";
		document.getElementById("txtSort").value = 1;
		
		Layout.clearStyle(document.getElementById("txtName"));
		Layout.clearStyle(document.getElementById("txtSort"));
		
		try
		{
			json = jQuery.parseJSON(data);
			if (json.rows && json.rows.length)
			{
				if (!json.rows[0].error)
				{
					document.getElementById("txtName").value = json.rows[0].name;
					document.getElementById("txtClassname").value = json.rows[0].classname;
					document.getElementById("txtSort").value = json.rows[0].sortOrder;	
															
					var rdoDesktop = document.getElementById("rdoDesktop");
					var rdoInner = document.getElementById("rdoInner");
					var rdoMobile = document.getElementById("rdoMobile");
					var rdoLarge = document.getElementById("rdoLarge");

					var desktopViewportWidth = layoutContainer.data("desktopViewport");
					if (json.rows[0].view == "DESKTOP")
					{
						rdoDesktop.checked = true;
						Layout.initResolution(layoutContainer, desktopViewportWidth);
					}
					else if (json.rows[0].view == "LARGE")
					{
						rdoLarge.checked = true;
						Layout.initResolution(layoutContainer, 1290);
					}		
					else if (json.rows[0].view == "INNER")
					{
						rdoInner.checked = true;
						Layout.initResolution(layoutContainer, 792);
					}
					else if (json.rows[0].view == "MOBILE")
					{
						rdoMobile.checked = true;
						Layout.initResolution(layoutContainer, 330);
					} 
					else
					{
						rdoDesktop.checked = true;
						Layout.initResolution(layoutContainer, desktopViewportWidth);	
					}				
					
					Layout.GetData("WebLayoutItem", Me.Guid, function(data) {
						json = jQuery.parseJSON(data);
						for (var i = 0; i < json.rows.length; i++)
						{
							var placeholder = Me.installApp(rdoDesktop, json.rows[i].width, json.rows[i].height);
							$(placeholder).find(".selectApp").val(json.rows[i].appKey);
							$(placeholder).find(".hidLayoutKey").val(json.rows[i].guidKey);
							$(placeholder).find(".hidClonedFrom").val(json.rows[i].clonedFrom);
							$(placeholder).find(".txtTitle").val(json.rows[i].title);
							$(placeholder).find(".txtClassname").val(json.rows[i].classname);
							$(placeholder).find("#currentSize").html(json.rows[i].width + " x " + json.rows[i].height);
						}
						layoutContainer.masonry('reload');
					});
				}
				else
					AdeoPlatform.ShowAlert("Error", json.rows[0].error);
			}
			else
			{
				layoutContainer.masonry('reload');
			}
		}
		catch (ex)
		{
			AdeoPlatform.ShowAlert("Error", "Failed to load layout. Press back and try again. <br />Details (if available): <i>" + data.message + "</i>");
		}
	});
}

AdeoApp.Layout.prototype.Delete = function(DropMosaic)
{
	var layoutKey = $(DropMosaic).val();
	var selectedIndex = DropMosaic.selectedIndex;
	if (selectedIndex + 1 < DropMosaic.options.length)
	{
		AdeoPlatform.ShowConfirm("Confirm permanent deletion", "Are you sure you want to delete this layout? This action can not be un-done", function() {
			Layout.DeleteData("WebLayout", layoutKey, function(data) {
				if (data == 1)
				{
					$(DropMosaic.options[selectedIndex]).remove();
					AdeoPlatform.ShowAlert("Success", "Layout deleted.");
				}
				else
				{
					AdeoPlatform.ShowAlert("Delete", "Failed to delete layout. It may be in use.");
				}
			});
		});
	}
}

AdeoApp.Layout.prototype.Clone = function(LayoutKey, ParentRow)
{
	Layout.CloneData("WebLayout", LayoutKey, function(data) {
		if (data)
		{
			AdeoPlatform.ShowAlert("Success", "Layout cloned successfully.", function() {
			
				document.location.reload()
			});
		}
		else
		{
			AdeoPlatform.ShowAlert("Clone", "Failed to clone layout.");
		}
	});
}

AdeoApp.Layout.prototype.SOAP_URL = "/cms/controller/services/AdminData.asmx";

AdeoApp.Layout.prototype.CloneData = function(ModuleName, Guid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("GuidKey", Guid);
	SOAPClient.invoke(this.SOAP_URL, "CloneData", parameters, true, Callback);
}

AdeoApp.Layout.prototype.GetData = function(ModuleName, Guid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("GuidKey", Guid);
	SOAPClient.invoke(this.SOAP_URL, "GetData", parameters, true, Callback);
}

AdeoApp.Layout.prototype.SaveData = function(ModuleName, Guid, Data, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("GuidKey", Guid);
	parameters.add("Data", JSON.stringify(Data));
	SOAPClient.invoke(this.SOAP_URL, "SaveData", parameters, true, Callback);
}

AdeoApp.Layout.prototype.DeleteData = function(ModuleName, Guid, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ModuleName", ModuleName);
	parameters.add("GuidKey", Guid);
	SOAPClient.invoke(this.SOAP_URL, "DeleteData", parameters, true, Callback);
}

var Layout;

function saveMosaic(ControlId)
{
	if (Layout.Save(ControlId))
	{	
		var name = $("#" + ControlId).find("#txtName").val();
		$("#" + ControlId).find(".drpMosaic option:selected").text(name);
	}
	return $("#" + ControlId).find(".drpMosaic").val();
}

function validateMosaic(ControlId)
{
	return Layout.FormValid("#" + ControlId);
}


function initMosaic(ControlId)
{
	if (!window.Layout)
		window.Layout = new AdeoApp.Layout();
	Layout.ReLoad($("#" + ControlId).find(".drpMosaic")[0]);
	
	$("#" + ControlId).find("input:checked[type=radio]").click();
};

/********************************
/cms/resources/javascript/toolbox.js
********************************/
var URL_SOAP_TOOLBOX = "/cms/controller/services/toolbox.asmx";
var URL_SOAP_SAVE = "/cms/model/services/save.asmx";

var trueStr = 'True'; /* Needs to be equal to .Net true.ToString() */
var falseStr = 'False';

var originalEdit, originalOnClick, originalClass, originalHtml;
var liveField, liveTable, liveKeyVal, liveCulture;

var COOKIE_DEFAULT_CULTURE = "CK_DEFAULT_CULTURE";

if (window.$)
{
	$(document).ready(function() {
		/*	
		var shortCulture = getBrowserCulture().substr(0, 2);
		var defaultCulture = getCookie(COOKIE_DEFAULT_CULTURE);
		var confirmRedirect = false;
		if (!defaultCulture)
		{
			defaultCulture = shortCulture;
			confirmRedirect = true; /* Never been asked.
		}

		var shortBoardCulture = board_culture.substr(0, 2);
		setCookie(COOKIE_DEFAULT_CULTURE, shortBoardCulture);

		if (defaultCulture != shortBoardCulture)
		{
			// Find the culture that matches the browser.
			var i = 0;
			while (SBCultures[i][0].substr(0, 2) != defaultCulture) 
			{
				i++;
			}
			var currentCulture = SBCultures[i][0].substr(0, 2);
			
			// Ask the user to redirect to it
			var confirmed = true;
			if ((i < SBCultures.length) && (!confirmRedirect || (confirmed = confirm(SBCultures[i][1]))))
			{
				setCookie(COOKIE_DEFAULT_CULTURE, currentCulture);
				//document.location = getMirrorUrl(SBCultures[i][0]);
			}
		}
		*/
		bodyLoader();
	});
}

function getMirrorUrl(currentCulture)
{
	var redirectUrl = "/";
	if (window.mirrorUrls)
	{
		var i = 0;
		while ((i < mirrorUrls.length) && (mirrorUrls[i][0] != currentCulture.substr(0, 2)))
		{
			i++;
		}
		if (i < mirrorUrls.length)
		{
			redirectUrl = mirrorUrls[i][1];
		}
	}
	
	return redirectUrl;
}

function getBrowserCulture()
{
	return (navigator["language"])?navigator["language"]:navigator["userLanguage"];
}


function editLivePage(sender, field, table, keyVal, culture)
{
	liveField = field;
	liveTable = table;
	liveKeyVal = keyVal;
	liveCulture = culture;

	alert(SBPhrases["EDIT_MODE"]); 
	if(document.addEventListener)
	{
		document.addEventListener("keyup",keyCapt,false);
	}
	else
	{
		document.attachEvent("onkeyup",keyCapt);
	} 

	originalClass = sender.className;
	originalOnClick = sender.ondblclick;
	originalHtml = sender.innerHTML;
	originalEdit = sender;
	originalEdit.className = "sbLiveEdit";
	sender.contentEditable = true;
	document.designMode = 'on';
	originalEdit.focus();
}
function keyCapt(e)
{
	if (window.event)
	{
		e = window.event;
	}
	var codeS = 83;
	var codeQ = 81;
	var codeB = 66;
	var codeI = 73;
	var codeEscape = 27;

	if (e.ctrlKey && e.altKey)
	{
		if ((e.keyCode == codeS) || (e.keyCode == codeQ))
		{
			if (e.keyCode == codeS)
			{
				var pl = new SOAPClientParameters();
				pl.add("TableName", liveTable);
				pl.add("FieldName", liveField);
				pl.add("FieldValue", originalEdit.innerHTML);
				pl.add("KeyValue", liveKeyVal);
				pl.add("CultureKey", liveCulture);
				SOAPClient.invoke(URL_SOAP_SAVE, "SaveField", pl, true, SaveField_CallBack);
			}
			else
			{
				editLivePageStop();
			}
		}
/*
		else
		{
			if (e.keyCode == codeB)
			{
				format_sel("b")
			}
			else if (e.keyCode == codeI)
			{
				format_sel("i")
			}
			//alert(e.keyCode);
		}
*/
	}
	else if (e.keyCode == codeEscape)
	{
		editLivePageStop();
		originalEdit.innerHTML = originalHtml;
	}
}

function editLivePageStop()
{
	originalEdit.contentEditable = false;
	document.designMode = 'off';
	originalEdit.className = originalClass;
	originalEdit.ondblclick = originalOnClick;
	if(document.removeEventListener)
	{
		document.removeEventListener("keyup", keyCapt, false);
	}
	else
	{
		document.detachEvent("onkeyup", keyCapt);
	}
	
}

function SaveField_CallBack(data)
{
	if (isNaN(data))
	{
		alert(data.toSource());
	}
	else
	{
		alert(SBPhrases["SAVED"]);
		editLivePageStop();
	}
}

//http://www.oreillynet.com/pub/a/javascript/2001/12/21/js_toolbar.html
/*
just plan doesn't work and sick of trying
function format_sel(v) 
{
	var sel = document.selection;
	if (!sel)
	{
		sel = window.getSelection();
	}
	var range;
	if (sel.createRange)
	{
		range = sel.createRange();
	}
	else
	{
		range = sel.getRangeAt(0);
	}

childNodes.startContainer.textContent = "<" + v + ">" + range.startContainer.textContent + "</" + v + ">";

alert(typeof(range))
	var str = range.text;
	alert(str);
	range.text = "<" + v + ">" + str + "</" + v + ">";
//alert(sel);
  return;
}
*/
function shortCulture(Culture)
{
	if (!Culture)
	{
		Culture = board_culture;
	}
	return Culture.substr(0, 2);
}

function getMailFormFieldCaption(input)
{
	var genericName = "field_";
	var name = "";
	if (input.name.substring(0, genericName.length) == genericName)
	{
		var captionField = document.getElementById(input.id + "_caption");
		if (captionField)
		{
			name = captionField.innerHTML;
		}
	}
	
	if (name == "")
	{
		return input.name.replace(/_/g, ' ');
	}
	else
	{
		return name;
	}
}

var lastSender;
function ajaxMailTo(sender, recipientFunction, recipientVariable)
{
	var form = sender;
	var msg = "", name, lastname;
	var cancelled = false;
	$(sender).hide();


	if (ValidateCaptcha() == false) {
		if (SBPhrases["REQUIRED_CAPTCHA"])
		  	alert(SBPhrases["REQUIRED_CAPTCHA"]);
		else
			alert("Please check the captcha form.");
		$(sender).show();
		return false;
	}

	while ((msg == "") && (form.parentNode) && (!cancelled))
	{
		form = form.parentNode;
		var inputs = form.getElementsByTagName("INPUT");
		var selects = form.getElementsByTagName("SELECT");
		var textareas = form.getElementsByTagName("TEXTAREA");

		var requiredFields = "";
		for (var i = 0; i < inputs.length; i++)
		{
			if ((inputs[i].type != "button") && (inputs[i].name.toLowerCase() != "viewstateuserkey") && (inputs[i].name != "__VIEWSTATE") && (((inputs[i].type != "radio") && (inputs[i].type != "checkbox")) || (inputs[i].checked)))
			{
				lastname = name;
				name = getMailFormFieldCaption(inputs[i]);
				if (inputs[i].value)
				{
					if (lastname != name)
					{ 
						msg += "\n" + name + ": ";
					}
					else
					{
						msg += ", ";
					}
					msg += inputs[i].value;
				}
				if ((inputs[i].getAttribute("required")) && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && ((inputs[i].value == "") || (inputs[i].value == inputs[i].defaultValue)))
				{
					requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], name) + "\n";
					inputs[i].focus();
					cancelled = true; /* breaks loop. */
				}
			} 
		}
		
		for (var i = 0; i < selects.length; i++)
		{
			var selections = "";
			var multipleSelections = false;
			for (j = 0; j < selects[i].options.length; j++)
			{
				if (selects[i].options[j].selected)
				{
					if (selections != "")
					{
						selections += "\n\t";
						multipleSelections = true;
					}
					selections += selects[i].options[j].text;
				}
			}
			var breaker = "";
			if (multipleSelections)
			{
				breaker = "\n\t";
			}
			name = getMailFormFieldCaption(selects[i]);
			if ((selects[i].getAttribute("required")) && (selects[i].getAttribute("required").toLowerCase() == "yes" || selects[i].getAttribute("required").toLowerCase() == "required") && (selections == ""))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], name) + "\n";
			}
			msg += "\n" + name + ": " + breaker + selections;
		}
		
		for (var i = 0; i < textareas.length; i++)
		{
			name = getMailFormFieldCaption(textareas[i]);
			msg += "\n" + name + ":\n" + textareas[i].value; 
			if ((textareas[i].getAttribute("required") == "yes" || textareas[i].getAttribute("required") == "required")  && (textareas[i].value == ""))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], name) + "\n";
				textareas[i].focus();
			}
		}
	}

	if (requiredFields)
	{
		alert(requiredFields);
		cancelled = true;
		$(sender).show();		
	}

	if (!cancelled)
	{
		if (!recipientFunction)
		{
			recipientFunction = "SendEmail";
		}
		
		var replyto = "";
		var email = document.getElementById('email');
		if (email)
			replyto = email.value;
		else
		{
			email = document.getElementById('courriel');
			if (email)
				replyto = email.value;
			else
			{
				email = document.getElementById('txtemail');
				if (email)
					replyto = email.value;
				else
				{
					email = document.getElementById('txtcourriel');
					if (email)
						replyto = email.value;					
				}
			}
		}
				

	    /* Debug info */
		msg += "\n\nBrowser used: " + navigator.userAgent.toString();

		var pl = new SOAPClientParameters();
		pl.add("message", msg);
		if (replyto != "")
		{
			recipientFunction = "SendEmailWithReply";
			pl.add("replyto", replyto);
		}
		pl.add("recipient", recipientVariable);
		
		//alert(msg);
		lastSender = sender;
		SOAPClient.invoke(URL_SOAP_TOOLBOX, recipientFunction, pl, true, function(data) {
		    $(sender).show();
		    $(form).find("input[type=text], textarea").val("");
			if (ajaxMailTo_CallBack)
				ajaxMailTo_CallBack(data);
		});
	}	
}

function collectFormData(sender, key)
{
	var form = sender;
	var name, lastname;
	var cancelled = false;
	var returnValue = {};
	var done = false;

	if (!ValidateCaptcha(sender.parentNode)) {
		if (SBPhrases["REQUIRED_CAPTCHA"])
		  	alert(SBPhrases["REQUIRED_CAPTCHA"]);
		else
			alert("Please check the captcha form.");
		return false;
	}

	while (form.parentNode && !cancelled && !done)
	{
		form = form.parentNode;
		done = form.className && (form.className.toLowerCase() == "divwrap" || form.className.toLowerCase() == "divcampaigncontainer" || form.className.toLowerCase() == "fancybox-inner");

		var inputs = form.getElementsByTagName("INPUT");
		var selects = form.getElementsByTagName("SELECT");
		var textareas = form.getElementsByTagName("TEXTAREA");

		var requiredFields = "";
		for (var i = 0; i < inputs.length; i++)
		{
			if ((inputs[i].type != "button") && (inputs[i].name != "__VIEWSTATE") && (inputs[i].name.toLowerCase() != "viewstateuserkey") && (inputs[i].name != "g-recaptcha-response") && (inputs[i].name != "ViewStateUserKey") && (((inputs[i].type != "radio") && (inputs[i].type != "checkbox")) || (inputs[i].checked)))
			{
				lastname = name;
				if (key)
					name = inputs[i].name;
				else
					name = getMailFormFieldCaption(inputs[i]);
				if (inputs[i].value)
				{
					if (lastname != name)
					{
						returnValue[name] = inputs[i].value;
					}
					else
					{
						if (inputs[i].type != "text")
							returnValue[name] += ", " + inputs[i].value;
					}
				}
				if ((inputs[i].getAttribute("required")) && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && ((inputs[i].value == "") || (inputs[i].value == inputs[i].defaultValue)))
				{
					requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(inputs[i])) + "\n";
					inputs[i].focus();
					cancelled = true; /* breaks loop. */
				}
			} 
			
		}
		
		for (var i = 0; i < selects.length; i++)
		{
			var selections = "";
			var multipleSelections = false;
			for (j = 0; j < selects[i].options.length; j++)
			{
				if (selects[i].options[j].selected)
				{
					if (selections != "")
					{
						selections += "\n\t";
						multipleSelections = true;
					}
					selections += selects[i].options[j].text;
				}
			}
			var breaker = "";
			if (multipleSelections)
			{
				breaker = "\n\t";
			}
			
			if (key)
				name = selects[i].name;
			else
				name = getMailFormFieldCaption(selects[i]);
					
			
			if ((selects[i].getAttribute("required")) && (selects[i].getAttribute("required").toLowerCase() == "yes" || selects[i].getAttribute("required").toLowerCase() == "required") && (selections == ""))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(selects[i])) + "\n";
			}
			returnValue[name] = breaker + selections;	
		}
		
		for (var i = 0; i < textareas.length; i++)
		{
			if (textareas[i].name != "g-recaptcha-response")
				{
				if (key)
					name = textareas[i].name;
				else
					name = getMailFormFieldCaption(textareas[i]);
				returnValue[name] = textareas[i].value; 
				if ((textareas[i].getAttribute("required") == "yes" || textareas[i].getAttribute("required") == "required") && (textareas[i].value == ""))
				{
					requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(textareas[i])) + "\n";
					textareas[i].focus();
				}
			}
		}
	}

	if (requiredFields)
	{
		alert(requiredFields);
		return null;
	}
	else if (cancelled)
		return	null;
	else
		return returnValue;
}

function ajaxMailTo_CallBack(data)
{
	if (data)
	{
		alert(data.toSource());
	}
	else
	{
		alert(SBPhrases["MAIL_SENT"]);
	}
	if (lastSender)
	{
		lastSender.disabled = false;
	}
}

function ValidateCaptcha(sender) {

	if ($(sender).find(".g-recaptcha").length == 0)
		return true;
	
	var v = grecaptcha.getResponse();
	var result = false;
	if(v.length == 0)
	{
	//    alert("You can't leave Captcha Code empty");
	    return false;
	}
	if(v.length != 0)
	{
	//	alert("Captcha completed");
		result = true; 
	}
	return result;
}

/*********************************************
  CAMPAIGN
**********************************************/
var campaignData = {};
var addCampaignButton = false;
var validateCampaign = '';
function collectCampaignData(sender, key, step)
{
	var form = sender;
	var name, lastname;
	var cancelled = false;
	var returnValue = {};
	var done = false;

	if (!ValidateCaptcha()) {
		if (SBPhrases["REQUIRED_CAPTCHA"])
		  	alert(SBPhrases["REQUIRED_CAPTCHA"]);
		else
			alert("Please check the captcha form.");
		return false;
	}

	while (form.parentNode && !cancelled && !done)
	{
		form = form.parentNode;
		if (step)
			done = form.className && (form.className.toLowerCase() == "step" || form.className.toLowerCase() == "divstep" || form.className.toLowerCase() == "divcampaigncontainer");
		else
			done = form.className && form.className.toLowerCase() == "divcampaigncontainer";
				
		var inputs = form.getElementsByTagName("INPUT");
		var selects = form.getElementsByTagName("SELECT");
		var textareas = form.getElementsByTagName("TEXTAREA");

		var requiredFields = "";

		for (var i = 0; i < inputs.length; i++)
		{
			if ((inputs[i].type != "button") && (inputs[i].name != "__VIEWSTATE") && (inputs[i].name.toLowerCase() != "viewstateuserkey") && (inputs[i].type != "radio") && (((inputs[i].type != "checkbox")) || (inputs[i].checked)))
			{
				lastname = name;
				if (key)
					name = inputs[i].name;
				else
					name = getMailFormFieldCaption(inputs[i]);
				if (inputs[i].value)
				{
					if (lastname != name)
					{
						campaignData[name] = inputs[i].value;
					}
					else
					{
						campaignData[name] += ", " + inputs[i].value;
					}
				}
				if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && ((inputs[i].value == "") || (inputs[i].value == inputs[i].defaultValue)))
				{
					requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(inputs[i])) + "\n";
					inputs[i].focus();
					cancelled = true; /* breaks loop. */
				}
			} 
		}

		/* RADIO */
		name = "";
		var hasValue = false;
		var hasRadio = false;
		var isRequired = false;
		for (var i = 0; i < inputs.length; i++)
		{
			if (inputs[i].type == "radio")
			{
				hasRadio = true;
				lastname = name;
				if (key)
					name = inputs[i].name;
				else
					name = getMailFormFieldCaption(inputs[i]);

				if (lastname != name && lastname != "")
				{
					if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && !hasValue)
					{
						requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(inputs[i])) + "\n";
						cancelled = true; /* breaks loop. */
					}
				}
				else
				{
					if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required")) {
						isRequired = true;
					}

					if (inputs[i].checked) {
						hasValue = true;
						campaignData[name] = inputs[i].value;
					}
				}
			} 
		}

		if (hasRadio) {
			if (isRequired && !hasValue)
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], lastname) + "\n";
				cancelled = true; /* breaks loop. */
			}
		}

		for (var i = 0; i < selects.length; i++)
		{
			var selections = "";
			var multipleSelections = false;
			for (j = 0; j < selects[i].options.length; j++)
			{
				if (selects[i].options[j].selected)
				{
					if (selections != "")
					{
						selections += "\n\t";
						multipleSelections = true;
					}
					selections += selects[i].options[j].text;
				}
			}
			var breaker = "";
			if (multipleSelections)
			{
				breaker = "\n\t";
			}
			
			if (key)
				name = selects[i].name;
			else
				name = getMailFormFieldCaption(selects[i]);
					
			
			if ((selects[i].getAttribute("required")) && (selects[i].getAttribute("required").toLowerCase() == "yes" || selects[i].getAttribute("required").toLowerCase() == "required") && (selections == "" || selections.toLowerCase() == "- select -" || selections.toLowerCase() == "- selectionnez -" ))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(selects[i])) + "\n";
			}
			campaignData[name] = breaker + selections;	
		}
		
		for (var i = 0; i < textareas.length; i++)
		{
			if (key)
				name = textareas[i].name;
			else
				name = getMailFormFieldCaption(textareas[i]);
			campaignData[name] = textareas[i].value; 
			if ((textareas[i].getAttribute("required") == "yes" || textareas[i].getAttribute("required") == "required") && (textareas[i].value == ""))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(textareas[i])) + "\n";
				textareas[i].focus();
			}
		}
	}

	if (requiredFields)
	{
		$(sender).show();
		alert(requiredFields);
		return false;
	}
	else if (cancelled)
		return	false;
	else
		return true;
}

function doSaveCampaignTo(sender, title, guid, message)
{
	$(sender).hide();
	pl = new SOAPClientParameters();
	pl.add("Campaign", title);
	pl.add("Data", JSON.stringify(message));		
	pl.add("DealerGuid", guid);
	pl.add("LastStep", true);
	pl.add("CultureCode", board_culture);
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaign", pl, true, doSaveCampaignTo_CallBack);
}

function doSaveCampaign(sender)
{		
	$(sender).hide();
	var spanCampaignTitle = document.getElementById("spanCampaignTitle");
	var spanCampaignGuid = document.getElementById("spanCampaignGuid");
			
	if (collectCampaignData(sender, true, false))
	{	
		pl = new SOAPClientParameters();
		pl.add("Campaign", spanCampaignTitle.innerHTML);
		pl.add("Data", JSON.stringify(campaignData));		
		pl.add("DealerGuid", spanCampaignGuid.innerHTML);
		pl.add("LastStep", true);
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaign", pl, true, function(url) {		
			// Thanks page			
			document.location = url;
		});
	}
	else 
	{	
		$(sender).show();
	}	
}

function doSaveCampaignFront(sender, message)
{		
	$(sender).hide();
	var spanCampaignTitle = document.getElementById("spanCampaignTitle");
	var spanCampaignEmail = document.getElementById("spanCampaignEmail");
	var spanCampaignThanks = document.getElementById("spanCampaignThanks");
				
	if (collectCampaignData(sender, true, false) || message)
	{
		var title = "Request";
		if (spanCampaignTitle)
			title = spanCampaignTitle.innerHTML;

		var email = "";
		if (spanCampaignEmail)
			email = spanCampaignEmail.innerHTML;
			
		if (message) {
			var data = JSON.stringify(message);
		} else {
			var data = JSON.stringify(campaignData);
		}
		
		pl = new SOAPClientParameters();
		pl.add("Campaign", title);
		pl.add("Data", data);		
		pl.add("DealerGuid", createGuid());
		pl.add("Email", email);
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaignWithEmail", pl, true, function(url) {		
			// Thanks page	
			if (spanCampaignThanks)	
				if (spanCampaignThanks.innerHTML == "") {
					alert(SBPhrases["MAIL_SENT"]);
					$(sender).show();
				}
				else
					document.location = spanCampaignThanks.innerHTML
			else
				document.location = url;

		});
	}
	else 
	{
		$(sender).show();
	}	
}

function createGuid()  
{  
   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
      var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);  
      return v.toString(16);  
   });  
}  
  
var guid = createGuid();  
function doSaveStepCampaign(sender, step)
{		
	$(sender).hide();
	var spanCampaignTitle = document.getElementById("spanCampaignTitle");
	var spanCampaignGuid = document.getElementById("spanCampaignGuid");
	var steps = $(".divCampaignContainer .step");
						
	if (collectCampaignData(sender, true, (steps.length != step)))
	{			
		pl = new SOAPClientParameters();
		pl.add("Campaign", spanCampaignTitle.innerHTML);
		pl.add("Data", JSON.stringify(campaignData));		
		pl.add("DealerGuid", spanCampaignGuid.innerHTML);
		pl.add("LastStep", (steps.length == step));
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaign", pl, true, function(url) {
			if (steps.length == step)
			{	// Thanks page
				document.location = url;
			}
			else 
			{	// Show next step	
				showNextStep(this, step);
				
				if (addCampaignButton) {	
					if (steps.length == (step + 1))
					{		
						$(".divCampaignContainer .step:eq(" + step + ")").append('<input onclick="doSaveStepCampaign(this, ' + (step + 1) +')" class="btnCampaignButton btnCampaignButtonSend" type="button" value="' + SBPhrases["CAMPAIGN_SEND"] + '" />')
					}
					else {
						$(".divCampaignContainer .step:eq(" + step + ")").append('<input onclick="doSaveStepCampaign(this, ' + (step + 1) +')" class="btnCampaignButton btnCampaignButtonNext" type="button" value="' + SBPhrases["CAMPAIGN_CONTINUE"] + '" />')
					}
				}
			}
		});		
	}
	else 
	{
		$(sender).show();
	}	
}

function showNextStep(sender, step)
{
	$(".divCampaignContainer h3:eq(" + step + ")").fadeIn(function() {
		$(".divCampaignContainer .step:eq(" + step + ")").fadeIn(function() {	
			var $target = $('html,body'); 
			$target.animate({scrollTop: $(".divCampaignContainer .step:eq(" + step +")").offset().top - $(".divCampaignContainer .step:first").offset().top }, 'slow');			
		});
	});		
}

var dropDowns;
function bodyLoader()
{
	dropDowns = document.getElementsByTagName("SELECT");
	for (var i = 0; i < dropDowns.length; i++)
	{
		var pl = new SOAPClientParameters();
		if (dropDowns[i].name.substring(0, 3) == "lst")
		{
			pl.add("TableName", dropDowns[i].name.substring(3));
			pl.add("DropIndex", i);
			SOAPClient.invoke(URL_SOAP_TOOLBOX, "FillDrop", pl, true, fillDrop_CallBack);
		}
	}
}

function fillDrop_CallBack(data)
{
	if (data)
	{
		if (data.split)
		{
			var lines = data.split("\n");
			var drp = dropDowns[parseInt(lines[0])];
			drp.name = lines[1];
			if (drp.options.length == 0)
			{
				for (var i = 2; i < lines.length; i++)
				{
					if (lines[i] != "")
					{
						var item = lines[i].split("|");
						drp.options[drp.options.length] = new Option(item[1], item[0]);
					}
				}
			}
		}
		else
		{
			alert("Error: " + data.toSource());
		}
	}
}

function GetCreatedTimestamp()
{
	var pl = new SOAPClientParameters();
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "GetCreatedTimestamp", pl, true, GetCreatedTimestamp_CallBack);
}

function DumpSpringBoard()
{
	var pl = new SOAPClientParameters();
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "DumpSpringBoard", pl, true, GetCreatedTimestamp_CallBack);
}

function GetCreatedTimestamp_CallBack(data)
{
	document.getElementById('divStarted').innerHTML = data;
}
function ClearLog()
{
	var pl = new SOAPClientParameters();
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "ClearLog", pl, true, ClearLog_CallBack);
}
function ClearLog_CallBack(data)
{
	if (data)
	{
		jAlert(data.toSource());
	}
	else
	{
		ReloadLog();
	}
}

function ReloadLog()
{
	document.getElementById('frmLog').contentWindow.location.reload(true);
}

function setCookie(name, Value, Days)
{
	if (!Days) 
	{
		Days = 365;
	}
	var endDate = new Date();
	endDate.setTime(endDate.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = String.format("{0}={1}; expires={2}; path=/;", name, escape(Value), endDate.toGMTString());
}
function getCookie(Name, defaultValue)
{
	var returnValue = getCookieRaw(Name);
	if (!returnValue)
	{
		returnValue = defaultValue;
	}
	return returnValue
}
function getCookieRaw(Name)
{
	var cookieName = Name + "=";
	var cookieLength = document.cookie.length;
	var cookieStart = 0;
	while (cookieStart < cookieLength)
	{
		var variableStart = cookieStart + cookieName.length;

		if (document.cookie.substring(cookieStart, variableStart) == cookieName)
		{
			var variableEnd = document.cookie.indexOf (";", variableStart);
			if (variableEnd == -1)
			{
				variableEnd = cookieLength;
			}
			var returnValue = unescape(document.cookie.substring(variableStart, variableEnd));
			if (returnValue == "null")
			{
				returnValue = null;
			}
			return returnValue;
		}

		cookieStart = document.cookie.indexOf(" ", cookieStart) + 1;

		if (cookieStart == 0)
		{
			break;
		}
	}
}

function getBrowserCulture()
{
	return (navigator["language"])?navigator["language"]:navigator["userLanguage"];
}


SpringBoard = {};

/* General toolbox */
SpringBoard.Toolbox = function() { };

SpringBoard.Toolbox.prototype.AddNewsletterSubscriber = function (FirstName, LastName, Email, Callback) {
	if (FirstName && LastName && Email)
	{
		var pl = new SOAPClientParameters();
		pl.add("FirstName", FirstName);
		pl.add("LastName", LastName);
		pl.add("Email", Email);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "AddNewsletterSubscriber", pl, true, Callback);
	}
	else
	{
		alert("First name, last name and email are required");
	}
}

SpringBoard.Toolbox.prototype.AddNewsletterSubscriberWithSource = function (FirstName, LastName, Email, Source, Callback) {
	if (FirstName && LastName && Email)
	{
		var pl = new SOAPClientParameters();
		pl.add("FirstName", FirstName);
		pl.add("LastName", LastName);
		pl.add("Email", Email);
		pl.add("Source", Source);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "AddNewsletterSubscriberWithSource", pl, true, Callback);
	}
	else
	{
		alert("First name, last name and email are required");
	}
}

SpringBoard.Toolbox.prototype.AddToNewsletterSubscriber = function (ApiKey, ListID, FirstName, LastName, Email, Callback) {
	if (ApiKey && ListID && FirstName && LastName && Email)
	{
		var pl = new SOAPClientParameters();
		pl.add("ApiKey", ApiKey);
		pl.add("ListID", ListID);
		pl.add("FirstName", FirstName);
		pl.add("LastName", LastName);
		pl.add("Email", Email);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "AddToNewsletterSubscriber", pl, true, Callback);
	}
	else
	{
		alert("First name, last name and email are required");
	}
}

SpringBoard.Toolbox.prototype.AddToNewsletterSubscriberWithSource = function (ApiKey, ListID, FirstName, LastName, Email, Source, Callback) {
	if (ApiKey && ListID && FirstName && LastName && Email && Source)
	{
		var pl = new SOAPClientParameters();
		pl.add("ApiKey", ApiKey);
		pl.add("ListID", ListID);
		pl.add("FirstName", FirstName);
		pl.add("LastName", LastName);
		pl.add("Email", Email);
		pl.add("Source", Source);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "AddToNewsletterSubscriberWithSource", pl, true, Callback);
	}
	else
	{
		alert("First name, last name and email are required");
	}
}

var Toolbox = new SpringBoard.Toolbox();


/* Security */

SpringBoard.Security = function() { };

SpringBoard.Security.prototype.UserLogin = function (UserName, Password, UserLogin_CallBack, Remember) {
    var hosts = new Array();
    var callBackCount = this.LoadHosts(hosts);
    var callbackIndex = 0;
    var wsdlCache = null;

    function doLogin() {
        var pl = new SOAPClientParameters();
        pl.add("UserName", UserName);
        pl.add("Password", Password);
        pl.add("SiteKey", board_site_key);
        pl.add("Remember", Remember == true);
        var hostName = ""; /* hosts[callbackIndex];
        if (hostName)
            hostName = "http://" + hostName;
            */
        var soapUrl = hostName + URL_SOAP_TOOLBOX;
        if (!SOAPClient_cacheWsdl[soapUrl])
            SOAPClient_cacheWsdl[soapUrl] = wsdlCache;
        SOAPClient.invoke(hostName + URL_SOAP_TOOLBOX, "UserLogin", pl, true, function (Data) {
            callbackIndex++;
            callbackIndex = callBackCount; //This just doesn't work.... so I give up
            if (!wsdlCache)
                wsdlCache = SOAPClient_cacheWsdl[soapUrl];
            //alert("Username: " + UserName + ", " + Data + ", callbackIndex: " + callbackIndex);
            if (callbackIndex == callBackCount)//Has callback and on last callback.
                UserLogin_CallBack(Data);
            else
                doLogin();
        });
    }
    doLogin();
}

SpringBoard.Security.prototype.UserLoginChallenge = function (UserName, Password, Question, Response, UserLogin_CallBack, Remember) {
    var hosts = new Array();
    var callBackCount = this.LoadHosts(hosts);
    var callbackIndex = 0;
    var wsdlCache = null;

    function doLogin() {
        var pl = new SOAPClientParameters();
        pl.add("UserName", UserName);
        pl.add("Password", Password);
        pl.add("Question", Question);
        pl.add("Response", Response);
        pl.add("SiteKey", board_site_key);
        pl.add("Remember", Remember == true);
        var hostName = ""; /* hosts[callbackIndex];
        if (hostName)
            hostName = "http://" + hostName;
            */
        var soapUrl = hostName + URL_SOAP_TOOLBOX;
        if (!SOAPClient_cacheWsdl[soapUrl])
            SOAPClient_cacheWsdl[soapUrl] = wsdlCache;
        SOAPClient.invoke(hostName + URL_SOAP_TOOLBOX, "UserLoginChallenge", pl, true, function (Data) {
            callbackIndex++;
            callbackIndex = callBackCount; //This just doesn't work.... so I give up
            if (!wsdlCache)
                wsdlCache = SOAPClient_cacheWsdl[soapUrl];
            //alert("Username: " + UserName + ", " + Data + ", callbackIndex: " + callbackIndex);
            if (callbackIndex == callBackCount)//Has callback and on last callback.
                UserLogin_CallBack(Data);
            else
                doLogin();
        });
    }
    doLogin();
}
 

SpringBoard.Security.prototype.LoadHosts = function (hosts) {
    var callBackCount = 0;
    for (var i = 0; i < SBCultures.length; i++) {
        if (SBCultures[i].HostName != "" || SBCultures[i].Code == board_culture) {
            hosts[hosts.length] = SBCultures[i].HostName;
            if (i > 0 && SBCultures[i].Code == board_culture) { //switch to make sure the current one is first
                hosts[hosts.length - 1] = hosts[0];
                hosts[0] = SBCultures[i].HostName;
            }
            callBackCount++;
        }
    }
    return callBackCount;
}

SpringBoard.Security.prototype.UserLogout = function(UserLogout_CallBack)
{
    var hosts = new Array();
    var callBackCount = this.LoadHosts(hosts);   
    var callbackIndex = 0;
    
    var wsdlCache = null;
    function doLogout() {
        var pl = new SOAPClientParameters();
        var hostName = ""; /* hosts[callbackIndex];
        if (hostName)
            hostName = "http://" + hostName;
            */
        var soapUrl = hostName + URL_SOAP_TOOLBOX;
        if (!SOAPClient_cacheWsdl[soapUrl])
            SOAPClient_cacheWsdl[soapUrl] = wsdlCache;
        SOAPClient.invoke(soapUrl, "UserLogout", pl, true, function (Data) {
            callbackIndex++;
            callbackIndex = callBackCount; //This just doesn't work.... so I give up
            if (!wsdlCache)
                wsdlCache = SOAPClient_cacheWsdl[soapUrl];
               
            //alert("Logout: " + callBackCount + ", " + Data + ", callbackIndex: " + callbackIndex);
            if (callbackIndex == callBackCount)//Has callback and on last callback.
                UserLogout_CallBack(Data);
            else
                doLogout();
        });
    };
    doLogout();
}

SpringBoard.Security.prototype.UserLoginFacebook = function(CallBack)
{
	if (!CallBack)
	{
		CallBack = UserLoginFacebook_CallBack;
	}
	var pl = new SOAPClientParameters();
	//alert(SBPhrases["FACEBOOK_BUNDLEID"]);
	pl.add("bundleId", SBPhrases["FACEBOOK_BUNDLEID"])
	pl.add("SiteKey", board_site_key);
	SOAPClient.invoke(URL_SOAP_TOOLBOX, "UserLoginFacebook", pl, true, CallBack);
}

SpringBoard.Security.prototype.UserLoginFacebook_CallBack = function(data)
{
	if (data.toString().toLowerCase() != trueStr.toLowerCase())
	{
		alert(SBPhrases["FACEBOOK_LOGINFAILED"] + "\r\n" + data.toSource());
	}
	else
	{
		window.location.reload();		
	}
}

SpringBoard.Security.prototype.SendPasswordReminder = function()
{
	var txtEmail = $("#txtEmail");
	var email = txtEmail.val();
	if (email)
	{
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);
		pl.add("Email", email);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "SendPasswordReminder", pl, true, this.SendPasswordReminder_CallBack);
	}
	else
	{
		txtEmail.focus();
		txtEmail.css("border-color", "red");
		txtEmail.click(function() {
			txtEmail.css("border-color", "");
		});
		txtEmail.keypress(function() {
			txtEmail.css("border-color", "");
		});
	}
}

SpringBoard.Security.prototype.SendPasswordReminder_CallBack = function(data)
{
	var response = eval(data);
		
	var divReminder = document.getElementById('divReminder');
	if (divReminder)
	{
		divReminder.innerHTML = response.message;
	}
	else
	{
		var msg = response.message;
		var divOk = document.createElement("div");
		$(divOk).html(msg);
		$(divOk).dialog({
			title: SBPhrases["MAIL_SENT"],
			modal: true,
			buttons: [
			{
				text: "OK",
				click: function() {
					$( this ).dialog( "close" );
				}
			}
			]
		});
	}
}

SpringBoard.Security.prototype.ResetPassword = function()
{
	var newPassword = document.getElementById("txtPassword").value;
	if (newPassword != document.getElementById("txtPasswordConfirm").value)
	{
		alert(SBPhrases["PWD_NOMATCH"]);
	}
	else
	{
		var tokenParam = "token=";
		var token = document.location.toString().substr(document.location.toString().indexOf(tokenParam) + tokenParam.length);
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);
		pl.add("Token", token);
		pl.add("Password", newPassword);
		SOAPClient.invoke(URL_SOAP_TOOLBOX, "ResetPassword", pl, true, this.ResetPassword_CallBack);
	}
}

SpringBoard.Security.prototype.ResetPassword_CallBack = function(data)
{
	var msg = SBPhrases["PWD_CHANGED"];

	var divReminder = document.getElementById('divReminder');
	if (divReminder)
	{
		divReminder.innerHTML = msg;
	}
	else
	{
		var divOk = document.createElement("div");
		$(divOk).html(msg);
		$(divOk).dialog({
			title: SBPhrases["SAVED"],
			modal: true,
			buttons: [
			{
				text: "OK",
				click: function() {
					if (window.ecomUserSettings && window.ecomUserSettings.homePage)
						document.location = window.ecomUserSettings.homePage;
					else
						document.location = "/";
					$( this ).dialog( "close" );
				}
			}
			]
		});
	}

	document.getElementById("txtPassword").value = "";
	document.getElementById("txtPasswordConfirm").value = "";
}

var Security = new SpringBoard.Security();

// FROM: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
function loadjscssfile(filename, filetype)
{
	var isJavascript = (filetype == "js");
	var isCss = (filetype == "css");
	var fileref = null;
	if (isJavascript) //if filename is a external JavaScript file
	{
		fileref = document.createElement('script')
		fileref.setAttribute("type","text/javascript")
		fileref.setAttribute("src", filename)
	}
	else if (isCss) //if filename is an external CSS file
	{ 
		fileref = document.createElement("link")
		fileref.setAttribute("rel", "stylesheet")
		fileref.setAttribute("type", "text/css")
		fileref.setAttribute("href", filename)
	}
	if (fileref)
	{
		var head = document.getElementsByTagName("head")[0];
		var duplicate = false;
		for (var i = 0; i < head.childNodes.length; i++)
		{
			if (head.childNodes[i].tagName == fileref.tagName)
			{
				var regexStr = filename + "$";
				var regex = new RegExp(regexStr);
				if (isJavascript && (head.childNodes[i].src.match(regex)))
				{
					duplicate = true;
				}
				else if (isCss && (head.childNodes[i].href == filename))
				{
					duplicate = true;
				}
			}
		}
		if (/*!isJavascript)*/ !duplicate)
		{		
			head.appendChild(fileref);
		}
	}
}


// FROM: http://www.west-wind.com/weblog/posts/509108.aspx BASED ON:
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
var _tmplCache = {}
this.parseTemplate = function(str, data) {
    /// <summary>
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            //                        str
            //                  .replace(/[\r\t\n]/g, " ")
            //                  .split("<#").join("\t")
            //                  .replace(/((^|#>)[^\t]*)'/g, "$1\r")
            //                  .replace(/\t=(.*?)#>/g, "',$1,'")
            //                  .split("\t").join("');")
            //                  .split("#>").join("p.push('")
            //                  .split("\r").join("\\'") + "');}return p.join('');";

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
}

//http://www.electrictoolbox.com/pad-number-zeroes-javascript/
function PadLeft(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

function FindCultureByCode(Code)
{
	var returnValue;
	for (var i = 0; i < SBCultures.length; i++)
	{
		if (SBCultures[i].Code == Code)
			returnValue = SBCultures[i];
	}
	return returnValue;
};

/********************************
/cms/lib/authentication/Authentication.js
********************************/
/** 
	@class Provides authentication services
  */
AdeoApp.Authentication = function() {
};

AdeoApp.Authentication.prototype.SOAP_URL = "/cms/lib/authentication/Authentication.asmx";

AdeoApp.Authentication.prototype.Login = function(Type, Parameters, Echo, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("Type", Type);
	var params = "";
	if (Parameters)
		params = JSON.stringify(Parameters);
	parameters.add("Parameters", params);
	parameters.add("Echo", Echo);
	SOAPClient.invoke(this.SOAP_URL, "Login", parameters, true, Callback);
}

AdeoApp.Authentication.prototype.IsLoggedIn = function(Type, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("Type", Type);
	SOAPClient.invoke(this.SOAP_URL, "IsLoggedIn", parameters, true, Callback);
}

AdeoApp.Authentication.prototype.AddParameter = function(Name, Value, Parameters) {
	if (!Parameters)
		Parameters = {};
	Parameters[Name] = Value;
	return Parameters;
}

AdeoApp.Authentication.prototype.SetLoggedIn = function(Container, LoginType, LoggedIn)
{
	if (LoggedIn)
	{
		$(".lnkPost").css("display", "");
		$(".lnkPostAs").css("display", "none");
		$(".LoginType").val(LoginType);
	}
	else
	{
		$(".lnkPostAs").css("display", "");
		$(".lnkPost").css("display", "none");
	}
}

AdeoApp.Authentication.prototype.Init = function(Container)
{
	this.SetLoggedIn(false);
	var fancyButtons = $(Container).find(".lnkPostAs, .lnkPost");
	var Me = this;
	var index = 0;
	var checkLogin = function() {
		// Which account is connected?
		var loginType = AdeoApp.Authentication.prototype.AuthenticationTypes[index];
		Authentication.IsLoggedIn(loginType, function(Data, LoginType) {
			if (Data)
				Me.SetLoggedIn(Container, loginType, Data);
			index++;
			if (index < AdeoApp.Authentication.prototype.AuthenticationTypes.length)
				checkLogin();
		});
	};
	checkLogin();	
	//fancyButtons.button();
}

AdeoApp.Authentication.prototype.AuthenticationTypes = new Array(
	/*"FACEBOOK", "TWITTER",*/ "GUEST"
);


AdeoApp.Authentication.prototype.OpenOAuth = function(Response)
{
	//alert(Data)
	//var response = eval(Data);
	alert(Response);
	alert(Response.data);
	window.open(Response.data);
}

AdeoApp.Authentication.prototype.ValidateLogin = function(Dialog, authType)
{
	if (authType == "GUEST")
	{		
		var guestName = $(Dialog).find(".txtGuestName").val();
		var guestEmail = $(Dialog).find(".txtGuestEmail").val();

		if (!guestName)
		{
			$(Dialog).find(".txtGuestName").addClass("missingLoginField");
			return false;
		}
		else if (!AdeoTools.IsEmail(guestEmail))
		{
			$(Dialog).find(".txtGuestName").removeClass("missingLoginField");
			$(Dialog).find(".txtGuestEmail").addClass("missingLoginField");
			return false;
		}
		else
			return true;
	}
	else
		return false;
}

AdeoApp.Authentication.prototype.GatherLoginData = function(Dialog, authType)
{
	var loginParameters = null;
	if (authType == "GUEST")
	{
		var guestName = $(Dialog).find(".txtGuestName").val();
		var guestEmail = $(Dialog).find(".txtGuestEmail").val();
		loginParameters = Authentication.AddParameter("name", guestName);
		Authentication.AddParameter("email", guestEmail, loginParameters);
	}
	return loginParameters;
}

AdeoApp.Authentication.prototype.OpenLogin = function(Sender, Callback)
{
	var Me = this;
	var container = Sender.parentNode.parentNode;
	var dialog = AdeoPlatform.ShowDialog(AdeoPlatform.Resource(SBPhrases["REVIEWS_LOGINTOPOST"]), $(".divCommentLogin")[0].innerHTML, true, function() {

		var loginTabs = $(dialog).find(".divTabs");

		var currentTab = loginTabs.tabs('option', 'active'); // Before Jquery 1.9 used 'selected'

		if (parseFloat($.fn.jquery) < 1.9)
			currentTab = loginTabs.tabs('option', 'selected'); 

		var authType = AdeoApp.Authentication.prototype.AuthenticationTypes[currentTab];

		if (authType == undefined)
			authType = "GUEST";

		$(container).find(".LoginType").val(authType);

		Authentication.IsLoggedIn(authType, function(LoggedIn) {

			var postLogin = function(Data) {				
				Me.SetLoggedIn(container, authType, true);
				Callback(Sender, dialog);
			};
			if (!LoggedIn)
			{
				if (Me.ValidateLogin(dialog, authType))
				{
					var loginParameters = Me.GatherLoginData(dialog, authType);
					var echo = $(dialog).find(".echo" + authType).is(':checked');				
					Authentication.Login(authType, loginParameters, echo, postLogin);
				}
				else
				{
					$(loginTabs.find(".ui-tabs-panel")[currentTab]).find(".lnkLogin").addClass("lnkLoginError");					
				}
			}
			else
			{
				postLogin();
			}
		});
	}, null, true);
	$(dialog).find(".divTabs").tabs({
		fx: { opacity: 'toggle' } 
	});
	$(dialog).addClass("divLogin");
}

AdeoApp.Authentication.prototype.CompleteLogin = function()
{
	var postloginParameter = "&dopostlogin=true";
	var divDialog = $(window.opener.document.documentElement).find(".divLogin");
	if (document.location.toString().indexOf(postloginParameter) > 0)
	{
		divDialog.removeClass("divLogin");
		divDialog.parents(".ui-dialog").find(".btnOk").click();
		window.close();
	}
	else
	{
		var paramString = "";
		var echos = divDialog.find('input[class^="echo"]').each(function() {
			paramString += "&" + this.className + "=" + this.checked;
		});
		document.location = window.location.href.toString().replace("#", "?") + postloginParameter + paramString;
	}
}


var Authentication = new AdeoApp.Authentication();;

/********************************
/cms/app/mediaButton/mediaButton.js
********************************/
AdeoApp.MediaButton = function() {};

AdeoApp.MediaButton.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/MediaButton/MediaButtonAdmin.aspx",
	"Name": "Media Button",
	"ModuleName": "MediaButton"
});

AdeoApp.MediaButton.prototype.ID = "9da68e11-1399-429d-968f-d52ecba75c87";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.MediaButton.prototype.ID, function() {
		return new AdeoApp.MediaButton();
	});
});

AdeoApp.MediaButton.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {

}


AdeoApp.MediaButton.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	Data["resizeOption"] = "1";
	if(!$(Container).find(".rdoStretch")[0].checked)
		Data["resizeOption"] = "2";
	return Data;
}


var MediaButton = new AdeoApp.MediaButton();;

/********************************
/cms/app/mediaButton/jQuery-File-Upload/js/jquery.fileupload.js
********************************/
/*
 * jQuery File Upload Plugin 5.19.8
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, File, Blob, FormData, location */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery.ui.widget'
        ], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // The FileReader API is not actually used, but works as feature detection,
    // as e.g. Safari supports XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads:
    $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default the complete document.
            // Set to null to disable paste support:
            pasteZone: $(document),
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uplaods, else
            // once for each file selection.
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows to override plugin options as well as define ajax settings.
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {
                data.submit();
            },

            // Other callbacks:
            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);
            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);
            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);
            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);
            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);
            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);
            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);
            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false
        },

        // A list of options that require a refresh after assigning a new value:
        _refreshOptionsList: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _BitrateTimer: function () {
            this.timestamp = +(new Date());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if (typeof options.formData === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if (options.formData) {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = +(new Date()),
                    total,
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                total = data.total || this._getTotal(data.files);
                loaded = parseInt(
                    e.loaded / e.total * (data.chunkSize || total),
                    10
                ) + (data.uploadedBytes || 0);
                this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
                data.lengthComputable = true;
                data.loaded = loaded;
                data.total = total;
                data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger('progress', e, data);
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger('progressall', e, {
                    lengthComputable: true,
                    loaded: this._loaded,
                    total: this._total,
                    bitrate: this._bitrateTimer.getBitrate(
                        now,
                        this._loaded,
                        data.bitrateInterval
                    )
                });
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _initXHRData: function (options) {
            var formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = options.paramName[0];
            options.headers = options.headers || {};
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
                options.contentType = file.type;
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: options.paramName[index] || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (options.formData instanceof FormData) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        options.headers['Content-Disposition'] = 'attachment; filename="' +
                            encodeURI(file.name) + '"';
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // Files are also Blob instances, but some browsers
                            // (Firefox 3.6) support the File API but not Blobs.
                            // This check allows the tests to run with
                            // dummy objects:
                            if ((window.Blob && file instanceof Blob) ||
                                    (window.File && file instanceof File)) {
                                formData.append(
                                    options.paramName[index] || paramName,
                                    file,
                                    file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && $('<a></a>').prop('href', options.url)
                    .prop('host') !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options, 'iframe');
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type || options.form.prop('method') || '')
                .toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes = options.uploadedBytes || 0,
                mcs = options.maxChunkSize || fs,
                slice = file.slice || file.webkitSlice || file.mozSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = 'Uploaded bytes exceed file size';
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function (i) {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options);
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if upload is done and
                        // no progress event has been invoked for this chunk:
                        if (!o.loaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
            }
            this._active += 1;
            // Initialize the global progress values:
            this._loaded += data.uploadedBytes || 0;
            this._total += this._getTotal(data.files);
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            if (!this._isXHRUpload(options)) {
                // Create a progress event for each iframe load:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: 1,
                    total: 1
                }), options);
            }
            options.result = result;
            options.textStatus = textStatus;
            options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            options.jqXHR = jqXHR;
            options.textStatus = textStatus;
            options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._loaded -= options.loaded || options.uploadedBytes || 0;
                this._total -= options.total || this._getTotal(options.files);
            }
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            this._active -= 1;
            options.textStatus = textStatus;
            if (jqXHRorError && jqXHRorError.always) {
                options.jqXHR = jqXHRorError;
                options.result = jqXHRorResult;
            } else {
                options.jqXHR = jqXHRorResult;
                options.errorThrown = jqXHRorError;
            }
            this._trigger('always', null, options);
            if (this._active === 0) {
                // The stop callback is triggered when all uploads have
                // been completed, equivalent to the global ajaxStop event:
                this._trigger('stop');
                // Reset the global progress values:
                this._loaded = this._total = 0;
                this._bitrateTimer = null;
            }
        },

        _onSend: function (e, data) {
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger('send', e, options) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._sending -= 1;
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift(),
                                isPending;
                            while (nextSlot) {
                                // jQuery 1.6 doesn't provide .state(),
                                // while jQuery 1.8+ removed .isRejected():
                                isPending = nextSlot.state ?
                                        nextSlot.state() === 'pending' :
                                        !nextSlot.isRejected();
                                if (isPending) {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.pipe(send);
                } else {
                    pipe = (this._sequence = this._sequence.pipe(send, send));
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                limit = options.limitMultiFileUploads,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i;
            if (!(options.singleFileUploads || limit) ||
                    !this._isXHRUpload(options)) {
                fileSet = [data.files];
                paramNameSet = [paramName];
            } else if (!options.singleFileUploads && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < data.files.length; i += limit) {
                    fileSet.push(data.files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = data.files;
            $.each(fileSet || data.files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                newData.submit = function () {
                    newData.jqXHR = this.jqXHR =
                        (that._trigger('submit', e, this) !== false) &&
                        that._onSend(e, this);
                    return this.jqXHR;
                };
                result = that._trigger('add', e, newData);
                return result;
            });
            return result;
        },

        _replaceFileInput: function (input) {
            var inputClone = input.clone(true);
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                dirReader;
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                dirReader.readEntries(function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                }, errorHandler);
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data.fileInput);
                }
                if (that._trigger('change', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var cbd = e.originalEvent.clipboardData,
                items = (cbd && cbd.items) || [],
                data = {files: []};
            $.each(items, function (index, item) {
                var file = item.getAsFile && item.getAsFile();
                if (file) {
                    data.files.push(file);
                }
            });
            if (this._trigger('paste', e, data) === false ||
                    this._onAdd(e, data) === false) {
                return false;
            }
        },

        _onDrop: function (e) {
            var that = this,
                dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
            }
            this._getDroppedFiles(dataTransfer).always(function (files) {
                data.files = files;
                if (that._trigger('drop', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onDragOver: function (e) {
            var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
            if (this._trigger('dragover', e) === false) {
                return false;
            }
            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1) {
                dataTransfer.dropEffect = 'copy';
                e.preventDefault();
            }
        },

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            this._on(this.options.fileInput, {
                change: this._onChange
            });
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _setOption: function (key, value) {
            var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
            if (refresh) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (refresh) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _create: function () {
            var options = this.options;
            // Initialize options set via HTML5 data-attributes:
            $.extend(options, $(this.element[0].cloneNode(false)).data());
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = this._loaded = this._total = 0;
            this._initEventHandlers();
        },

        _destroy: function () {
            this._destroyEventHandlers();
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data).then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
;

/********************************
/cms/app/mediaButton/jQuery-File-Upload/js/jquery.fileupload-fp.js
********************************/
/*
 * jQuery File Upload File Processing Plugin 1.2.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2012, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'load-image',
            'canvas-to-blob',
            './jquery.fileupload'
        ], factory);
    } else {
        // Browser globals:
        factory(
            window.jQuery,
            window.loadImage
        );
    }
}(function ($, loadImage) {
    'use strict';

    // The File Upload FP version extends the fileupload widget
    // with file processing functionality:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // The list of file processing actions:
            process: [
            /*
                {
                    action: 'load',
                    fileTypes: /^image\/(gif|jpeg|png)$/,
                    maxFileSize: 20000000 // 20MB
                },
                {
                    action: 'resize',
                    maxWidth: 1920,
                    maxHeight: 1200,
                    minWidth: 800,
                    minHeight: 600
                },
                {
                    action: 'save'
                }
            */
            ],

            // The add callback is invoked as soon as files are added to the
            // fileupload widget (via file input selection, drag & drop or add
            // API call). See the basic file upload widget for more information:
            add: function (e, data) {
                $(this).fileupload('process', data).done(function () {
                    data.submit();
                });
            }
        },

        processActions: {
            // Loads the image given via data.files and data.index
            // as img element if the browser supports canvas.
            // Accepts the options fileTypes (regular expression)
            // and maxFileSize (integer) to limit the files to load:
            load: function (data, options) {
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (window.HTMLCanvasElement &&
                        window.HTMLCanvasElement.prototype.toBlob &&
                        ($.type(options.maxFileSize) !== 'number' ||
                            file.size < options.maxFileSize) &&
                        (!options.fileTypes ||
                            options.fileTypes.test(file.type))) {
                    loadImage(
                        file,
                        function (img) {
                            if (!img.src) {
                                return dfd.rejectWith(that, [data]);
                            }
                            data.img = img;
                            dfd.resolveWith(that, [data]);
                        }
                    );
                } else {
                    dfd.rejectWith(that, [data]);
                }
                return dfd.promise();
            },
            // Resizes the image given as data.img and updates
            // data.canvas with the resized image as canvas element.
            // Accepts the options maxWidth, maxHeight, minWidth and
            // minHeight to scale the given image:
            resize: function (data, options) {
                var img = data.img,
                    canvas;
                options = $.extend({canvas: true}, options);
                if (img) {
                    canvas = loadImage.scale(img, options);
                    if (canvas.width !== img.width ||
                            canvas.height !== img.height) {
                        data.canvas = canvas;
                    }
                }
                return data;
            },
            // Saves the processed image given as data.canvas
            // inplace at data.index of data.files:
            save: function (data, options) {
                // Do nothing if no processing has happened:
                if (!data.canvas) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    name = file.name,
                    dfd = $.Deferred(),
                    callback = function (blob) {
                        if (!blob.name) {
                            if (file.type === blob.type) {
                                blob.name = file.name;
                            } else if (file.name) {
                                blob.name = file.name.replace(
                                    /\..+$/,
                                    '.' + blob.type.substr(6)
                                );
                            }
                        }
                        // Store the created blob at the position
                        // of the original file in the files list:
                        data.files[data.index] = blob;
                        dfd.resolveWith(that, [data]);
                    };
                // Use canvas.mozGetAsFile directly, to retain the filename, as
                // Gecko doesn't support the filename option for FormData.append:
                if (data.canvas.mozGetAsFile) {
                    callback(data.canvas.mozGetAsFile(
                        (/^image\/(jpeg|png)$/.test(file.type) && name) ||
                            ((name && name.replace(/\..+$/, '')) ||
                                'blob') + '.png',
                        file.type
                    ));
                } else {
                    data.canvas.toBlob(callback, file.type);
                }
                return dfd.promise();
            }
        },

        // Resizes the file at the given index and stores the created blob at
        // the original position of the files list, returns a Promise object:
        _processFile: function (files, index, options) {
            var that = this,
                dfd = $.Deferred().resolveWith(that, [{
                    files: files,
                    index: index
                }]),
                chain = dfd.promise();
            that._processing += 1;
            $.each(options.process, function (i, settings) {
                chain = chain.pipe(function (data) {
                    return that.processActions[settings.action]
                        .call(this, data, settings);
                });
            });
            chain.always(function () {
                that._processing -= 1;
                if (that._processing === 0) {
                    that.element
                        .removeClass('fileupload-processing');
                }
            });
            if (that._processing === 1) {
                that.element.addClass('fileupload-processing');
            }
            return chain;
        },

        // Processes the files given as files property of the data parameter,
        // returns a Promise object that allows to bind a done handler, which
        // will be invoked after processing all files (inplace) is done:
        process: function (data) {
            var that = this,
                options = $.extend({}, this.options, data);
            if (options.process && options.process.length &&
                    this._isXHRUpload(options)) {
                $.each(data.files, function (index, file) {
                    that._processingQueue = that._processingQueue.pipe(
                        function () {
                            var dfd = $.Deferred();
                            that._processFile(data.files, index, options)
                                .always(function () {
                                    dfd.resolveWith(that);
                                });
                            return dfd.promise();
                        }
                    );
                });
            }
            return this._processingQueue;
        },

        _create: function () {
            this._super();
            this._processing = 0;
            this._processingQueue = $.Deferred().resolveWith(this)
                .promise();
        }

    });

}));
;

/********************************
/cms/app/mediaButton/jQuery-File-Upload/js/jquery.fileupload-ui.js
********************************/
/*
 * jQuery File Upload User Interface Plugin 7.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, URL, webkitURL, FileReader */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'tmpl',
            'load-image',
            './jquery.fileupload-fp'
        ], factory);
    } else {
        // Browser globals:
        factory(
            window.jQuery,
            window.tmpl,
            window.loadImage
        );
    }
}(function ($, tmpl, loadImage) {
    'use strict';

    // The UI version extends the file upload widget
    // and adds complete user interface interaction:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // By default, files added to the widget are uploaded as soon
            // as the user clicks on the start buttons. To enable automatic
            // uploads, set the following option to true:
            autoUpload: false,
            // The following option limits the number of files that are
            // allowed to be uploaded using this widget:
            maxNumberOfFiles: undefined,
            // The maximum allowed file size:
            maxFileSize: undefined,
            // The minimum allowed file size:
            minFileSize: undefined,
            // The regular expression for allowed file types, matches
            // against either file type or file name:
            acceptFileTypes:  /.+$/i,
            // The regular expression to define for which files a preview
            // image is shown, matched against the file type:
            previewSourceFileTypes: /^image\/(gif|jpeg|png)$/,
            // The maximum file size of images that are to be displayed as preview:
            previewSourceMaxFileSize: 5000000, // 5MB
            // The maximum width of the preview images:
            previewMaxWidth: 80,
            // The maximum height of the preview images:
            previewMaxHeight: 80,
            // By default, preview images are displayed as canvas elements
            // if supported by the browser. Set the following option to false
            // to always display preview images as img elements:
            previewAsCanvas: true,
            // The ID of the upload template:
            uploadTemplateId: 'template-upload',
            // The ID of the download template:
            downloadTemplateId: 'template-download',
            // The container for the list of files. If undefined, it is set to
            // an element with class "files" inside of the widget element:
            filesContainer: undefined,
            // By default, files are appended to the files container.
            // Set the following option to true, to prepend files instead:
            prependFiles: false,
            // The expected data type of the upload response, sets the dataType
            // option of the $.ajax upload requests:
            dataType: 'json',

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop or add API call).
            // See the basic file upload widget for more information:
            add: function (e, data) {
                var that = $(this).data('fileupload'),
                    options = that.options,
                    files = data.files;
                $(this).fileupload('process', data).done(function () {
                    that._adjustMaxNumberOfFiles(-files.length);
                    data.maxNumberOfFilesAdjusted = true;
                    data.files.valid = data.isValidated = that._validate(files);
                    data.context = that._renderUpload(files).data('data', data);
                    options.filesContainer[
                        options.prependFiles ? 'prepend' : 'append'
                    ](data.context);
                    that._renderPreviews(data);
                    that._forceReflow(data.context);
                    that._transition(data.context).done(
                        function () {
                            if ((that._trigger('added', e, data) !== false) &&
                                    (options.autoUpload || data.autoUpload) &&
                                    data.autoUpload !== false && data.isValidated) {
                                data.submit();
                            }
                        }
                    );
                });
            },
            // Callback for the start of each file upload request:
            send: function (e, data) {
                var that = $(this).data('fileupload');
                if (!data.isValidated) {
                    if (!data.maxNumberOfFilesAdjusted) {
                        that._adjustMaxNumberOfFiles(-data.files.length);
                        data.maxNumberOfFilesAdjusted = true;
                    }
                    if (!that._validate(data.files)) {
                        return false;
                    }
                }
                if (data.context && data.dataType &&
                        data.dataType.substr(0, 6) === 'iframe') {
                    // Iframe Transport does not support progress events.
                    // In lack of an indeterminate progress bar, we set
                    // the progress to 100%, showing the full animated bar:
                    data.context
                        .find('.progress').addClass(
                            !$.support.transition && 'progress-animated'
                        )
                        .attr('aria-valuenow', 100)
                        .find('.bar').css(
                            'width',
                            '100%'
                        );
                }
                return that._trigger('sent', e, data);
            },
            // Callback for successful uploads:
            done: function (e, data) {
                var that = $(this).data('fileupload'),
                    files = that._getFilesFromResponse(data),
                    template,
                    deferred;
                if (data.context) {
                    data.context.each(function (index) {
                        var file = files[index] ||
                                {error: 'Empty file upload result'},
                            deferred = that._addFinishedDeferreds();
                        if (file.error) {
                            that._adjustMaxNumberOfFiles(1);
                        }
                        that._transition($(this)).done(
                            function () {
                                var node = $(this);
                                template = that._renderDownload([file])
                                    .replaceAll(node);
                                that._forceReflow(template);
                                that._transition(template).done(
                                    function () {
                                        data.context = $(this);
                                        that._trigger('completed', e, data);
                                        that._trigger('finished', e, data);
                                        deferred.resolve();
                                    }
                                );
                            }
                        );
                    });
                } else {
                    if (files.length) {
                        $.each(files, function (index, file) {
                            if (data.maxNumberOfFilesAdjusted && file.error) {
                                that._adjustMaxNumberOfFiles(1);
                            } else if (!data.maxNumberOfFilesAdjusted &&
                                    !file.error) {
                                that._adjustMaxNumberOfFiles(-1);
                            }
                        });
                        data.maxNumberOfFilesAdjusted = true;
                    }
                    template = that._renderDownload(files)
                        .appendTo(that.options.filesContainer);
                    that._forceReflow(template);
                    deferred = that._addFinishedDeferreds();
                    that._transition(template).done(
                        function () {
                            data.context = $(this);
                            that._trigger('completed', e, data);
                            that._trigger('finished', e, data);
                            deferred.resolve();
                        }
                    );
                }
            },
            // Callback for failed (abort or error) uploads:
            fail: function (e, data) {
                var that = $(this).data('fileupload'),
                    template,
                    deferred;
                if (data.maxNumberOfFilesAdjusted) {
                    that._adjustMaxNumberOfFiles(data.files.length);
                }
                if (data.context) {
                    data.context.each(function (index) {
                        if (data.errorThrown !== 'abort') {
                            var file = data.files[index];
                            file.error = file.error || data.errorThrown ||
                                true;
                            deferred = that._addFinishedDeferreds();
                            that._transition($(this)).done(
                                function () {
                                    var node = $(this);
                                    template = that._renderDownload([file])
                                        .replaceAll(node);
                                    that._forceReflow(template);
                                    that._transition(template).done(
                                        function () {
                                            data.context = $(this);
                                            that._trigger('failed', e, data);
                                            that._trigger('finished', e, data);
                                            deferred.resolve();
                                        }
                                    );
                                }
                            );
                        } else {
                            deferred = that._addFinishedDeferreds();
                            that._transition($(this)).done(
                                function () {
                                    $(this).remove();
                                    that._trigger('failed', e, data);
                                    that._trigger('finished', e, data);
                                    deferred.resolve();
                                }
                            );
                        }
                    });
                } else if (data.errorThrown !== 'abort') {
                    data.context = that._renderUpload(data.files)
                        .appendTo(that.options.filesContainer)
                        .data('data', data);
                    that._forceReflow(data.context);
                    deferred = that._addFinishedDeferreds();
                    that._transition(data.context).done(
                        function () {
                            data.context = $(this);
                            that._trigger('failed', e, data);
                            that._trigger('finished', e, data);
                            deferred.resolve();
                        }
                    );
                } else {
                    that._trigger('failed', e, data);
                    that._trigger('finished', e, data);
                    that._addFinishedDeferreds().resolve();
                }
            },
            // Callback for upload progress events:
            progress: function (e, data) {
                if (data.context) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    data.context.find('.progress')
                        .attr('aria-valuenow', progress)
                        .find('.bar').css(
                            'width',
                            progress + '%'
                        );
                }
            },
            // Callback for global upload progress events:
            progressall: function (e, data) {
                var $this = $(this),
                    progress = parseInt(data.loaded / data.total * 100, 10),
                    globalProgressNode = $this.find('.fileupload-progress'),
                    extendedProgressNode = globalProgressNode
                        .find('.progress-extended');
                if (extendedProgressNode.length) {
                    extendedProgressNode.html(
                        $this.data('fileupload')._renderExtendedProgress(data)
                    );
                }
                globalProgressNode
                    .find('.progress')
                    .attr('aria-valuenow', progress)
                    .find('.bar').css(
                        'width',
                        progress + '%'
                    );
            },
            // Callback for uploads start, equivalent to the global ajaxStart event:
            start: function (e) {
                var that = $(this).data('fileupload');
                that._resetFinishedDeferreds();
                that._transition($(this).find('.fileupload-progress')).done(
                    function () {
                        that._trigger('started', e);
                    }
                );
            },
            // Callback for uploads stop, equivalent to the global ajaxStop event:
            stop: function (e) {
                var that = $(this).data('fileupload'),
                    deferred = that._addFinishedDeferreds();
                $.when.apply($, that._getFinishedDeferreds())
                    .done(function () {
                        that._trigger('stopped', e);
                    });
                that._transition($(this).find('.fileupload-progress')).done(
                    function () {
                        $(this).find('.progress')
                            .attr('aria-valuenow', '0')
                            .find('.bar').css('width', '0%');
                        $(this).find('.progress-extended').html('&nbsp;');
                        deferred.resolve();
                    }
                );
            },
            // Callback for file deletion:
            destroy: function (e, data) {
                var that = $(this).data('fileupload');
                if (data.url) {
                    $.ajax(data);
                    that._adjustMaxNumberOfFiles(1);
                }
                that._transition(data.context).done(
                    function () {
                        $(this).remove();
                        that._trigger('destroyed', e, data);
                    }
                );
            }
        },

        _resetFinishedDeferreds: function () {
            this._finishedUploads = [];
        },

        _addFinishedDeferreds: function (deferred) {
            if (!deferred) {
                deferred = $.Deferred();
            }
            this._finishedUploads.push(deferred);
            return deferred;
        },

        _getFinishedDeferreds: function () {
            return this._finishedUploads;
        },

        _getFilesFromResponse: function (data) {
            if (data.result && $.isArray(data.result.files)) {
                return data.result.files;
            }
            return [];
        },

        // Link handler, that allows to download files
        // by drag & drop of the links to the desktop:
        _enableDragToDesktop: function () {
            var link = $(this),
                url = link.prop('href'),
                name = link.prop('download'),
                type = 'application/octet-stream';
            link.bind('dragstart', function (e) {
                try {
                    e.originalEvent.dataTransfer.setData(
                        'DownloadURL',
                        [type, name, url].join(':')
                    );
                } catch (err) {}
            });
        },

        _adjustMaxNumberOfFiles: function (operand) {
            if (typeof this.options.maxNumberOfFiles === 'number') {
                this.options.maxNumberOfFiles += operand;
                if (this.options.maxNumberOfFiles < 1) {
                    this._disableFileInputButton();
                } else {
                    this._enableFileInputButton();
                }
            }
        },

        _formatFileSize: function (bytes) {
            if (typeof bytes !== 'number') {
                return '';
            }
            if (bytes >= 1000000000) {
                return (bytes / 1000000000).toFixed(2) + ' GB';
            }
            if (bytes >= 1000000) {
                return (bytes / 1000000).toFixed(2) + ' MB';
            }
            return (bytes / 1000).toFixed(2) + ' KB';
        },

        _formatBitrate: function (bits) {
            if (typeof bits !== 'number') {
                return '';
            }
            if (bits >= 1000000000) {
                return (bits / 1000000000).toFixed(2) + ' Gbit/s';
            }
            if (bits >= 1000000) {
                return (bits / 1000000).toFixed(2) + ' Mbit/s';
            }
            if (bits >= 1000) {
                return (bits / 1000).toFixed(2) + ' kbit/s';
            }
            return bits.toFixed(2) + ' bit/s';
        },

        _formatTime: function (seconds) {
            var date = new Date(seconds * 1000),
                days = parseInt(seconds / 86400, 10);
            days = days ? days + 'd ' : '';
            return days +
                ('0' + date.getUTCHours()).slice(-2) + ':' +
                ('0' + date.getUTCMinutes()).slice(-2) + ':' +
                ('0' + date.getUTCSeconds()).slice(-2);
        },

        _formatPercentage: function (floatValue) {
            return (floatValue * 100).toFixed(2) + ' %';
        },

        _renderExtendedProgress: function (data) {
            return this._formatBitrate(data.bitrate) + ' | ' +
                this._formatTime(
                    (data.total - data.loaded) * 8 / data.bitrate
                ) + ' | ' +
                this._formatPercentage(
                    data.loaded / data.total
                ) + ' | ' +
                this._formatFileSize(data.loaded) + ' / ' +
                this._formatFileSize(data.total);
        },

        _hasError: function (file) {
            if (file.error) {
                return file.error;
            }
            // The number of added files is subtracted from
            // maxNumberOfFiles before validation, so we check if
            // maxNumberOfFiles is below 0 (instead of below 1):
            if (this.options.maxNumberOfFiles < 0) {
                return 'Maximum number of files exceeded';
            }
            // Files are accepted if either the file type or the file name
            // matches against the acceptFileTypes regular expression, as
            // only browsers with support for the File API report the type:
            if (!(this.options.acceptFileTypes.test(file.type) ||
                    this.options.acceptFileTypes.test(file.name))) {
                return 'Filetype not allowed';
            }
            if (this.options.maxFileSize &&
                    file.size > this.options.maxFileSize) {
                return 'File is too big';
            }
            if (typeof file.size === 'number' &&
                    file.size < this.options.minFileSize) {
                return 'File is too small';
            }
            return null;
        },

        _validate: function (files) {
            var that = this,
                valid = !!files.length;
            $.each(files, function (index, file) {
                file.error = that._hasError(file);
                if (file.error) {
                    valid = false;
                }
            });
            return valid;
        },

        _renderTemplate: function (func, files) {
            if (!func) {
                return $();
            }
            var result = func({
                files: files,
                formatFileSize: this._formatFileSize,
                options: this.options
            });
            if (result instanceof $) {
                return result;
            }
            return $(this.options.templatesContainer).html(result).children();
        },

        _renderPreview: function (file, node) {
            var that = this,
                options = this.options,
                dfd = $.Deferred();
            return ((loadImage && loadImage(
                file,
                function (img) {
                    node.append(img);
                    that._forceReflow(node);
                    that._transition(node).done(function () {
                        dfd.resolveWith(node);
                    });
                    if (!$.contains(that.document[0].body, node[0])) {
                        // If the element is not part of the DOM,
                        // transition events are not triggered,
                        // so we have to resolve manually:
                        dfd.resolveWith(node);
                    }
                },
                {
                    maxWidth: options.previewMaxWidth,
                    maxHeight: options.previewMaxHeight,
                    canvas: options.previewAsCanvas
                }
            )) || dfd.resolveWith(node)) && dfd;
        },

        _renderPreviews: function (data) {
            var that = this,
                options = this.options;
            data.context.find('.preview span').each(function (index, element) {
                var file = data.files[index];
                if (options.previewSourceFileTypes.test(file.type) &&
                        ($.type(options.previewSourceMaxFileSize) !== 'number' ||
                        file.size < options.previewSourceMaxFileSize)) {
                    that._processingQueue = that._processingQueue.pipe(function () {
                        var dfd = $.Deferred(),
                            ev = $.Event('previewdone', {
                                target: element
                            });
                        that._renderPreview(file, $(element)).done(
                            function () {
                                that._trigger(ev.type, ev, data);
                                dfd.resolveWith(that);
                            }
                        );
                        return dfd.promise();
                    });
                }
            });
            return this._processingQueue;
        },

        _renderUpload: function (files) {
            return this._renderTemplate(
                this.options.uploadTemplate,
                files
            );
        },

        _renderDownload: function (files) {
            return this._renderTemplate(
                this.options.downloadTemplate,
                files
            ).find('a[download]').each(this._enableDragToDesktop).end();
        },

        _startHandler: function (e) {
            e.preventDefault();
            var button = $(e.currentTarget),
                template = button.closest('.template-upload'),
                data = template.data('data');
            if (data && data.submit && !data.jqXHR && data.submit()) {
                button.prop('disabled', true);
            }
        },

        _cancelHandler: function (e) {
            e.preventDefault();
            var template = $(e.currentTarget).closest('.template-upload'),
                data = template.data('data') || {};
            if (!data.jqXHR) {
                data.errorThrown = 'abort';
                this._trigger('fail', e, data);
            } else {
                data.jqXHR.abort();
            }
        },

        _deleteHandler: function (e) {
            e.preventDefault();
            var button = $(e.currentTarget);
            this._trigger('destroy', e, $.extend({
                context: button.closest('.template-download'),
                type: 'DELETE',
                dataType: this.options.dataType
            }, button.data()));
        },

        _forceReflow: function (node) {
            return $.support.transition && node.length &&
                node[0].offsetWidth;
        },

        _transition: function (node) {
            var dfd = $.Deferred();
            if ($.support.transition && node.hasClass('fade')) {
                node.bind(
                    $.support.transition.end,
                    function (e) {
                        // Make sure we don't respond to other transitions events
                        // in the container element, e.g. from button elements:
                        if (e.target === node[0]) {
                            node.unbind($.support.transition.end);
                            dfd.resolveWith(node);
                        }
                    }
                ).toggleClass('in');
            } else {
                node.toggleClass('in');
                dfd.resolveWith(node);
            }
            return dfd;
        },

        _initButtonBarEventHandlers: function () {
            var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
                filesList = this.options.filesContainer;
            this._on(fileUploadButtonBar.find('.start'), {
                click: function (e) {
                    e.preventDefault();
                    filesList.find('.start button').click();
                }
            });
            this._on(fileUploadButtonBar.find('.cancel'), {
                click: function (e) {
                    e.preventDefault();
                    filesList.find('.cancel button').click();
                }
            });
            this._on(fileUploadButtonBar.find('.delete'), {
                click: function (e) {
                    e.preventDefault();
                    filesList.find('.delete input:checked')
                        .siblings('button').click();
                    fileUploadButtonBar.find('.toggle')
                        .prop('checked', false);
                }
            });
            this._on(fileUploadButtonBar.find('.toggle'), {
                change: function (e) {
                    filesList.find('.delete input').prop(
                        'checked',
                        $(e.currentTarget).is(':checked')
                    );
                }
            });
        },

        _destroyButtonBarEventHandlers: function () {
            this._off(
                this.element.find('.fileupload-buttonbar button'),
                'click'
            );
            this._off(
                this.element.find('.fileupload-buttonbar .toggle'),
                'change.'
            );
        },

        _initEventHandlers: function () {
            this._super();
            this._on(this.options.filesContainer, {
                'click .start button': this._startHandler,
                'click .cancel button': this._cancelHandler,
                'click .delete button': this._deleteHandler
            });
            this._initButtonBarEventHandlers();
        },

        _destroyEventHandlers: function () {
            this._destroyButtonBarEventHandlers();
            this._off(this.options.filesContainer, 'click');
            this._super();
        },

        _enableFileInputButton: function () {
            this.element.find('.fileinput-button input')
                .prop('disabled', false)
                .parent().removeClass('disabled');
        },

        _disableFileInputButton: function () {
            this.element.find('.fileinput-button input')
                .prop('disabled', true)
                .parent().addClass('disabled');
        },

        _initTemplates: function () {
            var options = this.options;
            options.templatesContainer = this.document[0].createElement(
                options.filesContainer.prop('nodeName')
            );
            if (tmpl) {
                if (options.uploadTemplateId) {
                    options.uploadTemplate = tmpl(options.uploadTemplateId);
                }
                if (options.downloadTemplateId) {
                    options.downloadTemplate = tmpl(options.downloadTemplateId);
                }
            }
        },

        _initFilesContainer: function () {
            var options = this.options;
            if (options.filesContainer === undefined) {
                options.filesContainer = this.element.find('.files');
            } else if (!(options.filesContainer instanceof $)) {
                options.filesContainer = $(options.filesContainer);
            }
        },

        _stringToRegExp: function (str) {
            var parts = str.split('/'),
                modifiers = parts.pop();
            parts.shift();
            return new RegExp(parts.join('/'), modifiers);
        },

        _initRegExpOptions: function () {
            var options = this.options;
            if ($.type(options.acceptFileTypes) === 'string') {
                options.acceptFileTypes = this._stringToRegExp(
                    options.acceptFileTypes
                );
            }
            if ($.type(options.previewSourceFileTypes) === 'string') {
                options.previewSourceFileTypes = this._stringToRegExp(
                    options.previewSourceFileTypes
                );
            }
        },

        _initSpecialOptions: function () {
            this._super();
            this._initFilesContainer();
            this._initTemplates();
            this._initRegExpOptions();
        },

        _setOption: function (key, value) {
            this._super(key, value);
            if (key === 'maxNumberOfFiles') {
                this._adjustMaxNumberOfFiles(0);
            }
        },

        _create: function () {
            this._super();
            this._refreshOptionsList.push(
                'filesContainer',
                'uploadTemplateId',
                'downloadTemplateId'
            );
            if (!this._processingQueue) {
                this._processingQueue = $.Deferred().resolveWith(this).promise();
                this.process = function () {
                    return this._processingQueue;
                };
            }
            this._resetFinishedDeferreds();
        },

        enable: function () {
            var wasDisabled = false;
            if (this.options.disabled) {
                wasDisabled = true;
            }
            this._super();
            if (wasDisabled) {
                this.element.find('input, button').prop('disabled', false);
                this._enableFileInputButton();
            }
        },

        disable: function () {
            if (!this.options.disabled) {
                this.element.find('input, button').prop('disabled', true);
                this._disableFileInputButton();
            }
            this._super();
        }

    });

}));
;

/********************************
/cms/app/textBlock/textBlock.js
********************************/
/** 
	@class Provides a second HTML text block
	@augments AdeoApp.AjaxApp
  */
AdeoApp.TextBlock = function() {};

AdeoApp.TextBlock.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/textBlock/textBlockAdmin.aspx",
	"Name": "Text block",
	"ModuleName": "TextBlock"
});

AdeoApp.TextBlock.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.MakeEditor(Container, LayoutGuid);
}

AdeoApp.TextBlock.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	Data["html"] = CKEDITOR.instances[LayoutGuid].getData();	
	
	return Data;
}

/**
	@description Creates an HTML editor
	@param {HTMLElement} Container DIV that contains a textarea
	@param {String} LayoutGuid A unique ID for the editor (typically the layout item GUID)
*/
AdeoApp.TextBlock.prototype.MakeEditor = function(Container, LayoutGuid)
{
	var initEditor = function() 
	{
		var textarea = $(Container).find("textarea")[0];
		textarea.id = LayoutGuid;
		var instance = CKEDITOR.instances[textarea.id];
	    if(instance)
	        CKEDITOR.remove(instance);
		CKEDITOR.replace(textarea);
	}
	
	if (!window.CKEDITOR)
	{
		AdeoPlatform.LoadResource("/cms/resources/ckeditor/ckeditor.js", AdeoPlatform.ResourceTypes.JavaScript);
		setTimeout(initEditor, 1000);
	}
	else
		initEditor();
}

$(document).ready(function() {
	AdeoPlatform.Factory.Register("213ed0bc-2da7-47c0-9f9d-4ba2cf18f4a6", function() {
		return new AdeoApp.TextBlock();
	});
});;

/********************************
/cms/app/template/template.js
********************************/
AdeoApp.Template = function() {};

AdeoApp.Template.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/template/templateAdmin.aspx",
	"Name": "Template",
	"ModuleName": "Template"
});

AdeoApp.Template.prototype.ID = "142fe8ab-ff71-4466-9cad-e6640eaee00b";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Template.prototype.ID, function() {
		return new AdeoApp.Template();
	});
});

AdeoApp.Template.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {

}

AdeoApp.Template.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	
}


AdeoApp.Template.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	// Data["customOption"] = "1";
	return Data;
}


var Template = new AdeoApp.Template();;

/********************************
/cms/app/comments/comments.js
********************************/
AdeoApp.Comments = function() {};

/** 
	@class Adds a comment section.
	@augments AdeoApp.AjaxApp
  */
AdeoApp.Comments.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/comments/commentsAdmin.aspx",
	"Name": "Comments",
	"ModuleName": "comments"
});

AdeoApp.Comments.prototype.ID = "e45e0f4f-c206-4cac-a47e-b277037c17b4";

$(document).ready(function() {
	
	AdeoPlatform.Factory.Register(AdeoApp.Comments.prototype.ID, function() {
		return new AdeoApp.Comments();
	});
});

/** 
	@description overriden. Loads the Authentication module.
  */
AdeoApp.Comments.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	Authentication.Init(Container);
	if (Callback)
		Callback();
}

AdeoApp.Comments.prototype.LoginCallback = function(Sender, LoginDialog)
{
	//Authentication.SetLoggedIn(true);
	//alert(Sender.parentNode.parentNode.parentNode.innerHTML)
	AdeoApp.Comments.prototype.PostComment(Sender.parentNode.parentNode.parentNode, LoginDialog);
}

/**
 * @static URL for the webservice
 */
AdeoApp.Comments.prototype.SOAP_URL = "/cms/app/comments/commentData.asmx";

/** 
	@description overriden. Calls the web service to post the comment
	@param {HTMLElement} Container Div element containing all the fields (visible and hidden) to generate a comment
	@param {HTMLElement} Dialog Login dialog to close (if applicable)
  */
AdeoApp.Comments.prototype.PostComment = function(Container, Dialog)
{
	var txtComment = $(Container).find(".txtComment");
	if (!txtComment.length)	//internet exploder........ words... I have none
		Container = $(Container.parentNode).first(".divCommentBox");
	txtComment = $(Container).find(".txtComment");
	var comment = txtComment.val();
	var title = SBPhrases["REVIEWS_ERROR"];
	var message = SBPhrases["REVIEWS_EMPTY_MESSAGE"];
	if (comment)
	{
		var parameters = new SOAPClientParameters();
		parameters.add("ContentKey", $(Container).find(".ContentKey").val());
		parameters.add("LayoutKey", $(Container).find(".LayoutKey").val());
		parameters.add("LoginType", $(Container).find(".LoginType").val());
		parameters.add("Comment", comment);
		parameters.add("ParentComment", $(Container).find(".ParentComment").val());
		parameters.add("CultureCode", board_culture);
		parameters.add("Url", window.location.href);
		SOAPClient.invoke(AdeoApp.Comments.prototype.SOAP_URL, "PostComment", parameters, true, function (Data) {
			//alert(Data);
			var data = jQuery.parseJSON(Data);
			if (data.Success)
			{
				title = SBPhrases["REVIEWS_SUCCESS"];
				txtComment.val("");
				if (Dialog)
					$(Dialog).dialog("close");
			}
			message = data.Message;
			AdeoPlatform.ShowDialog(title, message, false);
		});
	}
	else
	{
		AdeoPlatform.ShowDialog(title, message, false);
	}
}

/** 
	@private
  */
AdeoApp.Comments.prototype.ToggleChildren = function(Sender)
{
	var container = Sender.parentNode.parentNode;
	var childComments = $(container).children('.divCommentList');
	if (Sender.innerHTML == "+")
	{
		Sender.innerHTML = "-";
		childComments.slideDown(function() {
			MSGFront.TileApps();
		});
	}
	else
	{
		Sender.innerHTML = "+";	
		childComments.slideUp(function() {
			MSGFront.TileApps();
		});
	}
}

/** 
	@description Opens up an editing dialog for the comment by cloning the main editor
	@param {HTMLElement} Sender Button clicked to open the reply box
	@param {HTMLElement} ParentComment A GUID key referencing the parent comment
  */
AdeoApp.Comments.prototype.CommentChildren = function(Sender, ParentComment)
{
	var container = Sender.parentNode.parentNode;
	var divReply = $(container).find(".divCommentBox")[0];
	var resReply = "<span id=\"lblComments\">" + SBPhrases["REVIEWS_TITLE_COMMENTS"] + "</span>";	
	if (Sender.innerHTML == resReply)
	{
		var html = $(".divCommentBox").html();
		$(divReply).html(html);
		if (!$(divReply).find(".lnkPost").length) //Why MSIE - WHHHHYYYYYYYYYYYY?
		{
			var lnkPostClone = $(".divCommentBox .lnkPost")[0];
			var lnkNewPost = document.createElement("a");
			lnkNewPost.innerHTML = lnkPostClone.innerHTML;
			lnkNewPost.href = lnkPostClone.href;
			lnkNewPost.onclick = lnkPostClone.onclick;
			lnkNewPost.style.display = lnkPostClone.style.display;
			lnkNewPost.className = lnkPostClone.className;
			$(divReply).append(lnkNewPost);
			
			lnkPostClone = $(".divCommentBox .lnkPostAs")[0];
			lnkNewPost = document.createElement("a");
			lnkNewPost.innerHTML = lnkPostClone.innerHTML;
			lnkNewPost.href = lnkPostClone.href;
			lnkNewPost.onclick = lnkPostClone.onclick;
			lnkNewPost.style.display = lnkPostClone.style.display;
			lnkNewPost.className = lnkPostClone.className;

			$(divReply).append(lnkNewPost);
		}

		$(divReply).find(".ParentComment").val(ParentComment);
		$(divReply).find(".txtComment").val("");
		$(divReply).slideDown('slow', function() {
			$(".divCommentBox .lnkPostAs, .divCommentBox .lnkPost").css("top", "0").css("top", null);
			MSGFront.TileApps();
		});
		Sender.innerHTML = SBPhrases["REVIEWS_CANCEL"];
	}
	else
	{
		$(divReply).slideUp();
		Sender.innerHTML = resReply;
	}
}


AdeoApp.Comments.prototype.ReplyCommentChildren = function(Sender, ParentComment)
{
	var container = Sender.parentNode.parentNode.parentNode;
	var divReply = $(container).find(".divReply")[0];
	var resReply = "<span id=\"lblReply\">" + SBPhrases["REVIEWS_REPLY"] + "</span>";
	if (Sender.innerHTML == resReply)
	{
		var html = $(".divCommentBox").html();
		$(divReply).html(html);
		if (!$(divReply).find(".lnkPost").length) //Why MSIE - WHHHHYYYYYYYYYYYY?
		{
			var lnkPostClone = $(".divCommentBox .lnkPost")[0];
			var lnkNewPost = document.createElement("a");
			lnkNewPost.innerHTML = lnkPostClone.innerHTML;
			lnkNewPost.href = lnkPostClone.href;
			lnkNewPost.onclick = lnkPostClone.onclick;
			lnkNewPost.style.display = lnkPostClone.style.display;
			lnkNewPost.className = lnkPostClone.className;
			$(divReply).append(lnkNewPost);
			
			lnkPostClone = $(".divCommentBox .lnkPostAs")[0];
			lnkNewPost = document.createElement("a");
			lnkNewPost.innerHTML = lnkPostClone.innerHTML;
			lnkNewPost.href = lnkPostClone.href;
			lnkNewPost.onclick = lnkPostClone.onclick;
			lnkNewPost.style.display = lnkPostClone.style.display;
			lnkNewPost.className = lnkPostClone.className;

			$(divReply).append(lnkNewPost);
		}

		$(divReply).find(".ParentComment").val(ParentComment);
		$(divReply).find(".txtComment").val("");
		$(divReply).slideDown('slow', function() {
			$(".divCommentBox .lnkPostAs, .divCommentBox .lnkPost").css("top", "0").css("top", null);
			MSGFront.TileApps();
		});
		Sender.innerHTML = SBPhrases["REVIEWS_CANCEL"];
	}
	else
	{
		$(divReply).slideUp();
		Sender.innerHTML = resReply;
	}
}

var CommentSystem = new AdeoApp.Comments();;

/********************************
/cms/app/nivoslider/nivoslider.js
********************************/
AdeoApp.NivoSlider = function() {};

AdeoApp.NivoSlider.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/nivoslider/nivosliderAdmin.aspx",
	"Name": "NivoSlider",
	"ModuleName": "NivoSlider",
	"Resources": [
		{
			"type": AdeoPlatform.ResourceTypes.CascadingStyleSheet,
			"url": "/cms/app/nivoslider/nivo-slider/nivo-slider.css"
		},
		{
			"type": AdeoPlatform.ResourceTypes.CascadingStyleSheet,
			"url": "/cms/app/nivoslider/nivo-slider/themes/default/default.css"
		},
		{
			"type": AdeoPlatform.ResourceTypes.CascadingStyleSheet,
			"url": "/cms/app/nivoslider/nivo-slider/themes/light/light.css"
		}
	]
});

AdeoApp.NivoSlider.prototype.ID = "c9189d1c-f34b-4c21-9761-6a38344412eb";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.NivoSlider.prototype.ID, function() {
		return new AdeoApp.NivoSlider();
	});
});

AdeoApp.NivoSlider.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	var nivo = $('#nivo_' + LayoutGuid.replace(/-/g, "_"));
	var data = nivo.data("slider");
	nivo.nivoSlider(data);
}

AdeoApp.NivoSlider.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.LoadTableDrops($(Container).find("#sbTableKey")[0]);
}


AdeoApp.NivoSlider.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	// Data["customOption"] = "1";
	return Data;
}

var NivoSlider = new AdeoApp.NivoSlider();;

/********************************
/cms/app/nivoslider/nivo-slider/jquery.nivo.slider.pack.js
********************************/
(function(e){var t=function(t,n){var r=e.extend({},e.fn.nivoSlider.defaults,n);var i={currentSlide:0,currentImage:"",totalSlides:0,running:false,paused:false,stop:false,controlNavEl:false};var s=e(t);s.data("nivo:vars",i).addClass("nivoSlider");var o=s.children();o.each(function(){var t=e(this);var n="";if(!t.is("img")){if(t.is("a")){t.addClass("nivo-imageLink");n=t}t=t.find("img:first")}var r=r===0?t.attr("width"):t.width(),s=s===0?t.attr("height"):t.height();if(n!==""){n.css("display","none")}t.css("display","none");i.totalSlides++});if(r.randomStart){r.startSlide=Math.floor(Math.random()*i.totalSlides)}if(r.startSlide>0){if(r.startSlide>=i.totalSlides){r.startSlide=i.totalSlides-1}i.currentSlide=r.startSlide}if(e(o[i.currentSlide]).is("img")){i.currentImage=e(o[i.currentSlide])}else{i.currentImage=e(o[i.currentSlide]).find("img:first")}if(e(o[i.currentSlide]).is("a")){e(o[i.currentSlide]).css("display","block")}var u=e("<img/>").addClass("nivo-main-image");u.attr("src",i.currentImage.attr("src")).show();s.append(u);e(window).resize(function(){s.children("img").width(s.width());u.attr("src",i.currentImage.attr("src"));u.stop().height("auto");e(".nivo-slice").remove();e(".nivo-box").remove()});s.append(e('<div class="nivo-caption" onclick="if($(this).find('+"'a'"+').length > 0) { document.location = $(this).find('+"'a'"+").attr('href');} else { javascript:;}"+'"></div>'));var a=function(t){var n=e(".nivo-caption",s);if(i.currentImage.attr("title")!=""&&i.currentImage.attr("title")!=undefined){var r=i.currentImage.attr("title");if(r.substr(0,1)=="#")r=e(r).html();if(n.css("display")=="block"){setTimeout(function(){n.html(r)},t.animSpeed)}else{n.html(r);n.stop().fadeIn(t.animSpeed)}}else{n.stop().fadeOut(t.animSpeed)}};a(r);var f=0;if(!r.manualAdvance&&o.length>1){f=setInterval(function(){d(s,o,r,false)},r.pauseTime)}if(r.directionNav){s.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+r.prevText+'</a><a class="nivo-nextNav">'+r.nextText+"</a></div>");e(s).on("click","a.nivo-prevNav",function(){if(i.running){return false}clearInterval(f);f="";i.currentSlide-=2;d(s,o,r,"prev")});e(s).on("click","a.nivo-nextNav",function(){if(i.running){return false}clearInterval(f);f="";d(s,o,r,"next")})}if(r.controlNav){i.controlNavEl=e('<div class="nivo-controlNav"></div>');s.after(i.controlNavEl);for(var l=0;l<o.length;l++){if(r.controlNavThumbs){i.controlNavEl.addClass("nivo-thumbs-enabled");var c=o.eq(l);if(!c.is("img")){c=c.find("img:first")}if(c.attr("data-thumb"))i.controlNavEl.append('<a class="nivo-control" rel="'+l+'"><img src="'+c.attr("data-thumb")+'" alt="" /></a>')}else{i.controlNavEl.append('<a class="nivo-control" rel="'+l+'">'+(l+1)+"</a>")}}e("a:eq("+i.currentSlide+")",i.controlNavEl).addClass("active");e("a",i.controlNavEl).bind("click",function(){if(i.running)return false;if(e(this).hasClass("active"))return false;clearInterval(f);f="";u.attr("src",i.currentImage.attr("src"));i.currentSlide=e(this).attr("rel")-1;d(s,o,r,"control")})}if(r.pauseOnHover){s.hover(function(){i.paused=true;clearInterval(f);f=""},function(){i.paused=false;if(f===""&&!r.manualAdvance){f=setInterval(function(){d(s,o,r,false)},r.pauseTime)}})}s.bind("nivo:animFinished",function(){u.attr("src",i.currentImage.attr("src"));i.running=false;e(o).each(function(){if(e(this).is("a")){e(this).css("display","none")}});if(e(o[i.currentSlide]).is("a")){e(o[i.currentSlide]).css("display","block")}if(f===""&&!i.paused&&!r.manualAdvance){f=setInterval(function(){d(s,o,r,false)},r.pauseTime)}r.afterChange.call(this)});var h=function(t,n,r){if(e(r.currentImage).parent().is("a"))e(r.currentImage).parent().css("display","block");e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").width(t.width()).css("visibility","hidden").show();var i=e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").parent().is("a")?e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").parent().height():e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").height();for(var s=0;s<n.slices;s++){var o=Math.round(t.width()/n.slices);if(s===n.slices-1){t.append(e('<div class="nivo-slice" name="'+s+'"><img src="'+r.currentImage.attr("src")+'" style="position:absolute; width:'+t.width()+"px; height:auto; display:block !important; top:0; left:-"+(o+s*o-o)+'px;" /></div>').css({left:o*s+"px",width:t.width()-o*s+"px",height:i+"px",opacity:"0",overflow:"hidden"}))}else{t.append(e('<div class="nivo-slice" name="'+s+'"><img src="'+r.currentImage.attr("src")+'" style="position:absolute; width:'+t.width()+"px; height:auto; display:block !important; top:0; left:-"+(o+s*o-o)+'px;" /></div>').css({left:o*s+"px",width:o+"px",height:i+"px",opacity:"0",overflow:"hidden"}))}}e(".nivo-slice",t).height(i);u.stop().animate({height:e(r.currentImage).height()},n.animSpeed)};var p=function(t,n,r){if(e(r.currentImage).parent().is("a"))e(r.currentImage).parent().css("display","block");e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").width(t.width()).css("visibility","hidden").show();var i=Math.round(t.width()/n.boxCols),s=Math.round(e('img[src="'+r.currentImage.attr("src")+'"]',t).not(".nivo-main-image,.nivo-control img").height()/n.boxRows);for(var o=0;o<n.boxRows;o++){for(var a=0;a<n.boxCols;a++){if(a===n.boxCols-1){t.append(e('<div class="nivo-box" name="'+a+'" rel="'+o+'"><img src="'+r.currentImage.attr("src")+'" style="position:absolute; width:'+t.width()+"px; height:auto; display:block; top:-"+s*o+"px; left:-"+i*a+'px;" /></div>').css({opacity:0,left:i*a+"px",top:s*o+"px",width:t.width()-i*a+"px"}));e('.nivo-box[name="'+a+'"]',t).height(e('.nivo-box[name="'+a+'"] img',t).height()+"px")}else{t.append(e('<div class="nivo-box" name="'+a+'" rel="'+o+'"><img src="'+r.currentImage.attr("src")+'" style="position:absolute; width:'+t.width()+"px; height:auto; display:block; top:-"+s*o+"px; left:-"+i*a+'px;" /></div>').css({opacity:0,left:i*a+"px",top:s*o+"px",width:i+"px"}));e('.nivo-box[name="'+a+'"]',t).height(e('.nivo-box[name="'+a+'"] img',t).height()+"px")}}}u.stop().animate({height:e(r.currentImage).height()},n.animSpeed)};var d=function(t,n,r,i){var s=t.data("nivo:vars");if(s&&s.currentSlide===s.totalSlides-1){r.lastSlide.call(this)}if((!s||s.stop)&&!i){return false}r.beforeChange.call(this);if(!i){u.attr("src",s.currentImage.attr("src"))}else{if(i==="prev"){u.attr("src",s.currentImage.attr("src"))}if(i==="next"){u.attr("src",s.currentImage.attr("src"))}}s.currentSlide++;if(s.currentSlide===s.totalSlides){s.currentSlide=0;r.slideshowEnd.call(this)}if(s.currentSlide<0){s.currentSlide=s.totalSlides-1}if(e(n[s.currentSlide]).is("img")){s.currentImage=e(n[s.currentSlide])}else{s.currentImage=e(n[s.currentSlide]).find("img:first")}if(r.controlNav){e("a",s.controlNavEl).removeClass("active");e("a:eq("+s.currentSlide+")",s.controlNavEl).addClass("active")}a(r);e(".nivo-slice",t).remove();e(".nivo-box",t).remove();var o=r.effect,f="";if(r.effect==="random"){f=new Array("sliceDownRight","sliceDownLeft","sliceUpRight","sliceUpLeft","sliceUpDown","sliceUpDownLeft","fold","fade","boxRandom","boxRain","boxRainReverse","boxRainGrow","boxRainGrowReverse");o=f[Math.floor(Math.random()*(f.length+1))];if(o===undefined){o="fade"}}if(r.effect.indexOf(",")!==-1){f=r.effect.split(",");o=f[Math.floor(Math.random()*f.length)];if(o===undefined){o="fade"}}if(s.currentImage.attr("data-transition")){o=s.currentImage.attr("data-transition")}s.running=true;var l=0,c=0,d="",m="",g="",y="";if(o==="sliceDown"||o==="sliceDownRight"||o==="sliceDownLeft"){h(t,r,s);l=0;c=0;d=e(".nivo-slice",t);if(o==="sliceDownLeft"){d=e(".nivo-slice",t)._reverse()}d.each(function(){var n=e(this);n.css({top:"0px"});if(c===r.slices-1){setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed,"",function(){t.trigger("nivo:animFinished")})},100+l)}else{setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed)},100+l)}l+=50;c++})}else if(o==="sliceUp"||o==="sliceUpRight"||o==="sliceUpLeft"){h(t,r,s);l=0;c=0;d=e(".nivo-slice",t);if(o==="sliceUpLeft"){d=e(".nivo-slice",t)._reverse()}d.each(function(){var n=e(this);n.css({bottom:"0px"});if(c===r.slices-1){setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed,"",function(){t.trigger("nivo:animFinished")})},100+l)}else{setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed)},100+l)}l+=50;c++})}else if(o==="sliceUpDown"||o==="sliceUpDownRight"||o==="sliceUpDownLeft"){h(t,r,s);l=0;c=0;var b=0;d=e(".nivo-slice",t);if(o==="sliceUpDownLeft"){d=e(".nivo-slice",t)._reverse()}d.each(function(){var n=e(this);if(c===0){n.css("top","0px");c++}else{n.css("bottom","0px");c=0}if(b===r.slices-1){setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed,"",function(){t.trigger("nivo:animFinished")})},100+l)}else{setTimeout(function(){n.animate({opacity:"1.0"},r.animSpeed)},100+l)}l+=50;b++})}else if(o==="fold"){h(t,r,s);l=0;c=0;e(".nivo-slice",t).each(function(){var n=e(this);var i=n.width();n.css({top:"0px",width:"0px"});if(c===r.slices-1){setTimeout(function(){n.animate({width:i,opacity:"1.0"},r.animSpeed,"",function(){t.trigger("nivo:animFinished")})},100+l)}else{setTimeout(function(){n.animate({width:i,opacity:"1.0"},r.animSpeed)},100+l)}l+=50;c++})}else if(o==="fade"){h(t,r,s);m=e(".nivo-slice:first",t);m.css({width:t.width()+"px"});m.animate({opacity:"1.0"},r.animSpeed*2,"",function(){t.trigger("nivo:animFinished")})}else if(o==="slideInRight"){h(t,r,s);m=e(".nivo-slice:first",t);m.css({width:"0px",opacity:"1"});m.animate({width:t.width()+"px"},r.animSpeed*2,"",function(){t.trigger("nivo:animFinished")})}else if(o==="slideInLeft"){h(t,r,s);m=e(".nivo-slice:first",t);m.css({width:"0px",opacity:"1",left:"",right:"0px"});m.animate({width:t.width()+"px"},r.animSpeed*2,"",function(){m.css({left:"0px",right:""});t.trigger("nivo:animFinished")})}else if(o==="boxRandom"){p(t,r,s);g=r.boxCols*r.boxRows;c=0;l=0;y=v(e(".nivo-box",t));y.each(function(){var n=e(this);if(c===g-1){setTimeout(function(){n.animate({opacity:"1"},r.animSpeed,"",function(){t.trigger("nivo:animFinished")})},100+l)}else{setTimeout(function(){n.animate({opacity:"1"},r.animSpeed)},100+l)}l+=20;c++})}else if(o==="boxRain"||o==="boxRainReverse"||o==="boxRainGrow"||o==="boxRainGrowReverse"){p(t,r,s);g=r.boxCols*r.boxRows;c=0;l=0;var w=0;var E=0;var S=[];S[w]=[];y=e(".nivo-box",t);if(o==="boxRainReverse"||o==="boxRainGrowReverse"){y=e(".nivo-box",t)._reverse()}y.each(function(){S[w][E]=e(this);E++;if(E===r.boxCols){w++;E=0;S[w]=[]}});for(var x=0;x<r.boxCols*2;x++){var T=x;for(var N=0;N<r.boxRows;N++){if(T>=0&&T<r.boxCols){(function(n,i,s,u,a){var f=e(S[n][i]);var l=f.width();var c=f.height();if(o==="boxRainGrow"||o==="boxRainGrowReverse"){f.width(0).height(0)}if(u===a-1){setTimeout(function(){f.animate({opacity:"1",width:l,height:c},r.animSpeed/1.3,"",function(){t.trigger("nivo:animFinished")})},100+s)}else{setTimeout(function(){f.animate({opacity:"1",width:l,height:c},r.animSpeed/1.3)},100+s)}})(N,T,l,c,g);c++}T--}l+=100}}};var v=function(e){for(var t,n,r=e.length;r;t=parseInt(Math.random()*r,10),n=e[--r],e[r]=e[t],e[t]=n);return e};var m=function(e){if(this.console&&typeof console.log!=="undefined"){console.log(e)}};this.stop=function(){if(!e(t).data("nivo:vars").stop){e(t).data("nivo:vars").stop=true;m("Stop Slider")}};this.start=function(){if(e(t).data("nivo:vars").stop){e(t).data("nivo:vars").stop=false;m("Start Slider")}};r.afterLoad.call(this);return this};e.fn.nivoSlider=function(n){return this.each(function(r,i){var s=e(this);if(s.data("nivoslider")){return s.data("nivoslider")}var o=new t(this,n);s.data("nivoslider",o)})};e.fn.nivoSlider.defaults={effect:"random",slices:15,boxCols:8,boxRows:4,animSpeed:500,pauseTime:3e3,startSlide:0,directionNav:true,controlNav:true,controlNavThumbs:false,pauseOnHover:true,manualAdvance:false,prevText:"Prev",nextText:"Next",randomStart:false,beforeChange:function(){},afterChange:function(){},slideshowEnd:function(){},lastSlide:function(){},afterLoad:function(){}};e.fn._reverse=[].reverse})(jQuery);

/********************************
/cms/app/reviews/reviews.js
********************************/
/** 
	@class Adds a review section.
	@augments AdeoApp.AjaxApp
  */
AdeoApp.Reviews = function() {};

AdeoApp.Reviews.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/reviews/reviewsAdmin.aspx",
	"Name": "Reviews",
	"ModuleName": "reviews"
});

AdeoApp.Reviews.prototype.ID = "d2065e4f-f8f3-485d-a490-519a5212eda2";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Reviews.prototype.ID, function() {
		return new AdeoApp.Reviews();
	});
});

/**
 * @static URL for the webservice
 */
AdeoApp.Reviews.prototype.SOAP_URL = "/cms/app/reviews/reviewData.asmx";

/** 
	@description overriden. Calls the web service to post the review.
	@param {HTMLElement} Container Div element containing all the fields (visible and hidden) to generate a comment
	@param {HTMLElement} Dialog Login dialog to close (if applicable)
  */
AdeoApp.Reviews.prototype.PostReview = function(Container, Dialog)
{
	var review = $(Container).find(".txtReview").val();
	var location = $(Container).find(".txtLocation").val();
	var score = $(Container).find(".hidRating").val();
	var productKey = 1; /* $("#spanProductKey").html() + "1";*/
	var title = SBPhrases["REVIEWS_ERROR"]; //"TODO:Error"; //AdeoPlatform.Resource("Error");
	var message = "";	
	if (review && score > 0)
	{

		var parameters = new SOAPClientParameters();
		parameters.add("ContentKey", $(Container).find(".ContentKey").val());
		parameters.add("LayoutKey", $(Container).find(".LayoutKey").val());
		parameters.add("LoginType", $(Container).find(".LoginType").val());
		parameters.add("Review", review);
		parameters.add("Score", score);
		parameters.add("Location", location);
		parameters.add("Custnmbr", "SETBYSERVER");				
		parameters.add("BizArea", productKey);
		parameters.add("CultureCode", board_culture);
		parameters.add("Url", window.location.href);

		SOAPClient.invoke(AdeoApp.Reviews.prototype.SOAP_URL, "PostReview", parameters, true, function (Data) {
			var data = jQuery.parseJSON(Data);
			//alert("PostReview:" + message);
			if (data.Success)
			{
				title = SBPhrases["REVIEWS_SUCCESS"];
				if (Dialog)
					$(Dialog).dialog("close");
				$(Container).find(".txtReview").val("");
			}
			message = data.Message;
			AdeoPlatform.ShowDialog(title, message, false);

		});
	}
	else
	{
		if(! review)
		{
			message = SBPhrases["REVIEWS_EMPTY_MESSAGE"];
		}
		else
		{
			message =  SBPhrases["REVIEWS_EMPTY_SCORE"];
			$(Container).find(".divRating").addClass("errorBox");
		}
		AdeoPlatform.ShowDialog(title, message, false);
	}
}

AdeoApp.Reviews.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	var locationSelect = $(Container).find('.chkLocationSelect')[0];
	var locationSelectVal = "1";
	if (!locationSelect.checked)
		locationSelectVal = "0";
	Data["locationSelect"] = locationSelectVal;
	
	var businessSelect = $(Container).find('.rdoBusinessSelect')[0];
	var businessSelectVal = "1";
	if (!businessSelect.checked)
		businessSelectVal = "0";
	Data["businessSelect"] = businessSelectVal;

	//alert(JSON.stringify(Data));
	return Data;
}

AdeoApp.Reviews.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	var bizId = $(Container).find(".hidBizAreaId").val();
	$(Container).find(".drpLocationAdmin").val(bizId);
}

/** 
	@description overriden. Loads the Authentication module and the stars.
  */
AdeoApp.Reviews.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
   
	Authentication.Init(Container);	 
	var ratingIcons = $(Container).find(".divRating img");

	ratingIcons.mouseenter(function() {
		var iconOver = this;
		var style = "positive";
		var stillShowing = true;
		ratingIcons.each(function() {
			//this.src = "/img/theme/standard/review_" + style + ".jpg";
			//if (this == iconOver)
			//	style = "negative";
			if (stillShowing)
				$(this).stop().animate({"opacity": "1"}, "slow");
			else
				$(this).stop().animate({"opacity": "0"}, "slow");
			if (this == iconOver)
				stillShowing = false;
		});
	});
	$(".divRating").mouseleave(function() {		
		var index = 0;
		var rating = $(this).find(".hidRating").val();
		var style = "positive";
		ratingIcons.each(function() {
			/*
			index++;
			if (index > rating)
				style = "negative";	
			this.src = "/img/theme/standard/review_" + style + ".jpg";
			*/
			index++;
			if (index > rating)
				$(this).stop().animate({"opacity": "0"}, "slow");
			else
				$(this).stop().animate({"opacity": "1"}, "slow");
		})		
	});
	ratingIcons.click(function() {
		var rating = ratingIcons.index(this) + 1;
		$(this).parents(".divRating").find(".hidRating").val(rating);
		$(Container).find(".divRating").removeClass("errorBox");
	});
	if (Callback)
		Callback();
}

AdeoApp.Reviews.prototype.LoginCallback = function(Sender, LoginDialog)
{
	//Authentication.SetLoggedIn(true);
	AdeoApp.Reviews.prototype.PostReview(Sender.parentNode.parentNode.parentNode, LoginDialog);
}


var ReviewSystem = new AdeoApp.Reviews();;

/********************************
/cms/app/blog/blog.js
********************************/
AdeoApp.Blog = function() {};

AdeoApp.Blog.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/blog/blogAdmin.aspx",
	"Name": "Blog",
	"ModuleName": "Blog"
});

AdeoApp.Blog.prototype.ID = "1df0ae99-8284-11e2-a20a-dc0ea1022e1d";

AdeoApp.Blog.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.LoadTableDrops($(Container).find("#sbTableKey")[0]);
}

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Blog.prototype.ID, function() {
		return new AdeoApp.Blog();
	});
});

var Blog = new AdeoApp.Blog();;

/********************************
/cms/app/gridlist/gridlist.js
********************************/
AdeoApp.GridList = function() {};

AdeoApp.GridList.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/gridList/gridListAdmin.aspx",
	"Name": "GridList",
	"ModuleName": "GridList"
});

AdeoApp.GridList.prototype.ID = "1bea4707-2445-4ee1-8905-691c5dfcbf60";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.GridList.prototype.ID, function() {
		return new AdeoApp.GridList();
	});
});

AdeoApp.GridList.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {

}

AdeoApp.GridList.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.LoadTableDrops($(Container).find("#sbTableKey")[0]);
}


AdeoApp.GridList.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	// Data["customOption"] = "1";
	return Data;
}


var GridList = new AdeoApp.GridList();;

/********************************
/cms/app/formOutput/formOutput.js
********************************/
AdeoApp.FormOutput = function() {};

AdeoApp.FormOutput.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/formOutput/formOutputAdmin.aspx",
	"Name": "FormOutput",
	"ModuleName": "FormOutput"
});

AdeoApp.FormOutput.prototype.ID = "2ea59418-70ae-47a9-8b98-1ecff41b3fd6";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.FormOutput.prototype.ID, function() {
		return new AdeoApp.FormOutput();
	});
});

AdeoApp.FormOutput.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {

}

AdeoApp.FormOutput.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	
}


AdeoApp.FormOutput.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	// Data["customOption"] = "1";
	return Data;
}


var FormOutput = new AdeoApp.FormOutput();;

/********************************
/cms/app/logoList/logoList.js
********************************/
AdeoApp.LogoList = function() {};

AdeoApp.LogoList.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/logoList/logoListAdmin.aspx",
	"Name": "LogoList",
	"ModuleName": "LogoList",
	"Resources": [ ]
});

AdeoApp.LogoList.prototype.ID = "1C830E0A-8B12-11E2-A6B5-DC0EA1022E1D";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.LogoList.prototype.ID, function() {
		return new AdeoApp.LogoList();
	});
});

AdeoApp.LogoList.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	//$(Container).find('#slider').LogoList();
}

AdeoApp.LogoList.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.LoadTableDrops($(Container).find("#sbTableKey")[0]);
}


AdeoApp.LogoList.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	// Data["customOption"] = "1";
	return Data;
}

var LogoList = new AdeoApp.LogoList();;

/********************************
/cms/app/control/control.js
********************************/
AdeoApp.Control = function() {};

AdeoApp.Control.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/control/controlAdmin.aspx",
	"Name": "Control",
	"ModuleName": "Control"
});

AdeoApp.Control.prototype.ID = "682e9f27-6932-4680-9da2-9d94430f7971";

AdeoApp.Control.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) { }

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Control.prototype.ID, function() {
		return new AdeoApp.Control();
	});
});

var Control = new AdeoApp.Control();;

/********************************
/Modules/Adeo.SpringBoard.Ecommerce/app/cart.js
********************************/
AdeoApp.Cart = function() {};

AdeoApp.Cart.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/Modules/Adeo.SpringBoard.Ecommerce/app/cartAdmin.aspx",
	"Name": "Cart",
	"ModuleName": "Cart"
});

AdeoApp.Cart.prototype.ID = "e37e3d70-1cca-4fca-b186-d321a21c558c";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Cart.prototype.ID, function() {
		return new AdeoApp.Cart();
	});
});

AdeoApp.Cart.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {

}

AdeoApp.Cart.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	
}

AdeoApp.Cart.prototype.AdminSave = function(ContentGuid, LayoutGuid, Container, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("RewriteKey", $(Container).find("#drpRewrite").val());
	parameters.add("CartContentsKey", $(Container).find("#drpCartContents").val());
	parameters.add("CheckoutKey", $(Container).find("#drpCheckout").val());
	parameters.add("ReceiptKey", $(Container).find("#drpReceipt").val());
	parameters.add("AccountKey", $(Container).find("#drpAccount").val());
	SOAPClient.invoke("/Modules/Adeo.SpringBoard.Ecommerce/app/CartApp.asmx", "SaveRewrite", parameters, true, Callback);
}

var Cart = new AdeoApp.Cart();;

/********************************
/cms/app/campaign/campaign.js
********************************/
/** 
	@class Provides a second HTML campaign
	@augments AdeoApp.AjaxApp
  */
AdeoApp.Campaign = function() {};

AdeoApp.Campaign.prototype = new AdeoApp.AjaxApp({
	"AdminURL": "/cms/app/campaign/campaignAdmin.aspx",
	"Name": "Campaign",
	"ModuleName": "Campaign"
});

AdeoApp.Campaign.prototype.PostAdminLoad = function(ContentGuid, LayoutGuid, Container) {
	this.MakeEditor(Container, LayoutGuid);
}

AdeoApp.Campaign.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	Data["html"] = CKEDITOR.instances[LayoutGuid].getData();	
		
	Data["dataSource"] = $(Container).find('input:radio[name=rdoDataSource]:checked').val();
	Data["validation"] = $(Container).find('input:radio[name=rdoValidation]:checked').val();
	Data["recipient"] = $(Container).find('input:radio[name=rdoEmail]:checked').val();	
	
	if ($(Container).find(".showButton").length)
	{
		Data["showButton"] = 0;
		if($(Container).find("#showButton").is(':checked'))
			Data["showButton"] = -1;		
	}	
	
	return Data;
}

/**
	@description Creates an HTML editor
	@param {HTMLElement} Container DIV that contains a textarea
	@param {String} LayoutGuid A unique ID for the editor (typically the layout item GUID)
*/
AdeoApp.Campaign.prototype.MakeEditor = function(Container, LayoutGuid)
{	
	var initEditor = function() 
	{
		var textarea = $(Container).find("textarea")[0];
		textarea.id = LayoutGuid;
		var instance = CKEDITOR.instances[textarea.id];
	    if(instance)
	        CKEDITOR.remove(instance);
		CKEDITOR.replace(textarea);
	}
	
	if (!window.CKEDITOR)
	{
		AdeoPlatform.LoadResource("/cms/resources/ckeditor/ckeditor.js", AdeoPlatform.ResourceTypes.JavaScript);
		setTimeout(initEditor, 1000);
	}
	else
		initEditor();
}

$(document).ready(function() {
	AdeoPlatform.Factory.Register("084778f4-35b4-40dd-8719-da14d44962cb", function() {
		return new AdeoApp.Campaign();
	});
			
	var container = $(".divCampaignContainer .step"); 
	if (container.length > 0)
	{	
		$(".divCampaignContainer h3:first").show();
		$(".divCampaignContainer .step:first").show();
		
		if (addCampaignButton)
			$(".divCampaignContainer .step:first").append('<input onclick="doSaveStepCampaign(this, 1)" class="btnCampaignButton btnCampaignButtonNext" type="button" value="' + SBPhrases["CAMPAIGN_CONTINUE"] + '" />') 
	}	
	else
	{
		$(".divCampaignContainer h3").show();		
		if (addCampaignButton)
			$(".divCampaignContainer").append('<input onclick="doSaveCampaign(this)" class="btnCampaignButton btnCampaignButtonSend" type="button" value="' + SBPhrases["CAMPAIGN_SEND"] + '" />') 
	}		
});
		
	
AdeoApp.Campaign.selectDataSource = function(sender)
{	
	$("div .divDataSource").slideUp();
	$("." + sender.id).slideDown();		
}

AdeoApp.Campaign.selectValidation = function(sender)
{	
	$("div .divValidation").slideUp();
	$("." + sender.id).slideDown();		
}

AdeoApp.Campaign.selectRecipient = function(sender)
{	
	$("div .divRecipient").slideUp();
	$("." + sender.id).slideDown();		
};

/********************************
/cms/app/newsletter/newsletter.js
********************************/
AdeoApp.Newsletter = function() {};

AdeoApp.Newsletter.prototype = new AdeoApp.AjaxApp({
	/*"AdminURL": "/app/newsletter/newsletterAdmin.aspx",*/
	"Name": "Newsletter",
	"ModuleName": "Newsletter"
});

AdeoApp.Newsletter.prototype.ID = "cf4f200f-18b5-4ef9-817b-65af23da51a0";

$(document).ready(function() {
	AdeoPlatform.Factory.Register(AdeoApp.Newsletter.prototype.ID, function() {
		return new AdeoApp.Newsletter();
	});
});

AdeoApp.Newsletter.prototype.PreAdminSave = function(ContentGuid, LayoutGuid, Container, Data) {
	Data["custnmbr"] = "SETBYSERVER";
	return Data;
}

AdeoApp.Newsletter.prototype.FrontLoad = function(ContentGuid, LayoutGuid, Container, Width, Height, Callback) {
	$(Container).find("input:submit").button().click(function() {
		AdeoApp.Newsletter.prototype.Signup(Container, ContentGuid, LayoutGuid);
	});
	var txtSignup = $(Container).find(".txtSignup");
	$(txtSignup).focus(function(){
		if(txtSignup.val() == SBPhrases["NEWSLETTER_SIGNUP"]) {
			txtSignup.val("");
			//$('#txtSignup').css('color','#000000');
		}
		else {
			//$('#txtSignup').css('color','#000000');
		}
	});
	$(txtSignup).focusout(function(){
		if($.trim(txtSignup.val()) == "") {
			txtSignup.val(SBPhrases["NEWSLETTER_SIGNUP"]);
			$('#txtSignup').css('color','#C5C5C5');
		}
	});
	if (Callback)
		Callback();
}

AdeoApp.Newsletter.prototype.Signup = function(Container, ContentGuid, LayoutGuid) {
	var email = $(Container).find(".txtSignup").val();
	var host = window.location.hostname.replace("www.","").replace(".com","");
	if(email != SBPhrases["NEWSLETTER_SIGNUP"]) {
		$(Container).find(".txtSignup").removeClass("txtRequired");
		var Me = this;
		var CallbackOk = function(Dialog) {
			var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z.]{2,5}$/;
			email = $(Dialog).find(".txtEmail").val();
			if( ! emailRegex.test(email)) {
				$(Dialog).find(".txtEmail").addClass("txtRequired");
			} else if($(Dialog).find(".txtEmail").hasClass("txtRequired")) {
				$(Dialog).find(".txtEmail").removeClass("txtRequired");				
			}
			var name = $(Dialog).find(".txtName").val();
			if(name.length <= 3) {
				$(Dialog).find(".txtName").addClass("txtRequired");
			} else if($(Dialog).find(".txtName").hasClass("txtRequired")) {
				$(Dialog).find(".txtName").removeClass("txtRequired");
			}
			if($(Dialog).find('.txtRequired').length == 0) {
				Me.Subscribe(ContentGuid, LayoutGuid, name, email, host, function(Response) {
					if(Response != '0') {
						//$(Dialog).dialog("close");
						//$.fancybox.close();
						$(Container).find(".txtSignup").val(SBPhrases["NEWSLETTER_SIGNUP"]);
						//AdeoApp.Platform.prototype.ShowAlert(SBPhrases["NEWSLETTER_TITLE"], SBPhrases["NEWSLETTER_THANKS"], null);
						$(Dialog).html(SBPhrases["NEWSLETTER_THANKS"]);
					} else {
						// alert(Response); // Debug!
					}
				});
			}
		};
	
		var dlg = $(Container).find(".dlgSignup")[0];
		var title = SBPhrases["NEWSLETTER_TITLE"];
		//AdeoPlatform.ShowDialog(title, dlg.innerHTML, true, CallbackOk, null, true, "divDialogSignup");
		$('html').append('<div id="divDialogSignupWrap"><div id="divDialogSignup">' + dlg.innerHTML + '<input id="okbtn" type="button" value="OK" /></div></div>');
		$.fancybox({
			type:'inline', 
			content:$('#divDialogSignupWrap').html(),
			title:title,
			afterClose:function(){$('#divDialogSignupWrap').hide();}
		});
		$("#divDialogSignup").find(".txtEmail").val(email);
		$('#divDialogSignup #okbtn').click(function() {CallbackOk($('#divDialogSignup'));});
	} else {
		$(Container).find(".txtSignup").addClass("txtRequired");
	}
}

AdeoApp.Newsletter.prototype.SOAP_URL = "/cms/app/newsletter/NewsletterData.asmx";

AdeoApp.Newsletter.prototype.Subscribe = function(ContentGuid, LayoutGuid, name, email, host, Callback) {
	var parameters = new SOAPClientParameters();
	parameters.add("ContentGuid", ContentGuid);
	parameters.add("LayoutGuid", LayoutGuid);
	parameters.add("name", name);
	parameters.add("email", email);
	parameters.add("host", host);	
	parameters.add("cultureCode", board_culture);
	SOAPClient.invoke(this.SOAP_URL, "Subscribe", parameters, true, Callback);
};

/********************************
/cms/js/mosaic/front.js
********************************/
$(document).ready(function() {
	MSGFront.Init();
});

AdeoApp.Front = function() {
};

AdeoApp.Front.prototype.Init = function() 
{
	if (window.AppList) //Front end code only.
	{
		this.Containers = $(".divContainer .divAppFront");
		this.AppList = AppList.rows;
		for (var i = 0; i < this.AppList.length; i++)
		{
			this.LoadFront(this.AppList[i].appKey, ContentKey, this.AppList[i].layoutItemKey, i, this.AppList[i].height, this.AppList[i].width);
		}

		window.onresize = function() {
			MSGFront.SmartPadding();
			$('.divContainer').masonry('destroy');
			$('.divContainer').masonry({
				itemSelector: '.divAppFront',
				columnWidth: 1
			});
		};
		
		//Button link facyfication
		this.SmartPadding();
		$('.divContainer').masonry({
			itemSelector: '.divAppFront',
			columnWidth: 1
		}); /*.masonry('unbindResize');*/
	}
}

AdeoApp.Front.prototype.SmartPadding = function()
{
	var apps = $('.divContainer .divAppFront');
	var container = $('.divContainer');
	if (container.length)
	{
		var containerWidth = $($('.divContainer')[0].parentNode).width();
		var i = 0;
		while (i < apps.length)
		{
			var app = apps[i];
			var coordinates = this.NextWidth(apps, i, containerWidth);
			$(app).css("margin-left", coordinates.Padding);
			i = coordinates.Index;
		}
	}
}

AdeoApp.Front.prototype.NextWidth = function(Apps, Index, ContainerWidth) 
{
	var i = Index;
	var width = 0;
	var done = false;
	while (i < Apps.length && !done)
	{
		$(Apps[i]).css("margin-left", "");
		var appWidth = $(Apps[i]).data("width");
		if (width + appWidth < ContainerWidth)
		{
			width = width + appWidth;
			i++;
		}
		else
		{
			if (width == 0) //single block is already wider than width
			{
				width = ContainerWidth;
				i++;
			}
			done = true;
		}
	}

	var difference = ContainerWidth - width;
	return {
		"Index": i,
		"Padding": (difference ? (difference / 2) + "px" : "")
	}
}

AdeoApp.Front.prototype.FancyfiyButtons = function() 
{
	$(".lnkFancyButton").button();
}

AdeoApp.Front.prototype.LoadFront = function(AppGuid, ContentGuid, LayoutGuid, Index, Height, Width) 
{
	var item = this.Containers[Index];
	AdeoPlatform.Factory.GetApp(AppGuid).FrontLoad(ContentGuid, LayoutGuid, item, Width, Height, function () {
		this.progressCount++;
		//alert(AppGuid + ": " + progressCount + " == " + AppList.length + " -> " + (progressCount == AppList.length));
		if (this.progressCount == this.AppList.length)
		{
			this.TileApps();
		}
	});
}

AdeoApp.Front.prototype.TileApps = function() 
{
	this.SmartPadding();
	$('#divContainer').masonry({
		itemSelector: '.divAppFront',
		columnWidth: 1
	});
}

var MSGFront = new AdeoApp.Front();

/* cookies */
Adeo = {};

Adeo.Toolbox = function() { };

Adeo.Toolbox.prototype.SetCookie = function(Name, Value, Days) {
	if (!Days) 
	{
		Days = 365;
	}
	var endDate = new Date();
	endDate.setTime(endDate.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = Name +"=" + escape(Value) + "; expires=" + endDate.toGMTString() + "; path=/;";
}

Adeo.Toolbox.prototype.GetCookie = function(Name, DefaultValue)
{
	var returnValue = this.GetCookieRaw(Name);
	if (!returnValue)
	{
		returnValue = DefaultValue;
	}
	return returnValue
}

Adeo.Toolbox.prototype.GetCookieRaw = function(Name)
{
	var cookieName = Name + "=";
	var cookieLength = document.cookie.length;
	var cookieStart = 0;
	while (cookieStart < cookieLength)
	{
		var variableStart = cookieStart + cookieName.length;

		if (document.cookie.substring(cookieStart, variableStart) == cookieName)
		{
			var variableEnd = document.cookie.indexOf (";", variableStart);
			if (variableEnd == -1)
			{
				variableEnd = cookieLength;
			}
			var returnValue = unescape(document.cookie.substring(variableStart, variableEnd));
			if (returnValue == "null")
			{
				returnValue = null;
			}
			return returnValue;
		}

		cookieStart = document.cookie.indexOf(" ", cookieStart) + 1;

		if (cookieStart == 0)
		{
			break;
		}
	}
}

function doSearch(TextBoxName) {
	var query = $("#" + TextBoxName).val();
	var discoveryType = $("#searchBlock input:checked").val();
	if($.trim(query) != "") {
		var url = "/en/search.aspx?ContentGuid=55771eea-2ba8-4ae0-9225-c97edc501837&LayoutGuid=0971891b-ed20-44e3-aee0-1666e2a9f609"; //location.href;
		if(url.indexOf('query') > 0) {
			url = url.substring(0, url.lastIndexOf('query'));
		} else {
			url += "&"
		}
		url += "query="+query+"&discoveryType=WebPage&pageNumber=1&pageSize=10&shouldDocumentsBeClustered=0";
		//
		var url = "/en/search.aspx?query="+query+"&discoveryType=WebPage&pageNumber=1&pageSize=10&shouldDocumentsBeClustered=0";
		window.location = url;
	} else {
		alert("No query!");
	}
}

/**
	@description Checks a string against a regular expression to see if it's a valid email address.
	@param {String} Email
	@returns {Bool}
*/
Adeo.Toolbox.prototype.IsEmail = function(Email) 
{
  var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(Email);
}

var AdeoTools = new Adeo.Toolbox();

/*
//alert(AdeoTools.GetCookie("viewingMobile"));
if (jQuery.browser.mobile || AdeoTools.GetCookie("viewingMobile") == "1")
{
	var styleNode = document.createElement('link');
	styleNode.setAttribute('rel', 'stylesheet');
	styleNode.setAttribute('type', 'text/css');
	styleNode.setAttribute('href', '/css/mobile.css');
	document.getElementsByTagName('head')[0].appendChild(styleNode);
}

*
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 *
(function(a){jQuery.browser.mobile=/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
*/;

/********************************
/cms/resources/noty-master/js/noty/jquery.noty.js
********************************/
/**
 * noty - jQuery Notification Plugin v2.0.3
 * Contributors: https://github.com/needim/noty/graphs/contributors
 *
 * Examples and Documentation - http://needim.github.com/noty/
 *
 * Licensed under the MIT licenses:
 * http://www.opensource.org/licenses/mit-license.php
 *
 **/

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {
        }

        F.prototype = o;
        return new F();
    };
}

(function ($) {

    var NotyObject = {

        init:function (options) {

            // Mix in the passed in options with the default options
            this.options = $.extend({}, $.noty.defaults, options);

            this.options.layout = (this.options.custom) ? $.noty.layouts['inline'] : $.noty.layouts[this.options.layout];
            this.options.theme = $.noty.themes[this.options.theme];

            delete options.layout;
            delete options.theme;

            this.options = $.extend({}, this.options, this.options.layout.options);
            this.options.id = 'noty_' + (new Date().getTime() * Math.floor(Math.random() * 1000000));

            this.options = $.extend({}, this.options, options);

            // Build the noty dom initial structure
            this._build();

            // return this so we can chain/use the bridge with less code.
            return this;
        }, // end init

        _build:function () {

            // Generating noty bar
            var $bar = $('<div class="noty_bar"></div>').attr('id', this.options.id);
            $bar.append(this.options.template).find('.noty_text').html(this.options.text);

            this.$bar = (this.options.layout.parent.object !== null) ? $(this.options.layout.parent.object).css(this.options.layout.parent.css).append($bar) : $bar;

            // Set buttons if available
            if (this.options.buttons) {

                // If we have button disable closeWith & timeout options
                this.options.closeWith = [];
                this.options.timeout = false;

                var $buttons = $('<div/>').addClass('noty_buttons');

                (this.options.layout.parent.object !== null) ? this.$bar.find('.noty_bar').append($buttons) : this.$bar.append($buttons);

                var self = this;

                $.each(this.options.buttons, function (i, button) {
                    var $button = $('<button/>').addClass((button.addClass) ? button.addClass : 'gray').html(button.text)
                        .appendTo(self.$bar.find('.noty_buttons'))
                        .bind('click', function () {
                            if ($.isFunction(button.onClick)) {
                                button.onClick.call($button, self);
                            }
                        });
                });
            }

            // For easy access
            this.$message = this.$bar.find('.noty_message');
            this.$closeButton = this.$bar.find('.noty_close');
            this.$buttons = this.$bar.find('.noty_buttons');

            $.noty.store[this.options.id] = this; // store noty for api

        }, // end _build

        show:function () {

            var self = this;

            $(self.options.layout.container.selector).append(self.$bar);

            self.options.theme.style.apply(self);

            ($.type(self.options.layout.css) === 'function') ? this.options.layout.css.apply(self.$bar) : self.$bar.css(this.options.layout.css || {});

            self.$bar.addClass(self.options.layout.addClass);

            self.options.layout.container.style.apply($(self.options.layout.container.selector));

            self.options.theme.callback.onShow.apply(this);

            if ($.inArray('click', self.options.closeWith) > -1)
                self.$bar.css('cursor', 'pointer').one('click', function () {
                    self.close();
                });

            if ($.inArray('hover', self.options.closeWith) > -1)
                self.$bar.one('mouseenter', function () {
                    self.close();
                });

            if ($.inArray('button', self.options.closeWith) > -1)
                self.$closeButton.one('click', function () {
                    self.close();
                });

            if ($.inArray('button', self.options.closeWith) == -1)
                self.$closeButton.remove();

            if (self.options.callback.onShow)
                self.options.callback.onShow.apply(self);

            self.$bar.animate(
                self.options.animation.open,
                self.options.animation.speed,
                self.options.animation.easing,
                function () {
                    if (self.options.callback.afterShow) self.options.callback.afterShow.apply(self);
                    self.shown = true;
                });

            // If noty is have a timeout option
            if (self.options.timeout)
                self.$bar.delay(self.options.timeout).promise().done(function () {
                    self.close();
                });

            return this;

        }, // end show

        close:function () {

            if (this.closed) return;

            var self = this;

            if (!this.shown) { // If we are still waiting in the queue just delete from queue
                var queue = [];
                $.each($.noty.queue, function (i, n) {
                    if (n.options.id != self.options.id) {
                        queue.push(n);
                    }
                });
                $.noty.queue = queue;
                return;
            }

            self.$bar.addClass('i-am-closing-now');

            if (self.options.callback.onClose) {
                self.options.callback.onClose.apply(self);
            }

            self.$bar.clearQueue().stop().animate(
                self.options.animation.close,
                self.options.animation.speed,
                self.options.animation.easing,
                function () {
                    if (self.options.callback.afterClose) self.options.callback.afterClose.apply(self);
                })
                .promise().done(function () {

                    // Modal Cleaning
                    if (self.options.modal) {
                        $.notyRenderer.setModalCount(-1);
                        if ($.notyRenderer.getModalCount() == 0) $('.noty_modal').fadeOut('fast', function () {
                            $(this).remove();
                        });
                    }

                    // Layout Cleaning
                    $.notyRenderer.setLayoutCountFor(self, -1);
                    if ($.notyRenderer.getLayoutCountFor(self) == 0) $(self.options.layout.container.selector).remove();

                    // Make sure self.$bar has not been removed before attempting to remove it
                    if (typeof self.$bar !== 'undefined' && self.$bar !== null ) {
                        self.$bar.remove();
                        self.$bar = null;
                        self.closed = true;
                    }

                    delete $.noty.store[self.options.id]; // deleting noty from store

                    self.options.theme.callback.onClose.apply(self);

                    if (!self.options.dismissQueue) {
                        // Queue render
                        $.noty.ontap = true;

                        $.notyRenderer.render();
                    }

                });

        }, // end close

        setText:function (text) {
            if (!this.closed) {
                this.options.text = text;
                this.$bar.find('.noty_text').html(text);
            }
            return this;
        },

        setType:function (type) {
            if (!this.closed) {
                this.options.type = type;
                this.options.theme.style.apply(this);
                this.options.theme.callback.onShow.apply(this);
            }
            return this;
        },

        setTimeout:function (time) {
            if (!this.closed) {
                var self = this;
                this.options.timeout = time;
                self.$bar.delay(self.options.timeout).promise().done(function () {
                    self.close();
                });
            }
            return this;
        },

        closed:false,
        shown:false

    }; // end NotyObject

    $.notyRenderer = {};

    $.notyRenderer.init = function (options) {

        // Renderer creates a new noty
        var notification = Object.create(NotyObject).init(options);

        (notification.options.force) ? $.noty.queue.unshift(notification) : $.noty.queue.push(notification);

        $.notyRenderer.render();

        return ($.noty.returns == 'object') ? notification : notification.options.id;
    };

    $.notyRenderer.render = function () {

        var instance = $.noty.queue[0];

        if ($.type(instance) === 'object') {
            if (instance.options.dismissQueue) {
                $.notyRenderer.show($.noty.queue.shift());
            } else {
                if ($.noty.ontap) {
                    $.notyRenderer.show($.noty.queue.shift());
                    $.noty.ontap = false;
                }
            }
        } else {
            $.noty.ontap = true; // Queue is over
        }

    };

    $.notyRenderer.show = function (notification) {

        if (notification.options.modal) {
            $.notyRenderer.createModalFor(notification);
            $.notyRenderer.setModalCount(+1);
        }

        // Where is the container?
        if ($(notification.options.layout.container.selector).length == 0) {
            if (notification.options.custom) {
                notification.options.custom.append($(notification.options.layout.container.object).addClass('i-am-new'));
            } else {
                $('body').append($(notification.options.layout.container.object).addClass('i-am-new'));
            }
        } else {
            $(notification.options.layout.container.selector).removeClass('i-am-new');
        }

        $.notyRenderer.setLayoutCountFor(notification, +1);

        notification.show();
    };

    $.notyRenderer.createModalFor = function (notification) {
        if ($('.noty_modal').length == 0)
            $('<div/>').addClass('noty_modal').data('noty_modal_count', 0).css(notification.options.theme.modal.css).prependTo($('body')).fadeIn('fast');
    };

    $.notyRenderer.getLayoutCountFor = function (notification) {
        return $(notification.options.layout.container.selector).data('noty_layout_count') || 0;
    };

    $.notyRenderer.setLayoutCountFor = function (notification, arg) {
        return $(notification.options.layout.container.selector).data('noty_layout_count', $.notyRenderer.getLayoutCountFor(notification) + arg);
    };

    $.notyRenderer.getModalCount = function () {
        return $('.noty_modal').data('noty_modal_count') || 0;
    };

    $.notyRenderer.setModalCount = function (arg) {
        return $('.noty_modal').data('noty_modal_count', $.notyRenderer.getModalCount() + arg);
    };

    // This is for custom container
    $.fn.noty = function (options) {
        options.custom = $(this);
        return $.notyRenderer.init(options);
    };

    $.noty = {};
    $.noty.queue = [];
    $.noty.ontap = true;
    $.noty.layouts = {};
    $.noty.themes = {};
    $.noty.returns = 'object';
    $.noty.store = {};

    $.noty.get = function (id) {
        return $.noty.store.hasOwnProperty(id) ? $.noty.store[id] : false;
    };

    $.noty.close = function (id) {
        return $.noty.get(id) ? $.noty.get(id).close() : false;
    };

    $.noty.setText = function (id, text) {
        return $.noty.get(id) ? $.noty.get(id).setText(text) : false;
    };

    $.noty.setType = function (id, type) {
        return $.noty.get(id) ? $.noty.get(id).setType(type) : false;
    };

    $.noty.clearQueue = function () {
        $.noty.queue = [];
    };

    $.noty.closeAll = function () {
        $.noty.clearQueue();
        $.each($.noty.store, function (id, noty) {
            noty.close();
        });
    };

    var windowAlert = window.alert;

    $.noty.consumeAlert = function (options) {
        window.alert = function (text) {
            if (options)
                options.text = text;
            else
                options = {text:text};

            $.notyRenderer.init(options);
        };
    };

    $.noty.stopConsumeAlert = function () {
        window.alert = windowAlert;
    };

    $.noty.defaults = {
        layout:'top',
        theme:'defaultTheme',
        type:'alert',
        text:'',
        dismissQueue:true,
        template:'<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
        animation:{
            open:{height:'toggle'},
            close:{height:'toggle'},
            easing:'swing',
            speed:500
        },
        timeout:false,
        force:false,
        modal:false,
        closeWith:['click'],
        callback:{
            onShow:function () {
            },
            afterShow:function () {
            },
            onClose:function () {
            },
            afterClose:function () {
            }
        },
        buttons:false
    };

    $(window).resize(function () {
        $.each($.noty.layouts, function (index, layout) {
            layout.container.style.apply($(layout.container.selector));
        });
    });

})(jQuery);

// Helpers
function noty(options) {

    // This is for BC  -  Will be deleted on v2.2.0
    var using_old = 0
        , old_to_new = {
            'animateOpen':'animation.open',
            'animateClose':'animation.close',
            'easing':'animation.easing',
            'speed':'animation.speed',
            'onShow':'callback.onShow',
            'onShown':'callback.afterShow',
            'onClose':'callback.onClose',
            'onClosed':'callback.afterClose'
        };

    jQuery.each(options, function (key, value) {
        if (old_to_new[key]) {
            using_old++;
            var _new = old_to_new[key].split('.');

            if (!options[_new[0]]) options[_new[0]] = {};

            options[_new[0]][_new[1]] = (value) ? value : function () {
            };
            delete options[key];
        }
    });

    if (!options.closeWith) {
        options.closeWith = jQuery.noty.defaults.closeWith;
    }

    if (options.hasOwnProperty('closeButton')) {
        using_old++;
        if (options.closeButton) options.closeWith.push('button');
        delete options.closeButton;
    }

    if (options.hasOwnProperty('closeOnSelfClick')) {
        using_old++;
        if (options.closeOnSelfClick) options.closeWith.push('click');
        delete options.closeOnSelfClick;
    }

    if (options.hasOwnProperty('closeOnSelfOver')) {
        using_old++;
        if (options.closeOnSelfOver) options.closeWith.push('hover');
        delete options.closeOnSelfOver;
    }

    if (options.hasOwnProperty('custom')) {
        using_old++;
        if (options.custom.container != 'null') options.custom = options.custom.container;
    }

    if (options.hasOwnProperty('cssPrefix')) {
        using_old++;
        delete options.cssPrefix;
    }

    if (options.theme == 'noty_theme_default') {
        using_old++;
        options.theme = 'defaultTheme';
    }

    if (!options.hasOwnProperty('dismissQueue')) {
        if (options.layout == 'topLeft'
            || options.layout == 'topRight'
            || options.layout == 'bottomLeft'
            || options.layout == 'bottomRight') {
            options.dismissQueue = true;
        } else {
            options.dismissQueue = false;
        }
    }

    if (options.buttons) {
        jQuery.each(options.buttons, function (i, button) {
            if (button.click) {
                using_old++;
                button.onClick = button.click;
                delete button.click;
            }
            if (button.type) {
                using_old++;
                button.addClass = button.type;
                delete button.type;
            }
        });
    }

    if (using_old) {
        if (typeof console !== "undefined" && console.warn) {
            console.warn('You are using noty v2 with v1.x.x options. @deprecated until v2.2.0 - Please update your options.');
        }
    }

    // console.log(options);
    // End of the BC

    return jQuery.notyRenderer.init(options);
}
;

/********************************
/cms/resources/noty-master/js/noty/layouts/top.js
********************************/
;(function($) {

	$.noty.layouts.top = {
		name: 'top',
		options: {},
		container: {
			object: '<ul id="noty_top_layout_container" />',
			selector: 'ul#noty_top_layout_container',
			style: function() {
				$(this).css({
					top: 0,
					left: '5%',
					position: 'fixed',
					width: '90%',
					height: 'auto',
					margin: 0,
					padding: 0,
					listStyleType: 'none',
					zIndex: 9999999
				});
			}
		},
		parent: {
			object: '<li />',
			selector: 'li',
			css: {}
		},
		css: {
			display: 'none'
		},
		addClass: ''
	};

})(jQuery);;

/********************************
/cms/resources/noty-master/js/noty/layouts/topRight.js
********************************/
;(function($) {

	$.noty.layouts.topRight = {
		name: 'topRight',
		options: { // overrides options
			
		},
		container: {
			object: '<ul id="noty_topRight_layout_container" />',
			selector: 'ul#noty_topRight_layout_container',
			style: function() {
				$(this).css({
					top: 20,
					right: 20,
					position: 'fixed',
					width: '310px',
					height: 'auto',
					margin: 0,
					padding: 0,
					listStyleType: 'none',
					zIndex: 10000000
				});

				if (window.innerWidth < 600) {
					$(this).css({
						right: 5
					});
				}
			}
		},
		parent: {
			object: '<li />',
			selector: 'li',
			css: {}
		},
		css: {
			display: 'none',
			width: '310px'
		},
		addClass: ''
	};

})(jQuery);;

/********************************
/cms/resources/noty-master/js/noty/layouts/topLeft.js
********************************/
;(function($) {

	$.noty.layouts.topLeft = {
		name: 'topLeft',
		options: { // overrides options
			
		},
		container: {
			object: '<ul id="noty_topLeft_layout_container" />',
			selector: 'ul#noty_topLeft_layout_container',
			style: function() {
				$(this).css({
					top: 20,
					left: 20,
					position: 'fixed',
					width: '310px',
					height: 'auto',
					margin: 0,
					padding: 0,
					listStyleType: 'none',
					zIndex: 10000000
				});

				if (window.innerWidth < 600) {
					$(this).css({
						left: 5
					});
				}
			}
		},
		parent: {
			object: '<li />',
			selector: 'li',
			css: {}
		},
		css: {
			display: 'none',
			width: '310px'
		},
		addClass: ''
	};

})(jQuery);;

/********************************
/cms/resources/noty-master/js/noty/layouts/inline.js
********************************/
;(function($) {

	$.noty.layouts.inline = {
		name: 'inline',
		options: {},
		container: {
			object: '<ul id="noty_inline_layout_container" />',
			selector: 'ul#noty_inline_layout_container',
			style: function() {
				$(this).css({
					width: '100%',
					height: 'auto',
					margin: 0,
					padding: 0,
					listStyleType: 'none',
					zIndex: 9999999
				});
			}
		},
		parent: {
			object: '<li />',
			selector: 'li',
			css: {}
		},
		css: {
			display: 'none'
		},
		addClass: ''
	};

})(jQuery);;

/********************************
/cms/resources/noty-master/js/noty/layouts/center.js
********************************/
;(function($) {

	$.noty.layouts.center = {
		name: 'center',
		options: { // overrides options
			
		},
		container: {
			object: '<ul id="noty_center_layout_container" />',
			selector: 'ul#noty_center_layout_container',
			style: function() {
				$(this).css({
					position: 'fixed',
					width: '310px',
					height: 'auto',
					margin: 0,
					padding: 0,
					listStyleType: 'none',
					zIndex: 10000000
				});

				// getting hidden height
				var dupe = $(this).clone().css({visibility:"hidden", display:"block", position:"absolute", top: 0, left: 0}).attr('id', 'dupe');
				$("body").append(dupe);
				dupe.find('.i-am-closing-now').remove();
				dupe.find('li').css('display', 'block');
				var actual_height = dupe.height();
				dupe.remove();

				if ($(this).hasClass('i-am-new')) {
					$(this).css({
						left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px',
						top: ($(window).height() - actual_height) / 2 + 'px'
					});
				} else {
					$(this).animate({
						left: ($(window).width() - $(this).outerWidth(false)) / 2 + 'px',
						top: ($(window).height() - actual_height) / 2 + 'px'
					}, 500);
				}
				
			}
		},
		parent: {
			object: '<li />',
			selector: 'li',
			css: {}
		},
		css: {
			display: 'none',
			width: '310px'
		},
		addClass: ''
	};

})(jQuery);;

/********************************
/cms/resources/noty-master/js/noty/themes/default.js
********************************/
;(function($) {

	$.noty.themes.defaultTheme = {
		name: 'defaultTheme',
		helpers: {
			borderFix: function() {
				if (this.options.dismissQueue) {
					var selector = this.options.layout.container.selector + ' ' + this.options.layout.parent.selector;
					switch (this.options.layout.name) {
						case 'top':
							$(selector).css({borderRadius: '0px 0px 0px 0px'});
							$(selector).last().css({borderRadius: '0px 0px 5px 5px'}); break;
						case 'topCenter': case 'topLeft': case 'topRight':
						case 'bottomCenter': case 'bottomLeft': case 'bottomRight':
						case 'center': case 'centerLeft': case 'centerRight': case 'inline':
							$(selector).css({borderRadius: '0px 0px 0px 0px'});
							$(selector).first().css({'border-top-left-radius': '5px', 'border-top-right-radius': '5px'});
							$(selector).last().css({'border-bottom-left-radius': '5px', 'border-bottom-right-radius': '5px'}); break;
						case 'bottom':
							$(selector).css({borderRadius: '0px 0px 0px 0px'});
							$(selector).first().css({borderRadius: '5px 5px 0px 0px'}); break;
						default: break;
					}
				}
			}
		},
		modal: {
			css: {
				position: 'fixed',
				width: '100%',
				height: '100%',
				backgroundColor: '#000',
				zIndex: 10000,
				opacity: 0.6,
				display: 'none',
				left: 0,
				top: 0
			}
		},
		style: function() {

			this.$bar.css({
				overflow: 'hidden',
				background: "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAoCAYAAAAPOoFWAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPZJREFUeNq81tsOgjAMANB2ov7/7ypaN7IlIwi9rGuT8QSc9EIDAsAznxvY4pXPKr05RUE5MEVB+TyWfCEl9LZApYopCmo9C4FKSMtYoI8Bwv79aQJU4l6hXXCZrQbokJEksxHo9KMOgc6w1atHXM8K9DVC7FQnJ0i8iK3QooGgbnyKgMDygBWyYFZoqx4qS27KqLZJjA1D0jK6QJcYEQEiWv9PGkTsbqxQ8oT+ZtZB6AkdsJnQDnMoHXHLGKOgDYuCWmYhEERCI5gaamW0bnHdA3k2ltlIN+2qKRyCND0bhqSYCyTB3CAOc4WusBEIpkeBuPgJMAAX8Hs1NfqHRgAAAABJRU5ErkJggg==') repeat-x scroll left top #fff"
			});

			this.$message.css({
				fontSize: '13px',
				lineHeight: '16px',
				textAlign: 'center',
				padding: '8px 10px 9px',
				width: 'auto',
				position: 'relative'
			});

			this.$closeButton.css({
				position: 'absolute',
				top: 4, right: 4,
				width: 10, height: 10,
				background: "url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAATpJREFUeNoszrFqVFEUheG19zlz7sQ7ijMQBAvfYBqbpJCoZSAQbOwEE1IHGytbLQUJ8SUktW8gCCFJMSGSNxCmFBJO7j5rpXD6n5/P5vM53H3b3T9LOiB5AQDuDjM7BnA7DMPHDGBH0nuSzwHsRcRVRNRSysuU0i6AOwA/02w2+9Fae00SEbEh6SGAR5K+k3zWWptKepCm0+kpyRoRGyRBcpPkDsn1iEBr7drdP2VJZyQXERGSPpiZAViTBACXKaV9kqd5uVzCzO5KKb/d/UZSDwD/eyxqree1VqSu6zKAF2Z2RPJJaw0rAkjOJT0m+SuT/AbgDcmnkmBmfwAsJL1dXQ8lWY6IGwB1ZbrOOb8zs8thGP4COFwx/mE8Ho9Go9ErMzvJOW/1fY/JZIJSypqZfXX3L13X9fcDAKJct1sx3OiuAAAAAElFTkSuQmCC)",
				display: 'none',
				cursor: 'pointer'
			});

			this.$buttons.css({
				padding: 5,
				textAlign: 'right',
				borderTop: '1px solid #ccc',
				backgroundColor: '#fff'
			});

			this.$buttons.find('button').css({
				marginLeft: 5
			});

			this.$buttons.find('button:first').css({
				marginLeft: 0
			});

			this.$bar.bind({
				mouseenter: function() { $(this).find('.noty_close').fadeIn(); },
				mouseleave: function() { $(this).find('.noty_close').fadeOut(); }
			});

			switch (this.options.layout.name) {
				case 'top':
					this.$bar.css({
						borderRadius: '0px 0px 5px 5px',
						borderBottom: '2px solid #eee',
						borderLeft: '2px solid #eee',
						borderRight: '2px solid #eee',
						boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)"
					});
				break;
				case 'topCenter': case 'center': case 'bottomCenter': case 'inline':
					this.$bar.css({
						borderRadius: '5px',
						border: '1px solid #eee',
						boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)"
					});
					this.$message.css({fontSize: '13px', textAlign: 'center'});
				break;
				case 'topLeft': case 'topRight':
				case 'bottomLeft': case 'bottomRight':
				case 'centerLeft': case 'centerRight':
					this.$bar.css({
						borderRadius: '5px',
						border: '1px solid #eee',
						boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)"
					});
					this.$message.css({fontSize: '13px', textAlign: 'left'});
				break;
				case 'bottom':
					this.$bar.css({
						borderRadius: '5px 5px 0px 0px',
						borderTop: '2px solid #eee',
						borderLeft: '2px solid #eee',
						borderRight: '2px solid #eee',
						boxShadow: "0 -2px 4px rgba(0, 0, 0, 0.1)"
					});
				break;
				default:
					this.$bar.css({
						border: '2px solid #eee',
						boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)"
					});
				break;
			}

			switch (this.options.type) {
				case 'alert': case 'notification':
					this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break;
				case 'warning':
					this.$bar.css({backgroundColor: '#FFEAA8', borderColor: '#FFC237', color: '#826200'});
					this.$buttons.css({borderTop: '1px solid #FFC237'}); break;
				case 'error':
					this.$bar.css({backgroundColor: 'red', borderColor: 'darkred', color: '#FFF'});
					this.$message.css({fontWeight: 'bold'});
					this.$buttons.css({borderTop: '1px solid darkred'}); break;
				case 'information':
					this.$bar.css({backgroundColor: '#57B7E2', borderColor: '#0B90C4', color: '#FFF'});
					this.$buttons.css({borderTop: '1px solid #0B90C4'}); break;
				case 'success':
					this.$bar.css({backgroundColor: 'lightgreen', borderColor: '#50C24E', color: 'darkgreen'});
					this.$buttons.css({borderTop: '1px solid #50C24E'});break;
				default:
					this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break;
			}
		},
		callback: {
			onShow: function() { $.noty.themes.defaultTheme.helpers.borderFix.apply(this); },
			onClose: function() { $.noty.themes.defaultTheme.helpers.borderFix.apply(this); }
		}
	};

})(jQuery);
;

/********************************
/site/resources/mmenu/js/jquery.mmenu.min.all.js
********************************/
/*	
 * jQuery mmenu v5.3.2
 * @requires jQuery 1.7.0 or later
 *
 * mmenu.frebsite.nl
 *	
 * Copyright (c) Fred Heusschen
 * www.frebsite.nl
 *
 * Licensed under the MIT license:
 * http://en.wikipedia.org/wiki/MIT_License
 */
!function(e){function n(){e[t].glbl||(r={$wndw:e(window),$html:e("html"),$body:e("body")},a={},i={},l={},e.each([a,i,l],function(e,n){n.add=function(e){e=e.split(" ");for(var t=0,s=e.length;s>t;t++)n[e[t]]=n.mm(e[t])}}),a.mm=function(e){return"mm-"+e},a.add("wrapper menu panel nopanel current highest opened subopened navbar hasnavbar title btn prev next listview nolistview inset vertical selected divider spacer hidden fullsubopen"),a.umm=function(e){return"mm-"==e.slice(0,3)&&(e=e.slice(3)),e},i.mm=function(e){return"mm-"+e},i.add("parent sub"),l.mm=function(e){return e+".mm"},l.add("transitionend webkitTransitionEnd mousedown mouseup touchstart touchmove touchend click keydown"),e[t]._c=a,e[t]._d=i,e[t]._e=l,e[t].glbl=r)}var t="mmenu",s="5.3.2";if(!e[t]){e[t]=function(e,n,t){this.$menu=e,this._api=["bind","init","update","setSelected","getInstance","openPanel","closePanel","closeAllPanels"],this.opts=n,this.conf=t,this.vars={},this.cbck={},"function"==typeof this.___deprecated&&this.___deprecated(),this._initMenu(),this._initAnchors();var s=this.$menu.children(this.conf.panelNodetype);return this._initAddons(),this.init(s),"function"==typeof this.___debug&&this.___debug(),this},e[t].version=s,e[t].addons={},e[t].uniqueId=0,e[t].defaults={extensions:[],navbar:{add:!0,title:"Menu",titleLink:"panel"},onClick:{setSelected:!0},slidingSubmenus:!0},e[t].configuration={classNames:{divider:"Divider",inset:"Inset",panel:"Panel",selected:"Selected",spacer:"Spacer",vertical:"Vertical"},clone:!1,openingInterval:25,panelNodetype:"ul, ol, div",transitionDuration:400},e[t].prototype={init:function(e){e=e.not("."+a.nopanel),e=this._initPanels(e),this.trigger("init",e),this.trigger("update")},update:function(){this.trigger("update")},setSelected:function(e){this.$menu.find("."+a.listview).children().removeClass(a.selected),e.addClass(a.selected),this.trigger("setSelected",e)},openPanel:function(e){var n=e.parent();if(n.hasClass(a.vertical)){var t=n.parents("."+a.subopened);if(t.length)return this.openPanel(t.first());n.addClass(a.opened)}else{if(e.hasClass(a.current))return;var s=this.$menu.children("."+a.panel),i=s.filter("."+a.current);s.removeClass(a.highest).removeClass(a.current).not(e).not(i).not("."+a.vertical).addClass(a.hidden),e.hasClass(a.opened)?e.nextAll("."+a.opened).addClass(a.highest).removeClass(a.opened).removeClass(a.subopened):(e.addClass(a.highest),i.addClass(a.subopened)),e.removeClass(a.hidden).addClass(a.current),setTimeout(function(){e.removeClass(a.subopened).addClass(a.opened)},this.conf.openingInterval)}this.trigger("openPanel",e)},closePanel:function(e){var n=e.parent();n.hasClass(a.vertical)&&(n.removeClass(a.opened),this.trigger("closePanel",e))},closeAllPanels:function(){this.$menu.find("."+a.listview).children().removeClass(a.selected).filter("."+a.vertical).removeClass(a.opened);var e=this.$menu.children("."+a.panel),n=e.first();this.$menu.children("."+a.panel).not(n).removeClass(a.subopened).removeClass(a.opened).removeClass(a.current).removeClass(a.highest).addClass(a.hidden),this.openPanel(n)},togglePanel:function(e){var n=e.parent();n.hasClass(a.vertical)&&this[n.hasClass(a.opened)?"closePanel":"openPanel"](e)},getInstance:function(){return this},bind:function(e,n){this.cbck[e]=this.cbck[e]||[],this.cbck[e].push(n)},trigger:function(){var e=this,n=Array.prototype.slice.call(arguments),t=n.shift();if(this.cbck[t])for(var s=0,a=this.cbck[t].length;a>s;s++)this.cbck[t][s].apply(e,n)},_initMenu:function(){this.opts.offCanvas&&this.conf.clone&&(this.$menu=this.$menu.clone(!0),this.$menu.add(this.$menu.find("[id]")).filter("[id]").each(function(){e(this).attr("id",a.mm(e(this).attr("id")))})),this.$menu.contents().each(function(){3==e(this)[0].nodeType&&e(this).remove()}),this.$menu.parent().addClass(a.wrapper);var n=[a.menu];this.opts.slidingSubmenus||n.push(a.vertical),this.opts.extensions=this.opts.extensions.length?"mm-"+this.opts.extensions.join(" mm-"):"",this.opts.extensions&&n.push(this.opts.extensions),this.$menu.addClass(n.join(" "))},_initPanels:function(n){var t=this,s=this.__findAddBack(n,"ul, ol");this.__refactorClass(s,this.conf.classNames.inset,"inset").addClass(a.nolistview+" "+a.nopanel),s.not("."+a.nolistview).addClass(a.listview);var l=this.__findAddBack(n,"."+a.listview).children();this.__refactorClass(l,this.conf.classNames.selected,"selected"),this.__refactorClass(l,this.conf.classNames.divider,"divider"),this.__refactorClass(l,this.conf.classNames.spacer,"spacer"),this.__refactorClass(this.__findAddBack(n,"."+this.conf.classNames.panel),this.conf.classNames.panel,"panel");var r=e(),d=n.add(n.find("."+a.panel)).add(this.__findAddBack(n,"."+a.listview).children().children(this.conf.panelNodetype)).not("."+a.nopanel);this.__refactorClass(d,this.conf.classNames.vertical,"vertical"),this.opts.slidingSubmenus||d.addClass(a.vertical),d.each(function(){var n=e(this),s=n;n.is("ul, ol")?(n.wrap('<div class="'+a.panel+'" />'),s=n.parent()):s.addClass(a.panel);var i=n.attr("id");n.removeAttr("id"),s.attr("id",i||t.__getUniqueId()),n.hasClass(a.vertical)&&(n.removeClass(t.conf.classNames.vertical),s.add(s.parent()).addClass(a.vertical)),r=r.add(s)});var o=e("."+a.panel,this.$menu);r.each(function(){var n=e(this),s=n.parent(),l=s.children("a, span").first();if(s.is("."+a.menu)||(s.data(i.sub,n),n.data(i.parent,s)),!s.children("."+a.next).length&&s.parent().is("."+a.listview)){var r=n.attr("id"),d=e('<a class="'+a.next+'" href="#'+r+'" data-target="#'+r+'" />').insertBefore(l);l.is("span")&&d.addClass(a.fullsubopen)}if(!n.children("."+a.navbar).length&&!s.hasClass(a.vertical)){if(s.parent().is("."+a.listview))var s=s.closest("."+a.panel);else var l=s.closest("."+a.panel).find('a[href="#'+n.attr("id")+'"]').first(),s=l.closest("."+a.panel);var o=e('<div class="'+a.navbar+'" />');if(s.length){var r=s.attr("id");switch(t.opts.navbar.titleLink){case"anchor":_url=l.attr("href");break;case"panel":case"parent":_url="#"+r;break;case"none":default:_url=!1}o.append('<a class="'+a.btn+" "+a.prev+'" href="#'+r+'" data-target="#'+r+'"></a>').append('<a class="'+a.title+'"'+(_url?' href="'+_url+'"':"")+">"+l.text()+"</a>").prependTo(n),t.opts.navbar.add&&n.addClass(a.hasnavbar)}else t.opts.navbar.title&&(o.append('<a class="'+a.title+'">'+t.opts.navbar.title+"</a>").prependTo(n),t.opts.navbar.add&&n.addClass(a.hasnavbar))}});var c=this.__findAddBack(n,"."+a.listview).children("."+a.selected).removeClass(a.selected).last().addClass(a.selected);c.add(c.parentsUntil("."+a.menu,"li")).filter("."+a.vertical).addClass(a.opened).end().not("."+a.vertical).each(function(){e(this).parentsUntil("."+a.menu,"."+a.panel).not("."+a.vertical).first().addClass(a.opened).parentsUntil("."+a.menu,"."+a.panel).not("."+a.vertical).first().addClass(a.opened).addClass(a.subopened)}),c.children("."+a.panel).not("."+a.vertical).addClass(a.opened).parentsUntil("."+a.menu,"."+a.panel).not("."+a.vertical).first().addClass(a.opened).addClass(a.subopened);var h=o.filter("."+a.opened);return h.length||(h=r.first()),h.addClass(a.opened).last().addClass(a.current),r.not("."+a.vertical).not(h.last()).addClass(a.hidden).end().appendTo(this.$menu),r},_initAnchors:function(){var n=this;r.$body.on(l.click+"-oncanvas","a[href]",function(s){var i=e(this),l=!1,d=n.$menu.find(i).length;for(var o in e[t].addons)if(l=e[t].addons[o].clickAnchor.call(n,i,d))break;if(!l&&d){var c=i.attr("href");if(c.length>1&&"#"==c.slice(0,1))try{var h=e(c,n.$menu);h.is("."+a.panel)&&(l=!0,n[i.parent().hasClass(a.vertical)?"togglePanel":"openPanel"](h))}catch(u){}}if(l&&s.preventDefault(),!l&&d&&i.is("."+a.listview+" > li > a")&&!i.is('[rel="external"]')&&!i.is('[target="_blank"]')){n.__valueOrFn(n.opts.onClick.setSelected,i)&&n.setSelected(e(s.target).parent());var p=n.__valueOrFn(n.opts.onClick.preventDefault,i,"#"==c.slice(0,1));p&&s.preventDefault(),n.__valueOrFn(n.opts.onClick.blockUI,i,!p)&&r.$html.addClass(a.blocking),n.__valueOrFn(n.opts.onClick.close,i,p)&&n.close()}})},_initAddons:function(){for(var n in e[t].addons)e[t].addons[n].add.call(this),e[t].addons[n].add=function(){};for(var n in e[t].addons)e[t].addons[n].setup.call(this)},__api:function(){var n=this,t={};return e.each(this._api,function(){var e=this;t[e]=function(){var s=n[e].apply(n,arguments);return"undefined"==typeof s?t:s}}),t},__valueOrFn:function(e,n,t){return"function"==typeof e?e.call(n[0]):"undefined"==typeof e&&"undefined"!=typeof t?t:e},__refactorClass:function(e,n,t){return e.filter("."+n).removeClass(n).addClass(a[t])},__findAddBack:function(e,n){return e.find(n).add(e.filter(n))},__filterListItems:function(e){return e.not("."+a.divider).not("."+a.hidden)},__transitionend:function(e,n,t){var s=!1,a=function(){s||n.call(e[0]),s=!0};e.one(l.transitionend,a),e.one(l.webkitTransitionEnd,a),setTimeout(a,1.1*t)},__getUniqueId:function(){return a.mm(e[t].uniqueId++)}},e.fn[t]=function(s,a){return n(),s=e.extend(!0,{},e[t].defaults,s),a=e.extend(!0,{},e[t].configuration,a),this.each(function(){var n=e(this);if(!n.data(t)){var i=new e[t](n,s,a);n.data(t,i.__api())}})},e[t].support={touch:"ontouchstart"in window||navigator.msMaxTouchPoints};var a,i,l,r}}(jQuery);
/*	
 * jQuery mmenu offCanvas addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var e="mmenu",o="offCanvas";t[e].addons[o]={setup:function(){if(this.opts[o]){var n=this.opts[o],i=this.conf[o];a=t[e].glbl,this._api=t.merge(this._api,["open","close","setPage"]),("top"==n.position||"bottom"==n.position)&&(n.zposition="front"),"string"!=typeof i.pageSelector&&(i.pageSelector="> "+i.pageNodetype),a.$allMenus=(a.$allMenus||t()).add(this.$menu),this.vars.opened=!1;var r=[s.offcanvas];"left"!=n.position&&r.push(s.mm(n.position)),"back"!=n.zposition&&r.push(s.mm(n.zposition)),this.$menu.addClass(r.join(" ")).parent().removeClass(s.wrapper),this.setPage(a.$page),this._initBlocker(),this["_initWindow_"+o](),this.$menu[i.menuInjectMethod+"To"](i.menuWrapperSelector)}},add:function(){s=t[e]._c,n=t[e]._d,i=t[e]._e,s.add("offcanvas slideout modal background opening blocker page"),n.add("style"),i.add("resize")},clickAnchor:function(t){if(!this.opts[o])return!1;var e=this.$menu.attr("id");if(e&&e.length&&(this.conf.clone&&(e=s.umm(e)),t.is('[href="#'+e+'"]')))return this.open(),!0;if(a.$page){var e=a.$page.first().attr("id");return e&&e.length&&t.is('[href="#'+e+'"]')?(this.close(),!0):!1}}},t[e].defaults[o]={position:"left",zposition:"back",modal:!1,moveBackground:!0},t[e].configuration[o]={pageNodetype:"div",pageSelector:null,wrapPageIfNeeded:!0,menuWrapperSelector:"body",menuInjectMethod:"prepend"},t[e].prototype.open=function(){if(!this.vars.opened){var t=this;this._openSetup(),setTimeout(function(){t._openFinish()},this.conf.openingInterval),this.trigger("open")}},t[e].prototype._openSetup=function(){var e=this;this.closeAllOthers(),a.$page.each(function(){t(this).data(n.style,t(this).attr("style")||"")}),a.$wndw.trigger(i.resize+"-offcanvas",[!0]);var r=[s.opened];this.opts[o].modal&&r.push(s.modal),this.opts[o].moveBackground&&r.push(s.background),"left"!=this.opts[o].position&&r.push(s.mm(this.opts[o].position)),"back"!=this.opts[o].zposition&&r.push(s.mm(this.opts[o].zposition)),this.opts.extensions&&r.push(this.opts.extensions),a.$html.addClass(r.join(" ")),setTimeout(function(){e.vars.opened=!0},this.conf.openingInterval),this.$menu.addClass(s.current+" "+s.opened)},t[e].prototype._openFinish=function(){var t=this;this.__transitionend(a.$page.first(),function(){t.trigger("opened")},this.conf.transitionDuration),a.$html.addClass(s.opening),this.trigger("opening")},t[e].prototype.close=function(){if(this.vars.opened){var e=this;this.__transitionend(a.$page.first(),function(){e.$menu.removeClass(s.current).removeClass(s.opened),a.$html.removeClass(s.opened).removeClass(s.modal).removeClass(s.background).removeClass(s.mm(e.opts[o].position)).removeClass(s.mm(e.opts[o].zposition)),e.opts.extensions&&a.$html.removeClass(e.opts.extensions),a.$page.each(function(){t(this).attr("style",t(this).data(n.style))}),e.vars.opened=!1,e.trigger("closed")},this.conf.transitionDuration),a.$html.removeClass(s.opening),this.trigger("close"),this.trigger("closing")}},t[e].prototype.closeAllOthers=function(){a.$allMenus.not(this.$menu).each(function(){var o=t(this).data(e);o&&o.close&&o.close()})},t[e].prototype.setPage=function(e){var n=this,i=this.conf[o];e&&e.length||(e=a.$body.find(i.pageSelector),e.length>1&&i.wrapPageIfNeeded&&(e=e.wrapAll("<"+this.conf[o].pageNodetype+" />").parent())),e.each(function(){t(this).attr("id",t(this).attr("id")||n.__getUniqueId())}),e.addClass(s.page+" "+s.slideout),a.$page=e,this.trigger("setPage",e)},t[e].prototype["_initWindow_"+o]=function(){a.$wndw.off(i.keydown+"-offcanvas").on(i.keydown+"-offcanvas",function(t){return a.$html.hasClass(s.opened)&&9==t.keyCode?(t.preventDefault(),!1):void 0});var t=0;a.$wndw.off(i.resize+"-offcanvas").on(i.resize+"-offcanvas",function(e,o){if(1==a.$page.length&&(o||a.$html.hasClass(s.opened))){var n=a.$wndw.height();(o||n!=t)&&(t=n,a.$page.css("minHeight",n))}})},t[e].prototype._initBlocker=function(){var e=this;a.$blck||(a.$blck=t('<div id="'+s.blocker+'" class="'+s.slideout+'" />')),a.$blck.appendTo(a.$body).off(i.touchstart+"-offcanvas "+i.touchmove+"-offcanvas").on(i.touchstart+"-offcanvas "+i.touchmove+"-offcanvas",function(t){t.preventDefault(),t.stopPropagation(),a.$blck.trigger(i.mousedown+"-offcanvas")}).off(i.mousedown+"-offcanvas").on(i.mousedown+"-offcanvas",function(t){t.preventDefault(),a.$html.hasClass(s.modal)||(e.closeAllOthers(),e.close())})};var s,n,i,a}(jQuery);
/*	
 * jQuery mmenu autoHeight addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var e="mmenu",i="autoHeight";t[e].addons[i]={setup:function(){if(this.opts.offCanvas){switch(this.opts.offCanvas.position){case"left":case"right":return}var n=this,o=this.opts[i];if(this.conf[i],h=t[e].glbl,"boolean"==typeof o&&o&&(o={height:"auto"}),"object"!=typeof o&&(o={}),o=this.opts[i]=t.extend(!0,{},t[e].defaults[i],o),"auto"==o.height){this.$menu.addClass(s.autoheight);var u=function(t){var e=this.$menu.children("."+s.current);_top=parseInt(e.css("top"),10)||0,_bot=parseInt(e.css("bottom"),10)||0,this.$menu.addClass(s.measureheight),t=t||this.$menu.children("."+s.current),t.is("."+s.vertical)&&(t=t.parents("."+s.panel).not("."+s.vertical).first()),this.$menu.height(t.outerHeight()+_top+_bot).removeClass(s.measureheight)};this.bind("update",u),this.bind("openPanel",u),this.bind("closePanel",u),this.bind("open",u),h.$wndw.off(a.resize+"-autoheight").on(a.resize+"-autoheight",function(){u.call(n)})}}},add:function(){s=t[e]._c,n=t[e]._d,a=t[e]._e,s.add("autoheight measureheight"),a.add("resize")},clickAnchor:function(){}},t[e].defaults[i]={height:"default"};var s,n,a,h}(jQuery);
/*	
 * jQuery mmenu backButton addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(o){var t="mmenu",n="backButton";o[t].addons[n]={setup:function(){if(this.opts.offCanvas){var i=this,e=this.opts[n];if(this.conf[n],a=o[t].glbl,"boolean"==typeof e&&(e={close:e}),"object"!=typeof e&&(e={}),e=o.extend(!0,{},o[t].defaults[n],e),e.close){var c="#"+i.$menu.attr("id");this.bind("opened",function(){location.hash!=c&&history.pushState(null,document.title,c)}),o(window).on("popstate",function(o){a.$html.hasClass(s.opened)?(o.stopPropagation(),i.close()):location.hash==c&&(o.stopPropagation(),i.open())})}}},add:function(){return window.history&&window.history.pushState?(s=o[t]._c,i=o[t]._d,e=o[t]._e,void 0):(o[t].addons[n].setup=function(){},void 0)},clickAnchor:function(){}},o[t].defaults[n]={close:!1};var s,i,e,a}(jQuery);
/*	
 * jQuery mmenu counters addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var n="mmenu",e="counters";t[n].addons[e]={setup:function(){var c=this,o=this.opts[e];this.conf[e],s=t[n].glbl,"boolean"==typeof o&&(o={add:o,update:o}),"object"!=typeof o&&(o={}),o=this.opts[e]=t.extend(!0,{},t[n].defaults[e],o),this.bind("init",function(n){this.__refactorClass(t("em",n),this.conf.classNames[e].counter,"counter")}),o.add&&this.bind("init",function(n){n.each(function(){var n=t(this).data(a.parent);n&&(n.children("em."+i.counter).length||n.prepend(t('<em class="'+i.counter+'" />')))})}),o.update&&this.bind("update",function(){this.$menu.find("."+i.panel).each(function(){var n=t(this),e=n.data(a.parent);if(e){var s=e.children("em."+i.counter);s.length&&(n=n.children("."+i.listview),n.length&&s.html(c.__filterListItems(n.children()).length))}})})},add:function(){i=t[n]._c,a=t[n]._d,c=t[n]._e,i.add("counter search noresultsmsg")},clickAnchor:function(){}},t[n].defaults[e]={add:!1,update:!1},t[n].configuration.classNames[e]={counter:"Counter"};var i,a,c,s}(jQuery);
/*	
 * jQuery mmenu dividers addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(i){var e="mmenu",s="dividers";i[e].addons[s]={setup:function(){var n=this,a=this.opts[s];if(this.conf[s],l=i[e].glbl,"boolean"==typeof a&&(a={add:a,fixed:a}),"object"!=typeof a&&(a={}),a=this.opts[s]=i.extend(!0,{},i[e].defaults[s],a),this.bind("init",function(){this.__refactorClass(i("li",this.$menu),this.conf.classNames[s].collapsed,"collapsed")}),a.add&&this.bind("init",function(e){switch(a.addTo){case"panels":var s=e;break;default:var s=i(a.addTo,this.$menu).filter("."+d.panel)}i("."+d.divider,s).remove(),s.find("."+d.listview).not("."+d.vertical).each(function(){var e="";n.__filterListItems(i(this).children()).each(function(){var s=i.trim(i(this).children("a, span").text()).slice(0,1).toLowerCase();s!=e&&s.length&&(e=s,i('<li class="'+d.divider+'">'+s+"</li>").insertBefore(this))})})}),a.collapse&&this.bind("init",function(e){i("."+d.divider,e).each(function(){var e=i(this),s=e.nextUntil("."+d.divider,"."+d.collapsed);s.length&&(e.children("."+d.subopen).length||(e.wrapInner("<span />"),e.prepend('<a href="#" class="'+d.subopen+" "+d.fullsubopen+'" />')))})}),a.fixed){var o=function(e){e=e||this.$menu.children("."+d.current);var s=e.find("."+d.divider).not("."+d.hidden);if(s.length){this.$menu.addClass(d.hasdividers);var n=e.scrollTop()||0,t="";e.is(":visible")&&e.find("."+d.divider).not("."+d.hidden).each(function(){i(this).position().top+n<n+1&&(t=i(this).text())}),this.$fixeddivider.text(t)}else this.$menu.removeClass(d.hasdividers)};this.$fixeddivider=i('<ul class="'+d.listview+" "+d.fixeddivider+'"><li class="'+d.divider+'"></li></ul>').prependTo(this.$menu).children(),this.bind("openPanel",o),this.bind("init",function(e){e.off(t.scroll+"-dividers "+t.touchmove+"-dividers").on(t.scroll+"-dividers "+t.touchmove+"-dividers",function(){o.call(n,i(this))})})}},add:function(){d=i[e]._c,n=i[e]._d,t=i[e]._e,d.add("collapsed uncollapsed fixeddivider hasdividers"),t.add("scroll")},clickAnchor:function(i,e){if(this.opts[s].collapse&&e){var n=i.parent();if(n.is("."+d.divider)){var t=n.nextUntil("."+d.divider,"."+d.collapsed);return n.toggleClass(d.opened),t[n.hasClass(d.opened)?"addClass":"removeClass"](d.uncollapsed),!0}}return!1}},i[e].defaults[s]={add:!1,addTo:"panels",fixed:!1,collapse:!1},i[e].configuration.classNames[s]={collapsed:"Collapsed"};var d,n,t,l}(jQuery);
/*	
 * jQuery mmenu dragOpen addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){function t(e,t,n){return t>e&&(e=t),e>n&&(e=n),e}var n="mmenu",o="dragOpen";e[n].addons[o]={setup:function(){if(this.opts.offCanvas){var i=this,a=this.opts[o],p=this.conf[o];if(r=e[n].glbl,"boolean"==typeof a&&(a={open:a}),"object"!=typeof a&&(a={}),a=this.opts[o]=e.extend(!0,{},e[n].defaults[o],a),a.open){var d,f,c,u,h,l={},m=0,g=!1,v=!1,w=0,_=0;switch(this.opts.offCanvas.position){case"left":case"right":l.events="panleft panright",l.typeLower="x",l.typeUpper="X",v="width";break;case"top":case"bottom":l.events="panup pandown",l.typeLower="y",l.typeUpper="Y",v="height"}switch(this.opts.offCanvas.position){case"right":case"bottom":l.negative=!0,u=function(e){e>=r.$wndw[v]()-a.maxStartPos&&(m=1)};break;default:l.negative=!1,u=function(e){e<=a.maxStartPos&&(m=1)}}switch(this.opts.offCanvas.position){case"left":l.open_dir="right",l.close_dir="left";break;case"right":l.open_dir="left",l.close_dir="right";break;case"top":l.open_dir="down",l.close_dir="up";break;case"bottom":l.open_dir="up",l.close_dir="down"}switch(this.opts.offCanvas.zposition){case"front":h=function(){return this.$menu};break;default:h=function(){return e("."+s.slideout)}}var b=this.__valueOrFn(a.pageNode,this.$menu,r.$page);"string"==typeof b&&(b=e(b));var y=new Hammer(b[0],a.vendors.hammer);y.on("panstart",function(e){u(e.center[l.typeLower]),r.$slideOutNodes=h(),g=l.open_dir}).on(l.events+" panend",function(e){m>0&&e.preventDefault()}).on(l.events,function(e){if(d=e["delta"+l.typeUpper],l.negative&&(d=-d),d!=w&&(g=d>=w?l.open_dir:l.close_dir),w=d,w>a.threshold&&1==m){if(r.$html.hasClass(s.opened))return;m=2,i._openSetup(),i.trigger("opening"),r.$html.addClass(s.dragging),_=t(r.$wndw[v]()*p[v].perc,p[v].min,p[v].max)}2==m&&(f=t(w,10,_)-("front"==i.opts.offCanvas.zposition?_:0),l.negative&&(f=-f),c="translate"+l.typeUpper+"("+f+"px )",r.$slideOutNodes.css({"-webkit-transform":"-webkit-"+c,transform:c}))}).on("panend",function(){2==m&&(r.$html.removeClass(s.dragging),r.$slideOutNodes.css("transform",""),i[g==l.open_dir?"_openFinish":"close"]()),m=0})}}},add:function(){return"function"!=typeof Hammer||Hammer.VERSION<2?(e[n].addons[o].setup=function(){},void 0):(s=e[n]._c,i=e[n]._d,a=e[n]._e,s.add("dragging"),void 0)},clickAnchor:function(){}},e[n].defaults[o]={open:!1,maxStartPos:100,threshold:50,vendors:{hammer:{}}},e[n].configuration[o]={width:{perc:.8,min:140,max:440},height:{perc:.8,min:140,max:880}};var s,i,a,r}(jQuery);
/*	
 * jQuery mmenu fixedElements addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(i){var s="mmenu",n="fixedElements";i[s].addons[n]={setup:function(){if(this.opts.offCanvas){this.opts[n],this.conf[n],o=i[s].glbl;var a=function(i){var s=this.conf.classNames[n].fixed;this.__refactorClass(i.find("."+s),s,"slideout").appendTo(o.$body)};a.call(this,o.$page),this.bind("setPage",a)}},add:function(){a=i[s]._c,t=i[s]._d,e=i[s]._e,a.add("fixed")},clickAnchor:function(){}},i[s].configuration.classNames[n]={fixed:"Fixed"};var a,t,e,o}(jQuery);
/*	
 * jQuery mmenu iconPanels addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){var n="mmenu",i="iconPanels";e[n].addons[i]={setup:function(){var a=this,l=this.opts[i];if(this.conf[i],d=e[n].glbl,"boolean"==typeof l&&(l={add:l}),"number"==typeof l&&(l={add:!0,visible:l}),"object"!=typeof l&&(l={}),l=this.opts[i]=e.extend(!0,{},e[n].defaults[i],l),l.visible++,l.add){this.$menu.addClass(s.iconpanel);for(var t=[],o=0;o<=l.visible;o++)t.push(s.iconpanel+"-"+o);t=t.join(" ");var c=function(n){var i=a.$menu.children("."+s.panel).removeClass(t),d=i.filter("."+s.subopened);d.removeClass(s.hidden).add(n).slice(-l.visible).each(function(n){e(this).addClass(s.iconpanel+"-"+n)})};this.bind("openPanel",c),this.bind("init",function(n){c.call(a,a.$menu.children("."+s.current)),l.hideNavbars&&n.removeClass(s.hasnavbar),n.each(function(){e(this).children("."+s.subblocker).length||e(this).prepend('<a href="#'+e(this).closest("."+s.panel).attr("id")+'" class="'+s.subblocker+'" />')})})}},add:function(){s=e[n]._c,a=e[n]._d,l=e[n]._e,s.add("iconpanel subblocker")},clickAnchor:function(){}},e[n].defaults[i]={add:!1,visible:3,hideNavbars:!1};var s,a,l,d}(jQuery);
/*	
 * jQuery mmenu navbar addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(n){var a="mmenu",e="navbars";n[a].addons[e]={setup:function(){var r=this,i=this.opts[e],c=this.conf[e];if(s=n[a].glbl,"undefined"!=typeof i){i instanceof Array||(i=[i]);var d={};n.each(i,function(s){var o=i[s];"boolean"==typeof o&&o&&(o={}),"object"!=typeof o&&(o={}),"undefined"==typeof o.content&&(o.content=["prev","title"]),o.content instanceof Array||(o.content=[o.content]),o=n.extend(!0,{},r.opts.navbar,o);var l=o.position,h=o.height;"number"!=typeof h&&(h=1),h=Math.min(4,Math.max(1,h)),"bottom"!=l&&(l="top"),d[l]||(d[l]=0),d[l]++;var f=n("<div />").addClass(t.navbar+" "+t.navbar+"-"+l+" "+t.navbar+"-"+l+"-"+d[l]+" "+t.navbar+"-size-"+h);d[l]+=h-1;for(var v=0,u=o.content.length;u>v;v++){var p=n[a].addons[e][o.content[v]]||!1;p?p.call(r,f,o,c):(p=o.content[v],p instanceof n||(p=n(o.content[v])),p.each(function(){f.append(n(this))}))}var b=Math.ceil(f.children().not("."+t.btn).length/h);b>1&&f.addClass(t.navbar+"-content-"+b),f.children("."+t.btn).length&&f.addClass(t.hasbtns),f.prependTo(r.$menu)});for(var o in d)r.$menu.addClass(t.hasnavbar+"-"+o+"-"+d[o])}},add:function(){t=n[a]._c,r=n[a]._d,i=n[a]._e,t.add("close hasbtns")},clickAnchor:function(){}},n[a].configuration[e]={breadcrumbSeparator:"/"},n[a].configuration.classNames[e]={panelTitle:"Title",panelNext:"Next",panelPrev:"Prev"};var t,r,i,s}(jQuery),/*	
 * jQuery mmenu navbar addon breadcrumbs content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="breadcrumbs";n[a].addons[e][t]=function(e,t,r){var i=n[a]._c,s=n[a]._d;i.add("breadcrumbs separator"),e.append('<span class="'+i.breadcrumbs+'"></span>'),this.bind("init",function(a){a.removeClass(i.hasnavbar).each(function(){for(var a=[],e=n(this),t=n('<span class="'+i.breadcrumbs+'"></span>'),c=n(this).children().first(),d=!0;c&&c.length;){c.is("."+i.panel)||(c=c.closest("."+i.panel));var o=c.children("."+i.navbar).children("."+i.title).text();a.unshift(d?"<span>"+o+"</span>":'<a href="#'+c.attr("id")+'">'+o+"</a>"),d=!1,c=c.data(s.parent)}t.append(a.join('<span class="'+i.separator+'">'+r.breadcrumbSeparator+"</span>")).appendTo(e.children("."+i.navbar))})});var c=function(){var n=this.$menu.children("."+i.current),a=e.find("."+i.breadcrumbs),t=n.children("."+i.navbar).children("."+i.breadcrumbs);a.html(t.html())};this.bind("openPanel",c),this.bind("init",c)}}(jQuery),/*	
 * jQuery mmenu navbar addon close content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="close";n[a].addons[e][t]=function(e){var t=n[a]._c,r=n[a].glbl;e.append('<a class="'+t.close+" "+t.btn+'" href="#"></a>');var i=function(n){e.find("."+t.close).attr("href","#"+n.attr("id"))};i.call(this,r.$page),this.bind("setPage",i)}}(jQuery),/*	
 * jQuery mmenu navbar addon next content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="next";n[a].addons[e][t]=function(t){var r=n[a]._c;t.append('<a class="'+r.next+" "+r.btn+'" href="#"></a>');var i=function(n){n=n||this.$menu.children("."+r.current);var a=t.find("."+r.next),i=n.find("."+this.conf.classNames[e].panelNext),s=i.attr("href"),c=i.html();a[s?"attr":"removeAttr"]("href",s),a[s||c?"removeClass":"addClass"](r.hidden),a.html(c)};this.bind("openPanel",i),this.bind("init",function(){i.call(this)})}}(jQuery),/*	
 * jQuery mmenu navbar addon prev content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="prev";n[a].addons[e][t]=function(t){var r=n[a]._c;t.append('<a class="'+r.prev+" "+r.btn+'" href="#"></a>'),this.bind("init",function(n){n.removeClass(r.hasnavbar)});var i=function(){var n=this.$menu.children("."+r.current),a=t.find("."+r.prev),i=n.find("."+this.conf.classNames[e].panelPrev);i.length||(i=n.children("."+r.navbar).children("."+r.prev));var s=i.attr("href"),c=i.html();a[s?"attr":"removeAttr"]("href",s),a[s||c?"removeClass":"addClass"](r.hidden),a.html(c)};this.bind("openPanel",i),this.bind("init",i)}}(jQuery),/*	
 * jQuery mmenu navbar addon searchfield content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="searchfield";n[a].addons[e][t]=function(e){var t=n[a]._c,r=n('<div class="'+t.search+'" />').appendTo(e);"object"!=typeof this.opts.searchfield&&(this.opts.searchfield={}),this.opts.searchfield.add=!0,this.opts.searchfield.addTo=r}}(jQuery),/*	
 * jQuery mmenu navbar addon title content
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
function(n){var a="mmenu",e="navbars",t="title";n[a].addons[e][t]=function(t,r){var i=n[a]._c;t.append('<a class="'+i.title+'"></a>');var s=function(n){n=n||this.$menu.children("."+i.current);var a=t.find("."+i.title),s=n.find("."+this.conf.classNames[e].panelTitle);s.length||(s=n.children("."+i.navbar).children("."+i.title));var c=s.attr("href"),d=s.html()||r.title;a[c?"attr":"removeAttr"]("href",c),a[c||d?"removeClass":"addClass"](i.hidden),a.html(d)};this.bind("openPanel",s),this.bind("init",function(){s.call(this)})}}(jQuery);
/*	
 * jQuery mmenu searchfield addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){function s(e){switch(e){case 9:case 16:case 17:case 18:case 37:case 38:case 39:case 40:return!0}return!1}var n="mmenu",a="searchfield";e[n].addons[a]={setup:function(){var o=this,d=this.opts[a],c=this.conf[a];r=e[n].glbl,"boolean"==typeof d&&(d={add:d}),"object"!=typeof d&&(d={}),d=this.opts[a]=e.extend(!0,{},e[n].defaults[a],d),this.bind("close",function(){this.$menu.find("."+t.search).find("input").blur()}),this.bind("init",function(n){if(d.add){switch(d.addTo){case"panels":var a=n;break;default:var a=e(d.addTo,this.$menu)}a.each(function(){var s=e(this);if(!s.is("."+t.panel)||!s.is("."+t.vertical)){if(!s.children("."+t.search).length){var n=c.form?"form":"div",a=e("<"+n+' class="'+t.search+'" />');if(c.form&&"object"==typeof c.form)for(var l in c.form)a.attr(l,c.form[l]);a.append('<input placeholder="'+d.placeholder+'" type="text" autocomplete="off" />'),s.hasClass(t.search)?s.replaceWith(a):s.prepend(a).addClass(t.hassearch)}if(d.noResults){var i=s.closest("."+t.panel).length;if(i||(s=o.$menu.children("."+t.panel).first()),!s.children("."+t.noresultsmsg).length){var r=s.children("."+t.listview).first();e('<div class="'+t.noresultsmsg+'" />').append(d.noResults)[r.length?"insertAfter":"prependTo"](r.length?r:s)}}}}),d.search&&e("."+t.search,this.$menu).each(function(){var n=e(this),a=n.closest("."+t.panel).length;if(a)var r=n.closest("."+t.panel),c=r;else var r=e("."+t.panel,o.$menu),c=o.$menu;var h=n.children("input"),u=o.__findAddBack(r,"."+t.listview).children("li"),f=u.filter("."+t.divider),p=o.__filterListItems(u),v="> a",m=v+", > span",b=function(){var s=h.val().toLowerCase();r.scrollTop(0),p.add(f).addClass(t.hidden).find("."+t.fullsubopensearch).removeClass(t.fullsubopen).removeClass(t.fullsubopensearch),p.each(function(){var n=e(this),a=v;(d.showTextItems||d.showSubPanels&&n.find("."+t.next))&&(a=m),e(a,n).text().toLowerCase().indexOf(s)>-1&&n.add(n.prevAll("."+t.divider).first()).removeClass(t.hidden)}),d.showSubPanels&&r.each(function(){var s=e(this);o.__filterListItems(s.find("."+t.listview).children()).each(function(){var s=e(this),n=s.data(l.sub);s.removeClass(t.nosubresults),n&&n.find("."+t.listview).children().removeClass(t.hidden)})}),e(r.get().reverse()).each(function(s){var n=e(this),i=n.data(l.parent);i&&(o.__filterListItems(n.find("."+t.listview).children()).length?(i.hasClass(t.hidden)&&i.children("."+t.next).not("."+t.fullsubopen).addClass(t.fullsubopen).addClass(t.fullsubopensearch),i.removeClass(t.hidden).removeClass(t.nosubresults).prevAll("."+t.divider).first().removeClass(t.hidden)):a||(n.hasClass(t.opened)&&setTimeout(function(){o.openPanel(i.closest("."+t.panel))},1.5*(s+1)*o.conf.openingInterval),i.addClass(t.nosubresults)))}),c[p.not("."+t.hidden).length?"removeClass":"addClass"](t.noresults),this.update()};h.off(i.keyup+"-searchfield "+i.change+"-searchfield").on(i.keyup+"-searchfield",function(e){s(e.keyCode)||b.call(o)}).on(i.change+"-searchfield",function(){b.call(o)})})}})},add:function(){t=e[n]._c,l=e[n]._d,i=e[n]._e,t.add("search hassearch noresultsmsg noresults nosubresults fullsubopensearch"),i.add("change keyup")},clickAnchor:function(){}},e[n].defaults[a]={add:!1,addTo:"panels",search:!0,placeholder:"Search",noResults:"No results found.",showTextItems:!1,showSubPanels:!0},e[n].configuration[a]={form:!1};var t,l,i,r}(jQuery);
/*	
 * jQuery mmenu sectionIndexer addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(e){var a="mmenu",r="sectionIndexer";e[a].addons[r]={setup:function(){var i=this,d=this.opts[r];this.conf[r],s=e[a].glbl,"boolean"==typeof d&&(d={add:d}),"object"!=typeof d&&(d={}),d=this.opts[r]=e.extend(!0,{},e[a].defaults[r],d),this.bind("init",function(a){if(d.add){switch(d.addTo){case"panels":var r=a;break;default:var r=e(d.addTo,this.$menu).filter("."+n.panel)}r.find("."+n.divider).closest("."+n.panel).addClass(n.hasindexer)}if(!this.$indexer&&this.$menu.children("."+n.hasindexer).length){this.$indexer=e('<div class="'+n.indexer+'" />').prependTo(this.$menu).append('<a href="#a">a</a><a href="#b">b</a><a href="#c">c</a><a href="#d">d</a><a href="#e">e</a><a href="#f">f</a><a href="#g">g</a><a href="#h">h</a><a href="#i">i</a><a href="#j">j</a><a href="#k">k</a><a href="#l">l</a><a href="#m">m</a><a href="#n">n</a><a href="#o">o</a><a href="#p">p</a><a href="#q">q</a><a href="#r">r</a><a href="#s">s</a><a href="#t">t</a><a href="#u">u</a><a href="#v">v</a><a href="#w">w</a><a href="#x">x</a><a href="#y">y</a><a href="#z">z</a>'),this.$indexer.children().on(t.mouseover+"-sectionindexer "+n.touchstart+"-sectionindexer",function(){var a=e(this).attr("href").slice(1),r=i.$menu.children("."+n.current),t=r.find("."+n.listview),s=!1,d=r.scrollTop(),h=t.position().top+parseInt(t.css("margin-top"),10)+parseInt(t.css("padding-top"),10)+d;r.scrollTop(0),t.children("."+n.divider).not("."+n.hidden).each(function(){s===!1&&a==e(this).text().slice(0,1).toLowerCase()&&(s=e(this).position().top+h)}),r.scrollTop(s!==!1?s:d)});var s=function(e){i.$menu[(e.hasClass(n.hasindexer)?"add":"remove")+"Class"](n.hasindexer)};this.bind("openPanel",s),s.call(this,this.$menu.children("."+n.current))}})},add:function(){n=e[a]._c,i=e[a]._d,t=e[a]._e,n.add("indexer hasindexer"),t.add("mouseover touchstart")},clickAnchor:function(e){return e.parent().is("."+n.indexer)?!0:void 0}},e[a].defaults[r]={add:!1,addTo:"panels"};var n,i,t,s}(jQuery);
/*	
 * jQuery mmenu toggles addon
 * mmenu.frebsite.nl
 *
 * Copyright (c) Fred Heusschen
 */
!function(t){var e="mmenu",c="toggles";t[e].addons[c]={setup:function(){var n=this;this.opts[c],this.conf[c],l=t[e].glbl,this.bind("init",function(e){this.__refactorClass(t("input",e),this.conf.classNames[c].toggle,"toggle"),this.__refactorClass(t("input",e),this.conf.classNames[c].check,"check"),t("input."+s.toggle+", input."+s.check,e).each(function(){var e=t(this),c=e.closest("li"),i=e.hasClass(s.toggle)?"toggle":"check",l=e.attr("id")||n.__getUniqueId();c.children('label[for="'+l+'"]').length||(e.attr("id",l),c.prepend(e),t('<label for="'+l+'" class="'+s[i]+'"></label>').insertBefore(c.children("a, span").last()))})})},add:function(){s=t[e]._c,n=t[e]._d,i=t[e]._e,s.add("toggle check")},clickAnchor:function(){}},t[e].configuration.classNames[c]={toggle:"Toggle",check:"Check"};var s,n,i,l}(jQuery);;

/********************************
/site/resources/slick/slick.min.js
********************************/
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.5.9
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):"undefined"!=typeof exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){"use strict";var b=window.Slick||{};b=function(){function c(c,d){var f,e=this;e.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:a(c),appendDots:a(c),arrows:!0,asNavFor:null,prevArrow:'<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',nextArrow:'<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(a,b){return'<button type="button" data-role="none" role="button" aria-required="false" tabindex="0">'+(b+1)+"</button>"},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!1,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},e.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},a.extend(e,e.initials),e.activeBreakpoint=null,e.animType=null,e.animProp=null,e.breakpoints=[],e.breakpointSettings=[],e.cssTransitions=!1,e.hidden="hidden",e.paused=!1,e.positionProp=null,e.respondTo=null,e.rowCount=1,e.shouldClick=!0,e.$slider=a(c),e.$slidesCache=null,e.transformType=null,e.transitionType=null,e.visibilityChange="visibilitychange",e.windowWidth=0,e.windowTimer=null,f=a(c).data("slick")||{},e.options=a.extend({},e.defaults,f,d),e.currentSlide=e.options.initialSlide,e.originalSettings=e.options,"undefined"!=typeof document.mozHidden?(e.hidden="mozHidden",e.visibilityChange="mozvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(e.hidden="webkitHidden",e.visibilityChange="webkitvisibilitychange"),e.autoPlay=a.proxy(e.autoPlay,e),e.autoPlayClear=a.proxy(e.autoPlayClear,e),e.changeSlide=a.proxy(e.changeSlide,e),e.clickHandler=a.proxy(e.clickHandler,e),e.selectHandler=a.proxy(e.selectHandler,e),e.setPosition=a.proxy(e.setPosition,e),e.swipeHandler=a.proxy(e.swipeHandler,e),e.dragHandler=a.proxy(e.dragHandler,e),e.keyHandler=a.proxy(e.keyHandler,e),e.autoPlayIterator=a.proxy(e.autoPlayIterator,e),e.instanceUid=b++,e.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,e.registerBreakpoints(),e.init(!0),e.checkResponsive(!0)}var b=0;return c}(),b.prototype.addSlide=b.prototype.slickAdd=function(b,c,d){var e=this;if("boolean"==typeof c)d=c,c=null;else if(0>c||c>=e.slideCount)return!1;e.unload(),"number"==typeof c?0===c&&0===e.$slides.length?a(b).appendTo(e.$slideTrack):d?a(b).insertBefore(e.$slides.eq(c)):a(b).insertAfter(e.$slides.eq(c)):d===!0?a(b).prependTo(e.$slideTrack):a(b).appendTo(e.$slideTrack),e.$slides=e.$slideTrack.children(this.options.slide),e.$slideTrack.children(this.options.slide).detach(),e.$slideTrack.append(e.$slides),e.$slides.each(function(b,c){a(c).attr("data-slick-index",b)}),e.$slidesCache=e.$slides,e.reinit()},b.prototype.animateHeight=function(){var a=this;if(1===a.options.slidesToShow&&a.options.adaptiveHeight===!0&&a.options.vertical===!1){var b=a.$slides.eq(a.currentSlide).outerHeight(!0);a.$list.animate({height:b},a.options.speed)}},b.prototype.animateSlide=function(b,c){var d={},e=this;e.animateHeight(),e.options.rtl===!0&&e.options.vertical===!1&&(b=-b),e.transformsEnabled===!1?e.options.vertical===!1?e.$slideTrack.animate({left:b},e.options.speed,e.options.easing,c):e.$slideTrack.animate({top:b},e.options.speed,e.options.easing,c):e.cssTransitions===!1?(e.options.rtl===!0&&(e.currentLeft=-e.currentLeft),a({animStart:e.currentLeft}).animate({animStart:b},{duration:e.options.speed,easing:e.options.easing,step:function(a){a=Math.ceil(a),e.options.vertical===!1?(d[e.animType]="translate("+a+"px, 0px)",e.$slideTrack.css(d)):(d[e.animType]="translate(0px,"+a+"px)",e.$slideTrack.css(d))},complete:function(){c&&c.call()}})):(e.applyTransition(),b=Math.ceil(b),e.options.vertical===!1?d[e.animType]="translate3d("+b+"px, 0px, 0px)":d[e.animType]="translate3d(0px,"+b+"px, 0px)",e.$slideTrack.css(d),c&&setTimeout(function(){e.disableTransition(),c.call()},e.options.speed))},b.prototype.asNavFor=function(b){var c=this,d=c.options.asNavFor;d&&null!==d&&(d=a(d).not(c.$slider)),null!==d&&"object"==typeof d&&d.each(function(){var c=a(this).slick("getSlick");c.unslicked||c.slideHandler(b,!0)})},b.prototype.applyTransition=function(a){var b=this,c={};b.options.fade===!1?c[b.transitionType]=b.transformType+" "+b.options.speed+"ms "+b.options.cssEase:c[b.transitionType]="opacity "+b.options.speed+"ms "+b.options.cssEase,b.options.fade===!1?b.$slideTrack.css(c):b.$slides.eq(a).css(c)},b.prototype.autoPlay=function(){var a=this;a.autoPlayTimer&&clearInterval(a.autoPlayTimer),a.slideCount>a.options.slidesToShow&&a.paused!==!0&&(a.autoPlayTimer=setInterval(a.autoPlayIterator,a.options.autoplaySpeed))},b.prototype.autoPlayClear=function(){var a=this;a.autoPlayTimer&&clearInterval(a.autoPlayTimer)},b.prototype.autoPlayIterator=function(){var a=this;a.options.infinite===!1?1===a.direction?(a.currentSlide+1===a.slideCount-1&&(a.direction=0),a.slideHandler(a.currentSlide+a.options.slidesToScroll)):(a.currentSlide-1===0&&(a.direction=1),a.slideHandler(a.currentSlide-a.options.slidesToScroll)):a.slideHandler(a.currentSlide+a.options.slidesToScroll)},b.prototype.buildArrows=function(){var b=this;b.options.arrows===!0&&(b.$prevArrow=a(b.options.prevArrow).addClass("slick-arrow"),b.$nextArrow=a(b.options.nextArrow).addClass("slick-arrow"),b.slideCount>b.options.slidesToShow?(b.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),b.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),b.htmlExpr.test(b.options.prevArrow)&&b.$prevArrow.prependTo(b.options.appendArrows),b.htmlExpr.test(b.options.nextArrow)&&b.$nextArrow.appendTo(b.options.appendArrows),b.options.infinite!==!0&&b.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):b.$prevArrow.add(b.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},b.prototype.buildDots=function(){var c,d,b=this;if(b.options.dots===!0&&b.slideCount>b.options.slidesToShow){for(d='<ul class="'+b.options.dotsClass+'">',c=0;c<=b.getDotCount();c+=1)d+="<li>"+b.options.customPaging.call(this,b,c)+"</li>";d+="</ul>",b.$dots=a(d).appendTo(b.options.appendDots),b.$dots.find("li").first().addClass("slick-active").attr("aria-hidden","false")}},b.prototype.buildOut=function(){var b=this;b.$slides=b.$slider.children(b.options.slide+":not(.slick-cloned)").addClass("slick-slide"),b.slideCount=b.$slides.length,b.$slides.each(function(b,c){a(c).attr("data-slick-index",b).data("originalStyling",a(c).attr("style")||"")}),b.$slider.addClass("slick-slider"),b.$slideTrack=0===b.slideCount?a('<div class="slick-track"/>').appendTo(b.$slider):b.$slides.wrapAll('<div class="slick-track"/>').parent(),b.$list=b.$slideTrack.wrap('<div aria-live="polite" class="slick-list"/>').parent(),b.$slideTrack.css("opacity",0),(b.options.centerMode===!0||b.options.swipeToSlide===!0)&&(b.options.slidesToScroll=1),a("img[data-lazy]",b.$slider).not("[src]").addClass("slick-loading"),b.setupInfinite(),b.buildArrows(),b.buildDots(),b.updateDots(),b.setSlideClasses("number"==typeof b.currentSlide?b.currentSlide:0),b.options.draggable===!0&&b.$list.addClass("draggable")},b.prototype.buildRows=function(){var b,c,d,e,f,g,h,a=this;if(e=document.createDocumentFragment(),g=a.$slider.children(),a.options.rows>1){for(h=a.options.slidesPerRow*a.options.rows,f=Math.ceil(g.length/h),b=0;f>b;b++){var i=document.createElement("div");for(c=0;c<a.options.rows;c++){var j=document.createElement("div");for(d=0;d<a.options.slidesPerRow;d++){var k=b*h+(c*a.options.slidesPerRow+d);g.get(k)&&j.appendChild(g.get(k))}i.appendChild(j)}e.appendChild(i)}a.$slider.html(e),a.$slider.children().children().children().css({width:100/a.options.slidesPerRow+"%",display:"inline-block"})}},b.prototype.checkResponsive=function(b,c){var e,f,g,d=this,h=!1,i=d.$slider.width(),j=window.innerWidth||a(window).width();if("window"===d.respondTo?g=j:"slider"===d.respondTo?g=i:"min"===d.respondTo&&(g=Math.min(j,i)),d.options.responsive&&d.options.responsive.length&&null!==d.options.responsive){f=null;for(e in d.breakpoints)d.breakpoints.hasOwnProperty(e)&&(d.originalSettings.mobileFirst===!1?g<d.breakpoints[e]&&(f=d.breakpoints[e]):g>d.breakpoints[e]&&(f=d.breakpoints[e]));null!==f?null!==d.activeBreakpoint?(f!==d.activeBreakpoint||c)&&(d.activeBreakpoint=f,"unslick"===d.breakpointSettings[f]?d.unslick(f):(d.options=a.extend({},d.originalSettings,d.breakpointSettings[f]),b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b)),h=f):(d.activeBreakpoint=f,"unslick"===d.breakpointSettings[f]?d.unslick(f):(d.options=a.extend({},d.originalSettings,d.breakpointSettings[f]),b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b)),h=f):null!==d.activeBreakpoint&&(d.activeBreakpoint=null,d.options=d.originalSettings,b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b),h=f),b||h===!1||d.$slider.trigger("breakpoint",[d,h])}},b.prototype.changeSlide=function(b,c){var f,g,h,d=this,e=a(b.target);switch(e.is("a")&&b.preventDefault(),e.is("li")||(e=e.closest("li")),h=d.slideCount%d.options.slidesToScroll!==0,f=h?0:(d.slideCount-d.currentSlide)%d.options.slidesToScroll,b.data.message){case"previous":g=0===f?d.options.slidesToScroll:d.options.slidesToShow-f,d.slideCount>d.options.slidesToShow&&d.slideHandler(d.currentSlide-g,!1,c);break;case"next":g=0===f?d.options.slidesToScroll:f,d.slideCount>d.options.slidesToShow&&d.slideHandler(d.currentSlide+g,!1,c);break;case"index":var i=0===b.data.index?0:b.data.index||e.index()*d.options.slidesToScroll;d.slideHandler(d.checkNavigable(i),!1,c),e.children().trigger("focus");break;default:return}},b.prototype.checkNavigable=function(a){var c,d,b=this;if(c=b.getNavigableIndexes(),d=0,a>c[c.length-1])a=c[c.length-1];else for(var e in c){if(a<c[e]){a=d;break}d=c[e]}return a},b.prototype.cleanUpEvents=function(){var b=this;b.options.dots&&null!==b.$dots&&(a("li",b.$dots).off("click.slick",b.changeSlide),b.options.pauseOnDotsHover===!0&&b.options.autoplay===!0&&a("li",b.$dots).off("mouseenter.slick",a.proxy(b.setPaused,b,!0)).off("mouseleave.slick",a.proxy(b.setPaused,b,!1))),b.options.arrows===!0&&b.slideCount>b.options.slidesToShow&&(b.$prevArrow&&b.$prevArrow.off("click.slick",b.changeSlide),b.$nextArrow&&b.$nextArrow.off("click.slick",b.changeSlide)),b.$list.off("touchstart.slick mousedown.slick",b.swipeHandler),b.$list.off("touchmove.slick mousemove.slick",b.swipeHandler),b.$list.off("touchend.slick mouseup.slick",b.swipeHandler),b.$list.off("touchcancel.slick mouseleave.slick",b.swipeHandler),b.$list.off("click.slick",b.clickHandler),a(document).off(b.visibilityChange,b.visibility),b.$list.off("mouseenter.slick",a.proxy(b.setPaused,b,!0)),b.$list.off("mouseleave.slick",a.proxy(b.setPaused,b,!1)),b.options.accessibility===!0&&b.$list.off("keydown.slick",b.keyHandler),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().off("click.slick",b.selectHandler),a(window).off("orientationchange.slick.slick-"+b.instanceUid,b.orientationChange),a(window).off("resize.slick.slick-"+b.instanceUid,b.resize),a("[draggable!=true]",b.$slideTrack).off("dragstart",b.preventDefault),a(window).off("load.slick.slick-"+b.instanceUid,b.setPosition),a(document).off("ready.slick.slick-"+b.instanceUid,b.setPosition)},b.prototype.cleanUpRows=function(){var b,a=this;a.options.rows>1&&(b=a.$slides.children().children(),b.removeAttr("style"),a.$slider.html(b))},b.prototype.clickHandler=function(a){var b=this;b.shouldClick===!1&&(a.stopImmediatePropagation(),a.stopPropagation(),a.preventDefault())},b.prototype.destroy=function(b){var c=this;c.autoPlayClear(),c.touchObject={},c.cleanUpEvents(),a(".slick-cloned",c.$slider).detach(),c.$dots&&c.$dots.remove(),c.$prevArrow&&c.$prevArrow.length&&(c.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),c.htmlExpr.test(c.options.prevArrow)&&c.$prevArrow.remove()),c.$nextArrow&&c.$nextArrow.length&&(c.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),c.htmlExpr.test(c.options.nextArrow)&&c.$nextArrow.remove()),c.$slides&&(c.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){a(this).attr("style",a(this).data("originalStyling"))}),c.$slideTrack.children(this.options.slide).detach(),c.$slideTrack.detach(),c.$list.detach(),c.$slider.append(c.$slides)),c.cleanUpRows(),c.$slider.removeClass("slick-slider"),c.$slider.removeClass("slick-initialized"),c.unslicked=!0,b||c.$slider.trigger("destroy",[c])},b.prototype.disableTransition=function(a){var b=this,c={};c[b.transitionType]="",b.options.fade===!1?b.$slideTrack.css(c):b.$slides.eq(a).css(c)},b.prototype.fadeSlide=function(a,b){var c=this;c.cssTransitions===!1?(c.$slides.eq(a).css({zIndex:c.options.zIndex}),c.$slides.eq(a).animate({opacity:1},c.options.speed,c.options.easing,b)):(c.applyTransition(a),c.$slides.eq(a).css({opacity:1,zIndex:c.options.zIndex}),b&&setTimeout(function(){c.disableTransition(a),b.call()},c.options.speed))},b.prototype.fadeSlideOut=function(a){var b=this;b.cssTransitions===!1?b.$slides.eq(a).animate({opacity:0,zIndex:b.options.zIndex-2},b.options.speed,b.options.easing):(b.applyTransition(a),b.$slides.eq(a).css({opacity:0,zIndex:b.options.zIndex-2}))},b.prototype.filterSlides=b.prototype.slickFilter=function(a){var b=this;null!==a&&(b.$slidesCache=b.$slides,b.unload(),b.$slideTrack.children(this.options.slide).detach(),b.$slidesCache.filter(a).appendTo(b.$slideTrack),b.reinit())},b.prototype.getCurrent=b.prototype.slickCurrentSlide=function(){var a=this;return a.currentSlide},b.prototype.getDotCount=function(){var a=this,b=0,c=0,d=0;if(a.options.infinite===!0)for(;b<a.slideCount;)++d,b=c+a.options.slidesToScroll,c+=a.options.slidesToScroll<=a.options.slidesToShow?a.options.slidesToScroll:a.options.slidesToShow;else if(a.options.centerMode===!0)d=a.slideCount;else for(;b<a.slideCount;)++d,b=c+a.options.slidesToScroll,c+=a.options.slidesToScroll<=a.options.slidesToShow?a.options.slidesToScroll:a.options.slidesToShow;return d-1},b.prototype.getLeft=function(a){var c,d,f,b=this,e=0;return b.slideOffset=0,d=b.$slides.first().outerHeight(!0),b.options.infinite===!0?(b.slideCount>b.options.slidesToShow&&(b.slideOffset=b.slideWidth*b.options.slidesToShow*-1,e=d*b.options.slidesToShow*-1),b.slideCount%b.options.slidesToScroll!==0&&a+b.options.slidesToScroll>b.slideCount&&b.slideCount>b.options.slidesToShow&&(a>b.slideCount?(b.slideOffset=(b.options.slidesToShow-(a-b.slideCount))*b.slideWidth*-1,e=(b.options.slidesToShow-(a-b.slideCount))*d*-1):(b.slideOffset=b.slideCount%b.options.slidesToScroll*b.slideWidth*-1,e=b.slideCount%b.options.slidesToScroll*d*-1))):a+b.options.slidesToShow>b.slideCount&&(b.slideOffset=(a+b.options.slidesToShow-b.slideCount)*b.slideWidth,e=(a+b.options.slidesToShow-b.slideCount)*d),b.slideCount<=b.options.slidesToShow&&(b.slideOffset=0,e=0),b.options.centerMode===!0&&b.options.infinite===!0?b.slideOffset+=b.slideWidth*Math.floor(b.options.slidesToShow/2)-b.slideWidth:b.options.centerMode===!0&&(b.slideOffset=0,b.slideOffset+=b.slideWidth*Math.floor(b.options.slidesToShow/2)),c=b.options.vertical===!1?a*b.slideWidth*-1+b.slideOffset:a*d*-1+e,b.options.variableWidth===!0&&(f=b.slideCount<=b.options.slidesToShow||b.options.infinite===!1?b.$slideTrack.children(".slick-slide").eq(a):b.$slideTrack.children(".slick-slide").eq(a+b.options.slidesToShow),c=b.options.rtl===!0?f[0]?-1*(b.$slideTrack.width()-f[0].offsetLeft-f.width()):0:f[0]?-1*f[0].offsetLeft:0,b.options.centerMode===!0&&(f=b.slideCount<=b.options.slidesToShow||b.options.infinite===!1?b.$slideTrack.children(".slick-slide").eq(a):b.$slideTrack.children(".slick-slide").eq(a+b.options.slidesToShow+1),c=b.options.rtl===!0?f[0]?-1*(b.$slideTrack.width()-f[0].offsetLeft-f.width()):0:f[0]?-1*f[0].offsetLeft:0,c+=(b.$list.width()-f.outerWidth())/2)),c},b.prototype.getOption=b.prototype.slickGetOption=function(a){var b=this;return b.options[a]},b.prototype.getNavigableIndexes=function(){var e,a=this,b=0,c=0,d=[];for(a.options.infinite===!1?e=a.slideCount:(b=-1*a.options.slidesToScroll,c=-1*a.options.slidesToScroll,e=2*a.slideCount);e>b;)d.push(b),b=c+a.options.slidesToScroll,c+=a.options.slidesToScroll<=a.options.slidesToShow?a.options.slidesToScroll:a.options.slidesToShow;return d},b.prototype.getSlick=function(){return this},b.prototype.getSlideCount=function(){var c,d,e,b=this;return e=b.options.centerMode===!0?b.slideWidth*Math.floor(b.options.slidesToShow/2):0,b.options.swipeToSlide===!0?(b.$slideTrack.find(".slick-slide").each(function(c,f){return f.offsetLeft-e+a(f).outerWidth()/2>-1*b.swipeLeft?(d=f,!1):void 0}),c=Math.abs(a(d).attr("data-slick-index")-b.currentSlide)||1):b.options.slidesToScroll},b.prototype.goTo=b.prototype.slickGoTo=function(a,b){var c=this;c.changeSlide({data:{message:"index",index:parseInt(a)}},b)},b.prototype.init=function(b){var c=this;a(c.$slider).hasClass("slick-initialized")||(a(c.$slider).addClass("slick-initialized"),c.buildRows(),c.buildOut(),c.setProps(),c.startLoad(),c.loadSlider(),c.initializeEvents(),c.updateArrows(),c.updateDots()),b&&c.$slider.trigger("init",[c]),c.options.accessibility===!0&&c.initADA()},b.prototype.initArrowEvents=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.on("click.slick",{message:"previous"},a.changeSlide),a.$nextArrow.on("click.slick",{message:"next"},a.changeSlide))},b.prototype.initDotEvents=function(){var b=this;b.options.dots===!0&&b.slideCount>b.options.slidesToShow&&a("li",b.$dots).on("click.slick",{message:"index"},b.changeSlide),b.options.dots===!0&&b.options.pauseOnDotsHover===!0&&b.options.autoplay===!0&&a("li",b.$dots).on("mouseenter.slick",a.proxy(b.setPaused,b,!0)).on("mouseleave.slick",a.proxy(b.setPaused,b,!1))},b.prototype.initializeEvents=function(){var b=this;b.initArrowEvents(),b.initDotEvents(),b.$list.on("touchstart.slick mousedown.slick",{action:"start"},b.swipeHandler),b.$list.on("touchmove.slick mousemove.slick",{action:"move"},b.swipeHandler),b.$list.on("touchend.slick mouseup.slick",{action:"end"},b.swipeHandler),b.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},b.swipeHandler),b.$list.on("click.slick",b.clickHandler),a(document).on(b.visibilityChange,a.proxy(b.visibility,b)),b.$list.on("mouseenter.slick",a.proxy(b.setPaused,b,!0)),b.$list.on("mouseleave.slick",a.proxy(b.setPaused,b,!1)),b.options.accessibility===!0&&b.$list.on("keydown.slick",b.keyHandler),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().on("click.slick",b.selectHandler),a(window).on("orientationchange.slick.slick-"+b.instanceUid,a.proxy(b.orientationChange,b)),a(window).on("resize.slick.slick-"+b.instanceUid,a.proxy(b.resize,b)),a("[draggable!=true]",b.$slideTrack).on("dragstart",b.preventDefault),a(window).on("load.slick.slick-"+b.instanceUid,b.setPosition),a(document).on("ready.slick.slick-"+b.instanceUid,b.setPosition)},b.prototype.initUI=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.show(),a.$nextArrow.show()),a.options.dots===!0&&a.slideCount>a.options.slidesToShow&&a.$dots.show(),a.options.autoplay===!0&&a.autoPlay()},b.prototype.keyHandler=function(a){var b=this;a.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===a.keyCode&&b.options.accessibility===!0?b.changeSlide({data:{message:"previous"}}):39===a.keyCode&&b.options.accessibility===!0&&b.changeSlide({data:{message:"next"}}))},b.prototype.lazyLoad=function(){function g(b){a("img[data-lazy]",b).each(function(){var b=a(this),c=a(this).attr("data-lazy"),d=document.createElement("img");d.onload=function(){b.animate({opacity:0},100,function(){b.attr("src",c).animate({opacity:1},200,function(){b.removeAttr("data-lazy").removeClass("slick-loading")})})},d.src=c})}var c,d,e,f,b=this;b.options.centerMode===!0?b.options.infinite===!0?(e=b.currentSlide+(b.options.slidesToShow/2+1),f=e+b.options.slidesToShow+2):(e=Math.max(0,b.currentSlide-(b.options.slidesToShow/2+1)),f=2+(b.options.slidesToShow/2+1)+b.currentSlide):(e=b.options.infinite?b.options.slidesToShow+b.currentSlide:b.currentSlide,f=e+b.options.slidesToShow,b.options.fade===!0&&(e>0&&e--,f<=b.slideCount&&f++)),c=b.$slider.find(".slick-slide").slice(e,f),g(c),b.slideCount<=b.options.slidesToShow?(d=b.$slider.find(".slick-slide"),g(d)):b.currentSlide>=b.slideCount-b.options.slidesToShow?(d=b.$slider.find(".slick-cloned").slice(0,b.options.slidesToShow),g(d)):0===b.currentSlide&&(d=b.$slider.find(".slick-cloned").slice(-1*b.options.slidesToShow),g(d))},b.prototype.loadSlider=function(){var a=this;a.setPosition(),a.$slideTrack.css({opacity:1}),a.$slider.removeClass("slick-loading"),a.initUI(),"progressive"===a.options.lazyLoad&&a.progressiveLazyLoad()},b.prototype.next=b.prototype.slickNext=function(){var a=this;a.changeSlide({data:{message:"next"}})},b.prototype.orientationChange=function(){var a=this;a.checkResponsive(),a.setPosition()},b.prototype.pause=b.prototype.slickPause=function(){var a=this;a.autoPlayClear(),a.paused=!0},b.prototype.play=b.prototype.slickPlay=function(){var a=this;a.paused=!1,a.autoPlay()},b.prototype.postSlide=function(a){var b=this;b.$slider.trigger("afterChange",[b,a]),b.animating=!1,b.setPosition(),b.swipeLeft=null,b.options.autoplay===!0&&b.paused===!1&&b.autoPlay(),b.options.accessibility===!0&&b.initADA()},b.prototype.prev=b.prototype.slickPrev=function(){var a=this;a.changeSlide({data:{message:"previous"}})},b.prototype.preventDefault=function(a){a.preventDefault()},b.prototype.progressiveLazyLoad=function(){var c,d,b=this;c=a("img[data-lazy]",b.$slider).length,c>0&&(d=a("img[data-lazy]",b.$slider).first(),d.attr("src",null),d.attr("src",d.attr("data-lazy")).removeClass("slick-loading").load(function(){d.removeAttr("data-lazy"),b.progressiveLazyLoad(),b.options.adaptiveHeight===!0&&b.setPosition()}).error(function(){d.removeAttr("data-lazy"),b.progressiveLazyLoad()}))},b.prototype.refresh=function(b){var d,e,c=this;e=c.slideCount-c.options.slidesToShow,c.options.infinite||(c.slideCount<=c.options.slidesToShow?c.currentSlide=0:c.currentSlide>e&&(c.currentSlide=e)),d=c.currentSlide,c.destroy(!0),a.extend(c,c.initials,{currentSlide:d}),c.init(),b||c.changeSlide({data:{message:"index",index:d}},!1)},b.prototype.registerBreakpoints=function(){var c,d,e,b=this,f=b.options.responsive||null;if("array"===a.type(f)&&f.length){b.respondTo=b.options.respondTo||"window";for(c in f)if(e=b.breakpoints.length-1,d=f[c].breakpoint,f.hasOwnProperty(c)){for(;e>=0;)b.breakpoints[e]&&b.breakpoints[e]===d&&b.breakpoints.splice(e,1),e--;b.breakpoints.push(d),b.breakpointSettings[d]=f[c].settings}b.breakpoints.sort(function(a,c){return b.options.mobileFirst?a-c:c-a})}},b.prototype.reinit=function(){var b=this;b.$slides=b.$slideTrack.children(b.options.slide).addClass("slick-slide"),b.slideCount=b.$slides.length,b.currentSlide>=b.slideCount&&0!==b.currentSlide&&(b.currentSlide=b.currentSlide-b.options.slidesToScroll),b.slideCount<=b.options.slidesToShow&&(b.currentSlide=0),b.registerBreakpoints(),b.setProps(),b.setupInfinite(),b.buildArrows(),b.updateArrows(),b.initArrowEvents(),b.buildDots(),b.updateDots(),b.initDotEvents(),b.checkResponsive(!1,!0),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().on("click.slick",b.selectHandler),b.setSlideClasses(0),b.setPosition(),b.$slider.trigger("reInit",[b]),b.options.autoplay===!0&&b.focusHandler()},b.prototype.resize=function(){var b=this;a(window).width()!==b.windowWidth&&(clearTimeout(b.windowDelay),b.windowDelay=window.setTimeout(function(){b.windowWidth=a(window).width(),b.checkResponsive(),b.unslicked||b.setPosition()},50))},b.prototype.removeSlide=b.prototype.slickRemove=function(a,b,c){var d=this;return"boolean"==typeof a?(b=a,a=b===!0?0:d.slideCount-1):a=b===!0?--a:a,d.slideCount<1||0>a||a>d.slideCount-1?!1:(d.unload(),c===!0?d.$slideTrack.children().remove():d.$slideTrack.children(this.options.slide).eq(a).remove(),d.$slides=d.$slideTrack.children(this.options.slide),d.$slideTrack.children(this.options.slide).detach(),d.$slideTrack.append(d.$slides),d.$slidesCache=d.$slides,void d.reinit())},b.prototype.setCSS=function(a){var d,e,b=this,c={};b.options.rtl===!0&&(a=-a),d="left"==b.positionProp?Math.ceil(a)+"px":"0px",e="top"==b.positionProp?Math.ceil(a)+"px":"0px",c[b.positionProp]=a,b.transformsEnabled===!1?b.$slideTrack.css(c):(c={},b.cssTransitions===!1?(c[b.animType]="translate("+d+", "+e+")",b.$slideTrack.css(c)):(c[b.animType]="translate3d("+d+", "+e+", 0px)",b.$slideTrack.css(c)))},b.prototype.setDimensions=function(){var a=this;a.options.vertical===!1?a.options.centerMode===!0&&a.$list.css({padding:"0px "+a.options.centerPadding}):(a.$list.height(a.$slides.first().outerHeight(!0)*a.options.slidesToShow),a.options.centerMode===!0&&a.$list.css({padding:a.options.centerPadding+" 0px"})),a.listWidth=a.$list.width(),a.listHeight=a.$list.height(),a.options.vertical===!1&&a.options.variableWidth===!1?(a.slideWidth=Math.ceil(a.listWidth/a.options.slidesToShow),a.$slideTrack.width(Math.ceil(a.slideWidth*a.$slideTrack.children(".slick-slide").length))):a.options.variableWidth===!0?a.$slideTrack.width(5e3*a.slideCount):(a.slideWidth=Math.ceil(a.listWidth),a.$slideTrack.height(Math.ceil(a.$slides.first().outerHeight(!0)*a.$slideTrack.children(".slick-slide").length)));var b=a.$slides.first().outerWidth(!0)-a.$slides.first().width();a.options.variableWidth===!1&&a.$slideTrack.children(".slick-slide").width(a.slideWidth-b)},b.prototype.setFade=function(){var c,b=this;b.$slides.each(function(d,e){c=b.slideWidth*d*-1,b.options.rtl===!0?a(e).css({position:"relative",right:c,top:0,zIndex:b.options.zIndex-2,opacity:0}):a(e).css({position:"relative",left:c,top:0,zIndex:b.options.zIndex-2,opacity:0})}),b.$slides.eq(b.currentSlide).css({zIndex:b.options.zIndex-1,opacity:1})},b.prototype.setHeight=function(){var a=this;if(1===a.options.slidesToShow&&a.options.adaptiveHeight===!0&&a.options.vertical===!1){var b=a.$slides.eq(a.currentSlide).outerHeight(!0);a.$list.css("height",b)}},b.prototype.setOption=b.prototype.slickSetOption=function(b,c,d){var f,g,e=this;if("responsive"===b&&"array"===a.type(c))for(g in c)if("array"!==a.type(e.options.responsive))e.options.responsive=[c[g]];else{for(f=e.options.responsive.length-1;f>=0;)e.options.responsive[f].breakpoint===c[g].breakpoint&&e.options.responsive.splice(f,1),f--;e.options.responsive.push(c[g])}else e.options[b]=c;d===!0&&(e.unload(),e.reinit())},b.prototype.setPosition=function(){var a=this;a.setDimensions(),a.setHeight(),a.options.fade===!1?a.setCSS(a.getLeft(a.currentSlide)):a.setFade(),a.$slider.trigger("setPosition",[a])},b.prototype.setProps=function(){var a=this,b=document.body.style;a.positionProp=a.options.vertical===!0?"top":"left","top"===a.positionProp?a.$slider.addClass("slick-vertical"):a.$slider.removeClass("slick-vertical"),(void 0!==b.WebkitTransition||void 0!==b.MozTransition||void 0!==b.msTransition)&&a.options.useCSS===!0&&(a.cssTransitions=!0),a.options.fade&&("number"==typeof a.options.zIndex?a.options.zIndex<3&&(a.options.zIndex=3):a.options.zIndex=a.defaults.zIndex),void 0!==b.OTransform&&(a.animType="OTransform",a.transformType="-o-transform",a.transitionType="OTransition",void 0===b.perspectiveProperty&&void 0===b.webkitPerspective&&(a.animType=!1)),void 0!==b.MozTransform&&(a.animType="MozTransform",a.transformType="-moz-transform",a.transitionType="MozTransition",void 0===b.perspectiveProperty&&void 0===b.MozPerspective&&(a.animType=!1)),void 0!==b.webkitTransform&&(a.animType="webkitTransform",a.transformType="-webkit-transform",a.transitionType="webkitTransition",void 0===b.perspectiveProperty&&void 0===b.webkitPerspective&&(a.animType=!1)),void 0!==b.msTransform&&(a.animType="msTransform",a.transformType="-ms-transform",a.transitionType="msTransition",void 0===b.msTransform&&(a.animType=!1)),void 0!==b.transform&&a.animType!==!1&&(a.animType="transform",a.transformType="transform",a.transitionType="transition"),a.transformsEnabled=a.options.useTransform&&null!==a.animType&&a.animType!==!1},b.prototype.setSlideClasses=function(a){var c,d,e,f,b=this;d=b.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),b.$slides.eq(a).addClass("slick-current"),b.options.centerMode===!0?(c=Math.floor(b.options.slidesToShow/2),b.options.infinite===!0&&(a>=c&&a<=b.slideCount-1-c?b.$slides.slice(a-c,a+c+1).addClass("slick-active").attr("aria-hidden","false"):(e=b.options.slidesToShow+a,d.slice(e-c+1,e+c+2).addClass("slick-active").attr("aria-hidden","false")),0===a?d.eq(d.length-1-b.options.slidesToShow).addClass("slick-center"):a===b.slideCount-1&&d.eq(b.options.slidesToShow).addClass("slick-center")),b.$slides.eq(a).addClass("slick-center")):a>=0&&a<=b.slideCount-b.options.slidesToShow?b.$slides.slice(a,a+b.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):d.length<=b.options.slidesToShow?d.addClass("slick-active").attr("aria-hidden","false"):(f=b.slideCount%b.options.slidesToShow,e=b.options.infinite===!0?b.options.slidesToShow+a:a,b.options.slidesToShow==b.options.slidesToScroll&&b.slideCount-a<b.options.slidesToShow?d.slice(e-(b.options.slidesToShow-f),e+f).addClass("slick-active").attr("aria-hidden","false"):d.slice(e,e+b.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false")),"ondemand"===b.options.lazyLoad&&b.lazyLoad()},b.prototype.setupInfinite=function(){var c,d,e,b=this;if(b.options.fade===!0&&(b.options.centerMode=!1),b.options.infinite===!0&&b.options.fade===!1&&(d=null,b.slideCount>b.options.slidesToShow)){for(e=b.options.centerMode===!0?b.options.slidesToShow+1:b.options.slidesToShow,c=b.slideCount;c>b.slideCount-e;c-=1)d=c-1,a(b.$slides[d]).clone(!0).attr("id","").attr("data-slick-index",d-b.slideCount).prependTo(b.$slideTrack).addClass("slick-cloned");for(c=0;e>c;c+=1)d=c,a(b.$slides[d]).clone(!0).attr("id","").attr("data-slick-index",d+b.slideCount).appendTo(b.$slideTrack).addClass("slick-cloned");b.$slideTrack.find(".slick-cloned").find("[id]").each(function(){a(this).attr("id","")})}},b.prototype.setPaused=function(a){var b=this;b.options.autoplay===!0&&b.options.pauseOnHover===!0&&(b.paused=a,a?b.autoPlayClear():b.autoPlay())},b.prototype.selectHandler=function(b){var c=this,d=a(b.target).is(".slick-slide")?a(b.target):a(b.target).parents(".slick-slide"),e=parseInt(d.attr("data-slick-index"));return e||(e=0),c.slideCount<=c.options.slidesToShow?(c.setSlideClasses(e),void c.asNavFor(e)):void c.slideHandler(e)},b.prototype.slideHandler=function(a,b,c){var d,e,f,g,h=null,i=this;return b=b||!1,i.animating===!0&&i.options.waitForAnimate===!0||i.options.fade===!0&&i.currentSlide===a||i.slideCount<=i.options.slidesToShow?void 0:(b===!1&&i.asNavFor(a),d=a,h=i.getLeft(d),g=i.getLeft(i.currentSlide),i.currentLeft=null===i.swipeLeft?g:i.swipeLeft,i.options.infinite===!1&&i.options.centerMode===!1&&(0>a||a>i.getDotCount()*i.options.slidesToScroll)?void(i.options.fade===!1&&(d=i.currentSlide,c!==!0?i.animateSlide(g,function(){i.postSlide(d);
}):i.postSlide(d))):i.options.infinite===!1&&i.options.centerMode===!0&&(0>a||a>i.slideCount-i.options.slidesToScroll)?void(i.options.fade===!1&&(d=i.currentSlide,c!==!0?i.animateSlide(g,function(){i.postSlide(d)}):i.postSlide(d))):(i.options.autoplay===!0&&clearInterval(i.autoPlayTimer),e=0>d?i.slideCount%i.options.slidesToScroll!==0?i.slideCount-i.slideCount%i.options.slidesToScroll:i.slideCount+d:d>=i.slideCount?i.slideCount%i.options.slidesToScroll!==0?0:d-i.slideCount:d,i.animating=!0,i.$slider.trigger("beforeChange",[i,i.currentSlide,e]),f=i.currentSlide,i.currentSlide=e,i.setSlideClasses(i.currentSlide),i.updateDots(),i.updateArrows(),i.options.fade===!0?(c!==!0?(i.fadeSlideOut(f),i.fadeSlide(e,function(){i.postSlide(e)})):i.postSlide(e),void i.animateHeight()):void(c!==!0?i.animateSlide(h,function(){i.postSlide(e)}):i.postSlide(e))))},b.prototype.startLoad=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.hide(),a.$nextArrow.hide()),a.options.dots===!0&&a.slideCount>a.options.slidesToShow&&a.$dots.hide(),a.$slider.addClass("slick-loading")},b.prototype.swipeDirection=function(){var a,b,c,d,e=this;return a=e.touchObject.startX-e.touchObject.curX,b=e.touchObject.startY-e.touchObject.curY,c=Math.atan2(b,a),d=Math.round(180*c/Math.PI),0>d&&(d=360-Math.abs(d)),45>=d&&d>=0?e.options.rtl===!1?"left":"right":360>=d&&d>=315?e.options.rtl===!1?"left":"right":d>=135&&225>=d?e.options.rtl===!1?"right":"left":e.options.verticalSwiping===!0?d>=35&&135>=d?"left":"right":"vertical"},b.prototype.swipeEnd=function(a){var c,b=this;if(b.dragging=!1,b.shouldClick=b.touchObject.swipeLength>10?!1:!0,void 0===b.touchObject.curX)return!1;if(b.touchObject.edgeHit===!0&&b.$slider.trigger("edge",[b,b.swipeDirection()]),b.touchObject.swipeLength>=b.touchObject.minSwipe)switch(b.swipeDirection()){case"left":c=b.options.swipeToSlide?b.checkNavigable(b.currentSlide+b.getSlideCount()):b.currentSlide+b.getSlideCount(),b.slideHandler(c),b.currentDirection=0,b.touchObject={},b.$slider.trigger("swipe",[b,"left"]);break;case"right":c=b.options.swipeToSlide?b.checkNavigable(b.currentSlide-b.getSlideCount()):b.currentSlide-b.getSlideCount(),b.slideHandler(c),b.currentDirection=1,b.touchObject={},b.$slider.trigger("swipe",[b,"right"])}else b.touchObject.startX!==b.touchObject.curX&&(b.slideHandler(b.currentSlide),b.touchObject={})},b.prototype.swipeHandler=function(a){var b=this;if(!(b.options.swipe===!1||"ontouchend"in document&&b.options.swipe===!1||b.options.draggable===!1&&-1!==a.type.indexOf("mouse")))switch(b.touchObject.fingerCount=a.originalEvent&&void 0!==a.originalEvent.touches?a.originalEvent.touches.length:1,b.touchObject.minSwipe=b.listWidth/b.options.touchThreshold,b.options.verticalSwiping===!0&&(b.touchObject.minSwipe=b.listHeight/b.options.touchThreshold),a.data.action){case"start":b.swipeStart(a);break;case"move":b.swipeMove(a);break;case"end":b.swipeEnd(a)}},b.prototype.swipeMove=function(a){var d,e,f,g,h,b=this;return h=void 0!==a.originalEvent?a.originalEvent.touches:null,!b.dragging||h&&1!==h.length?!1:(d=b.getLeft(b.currentSlide),b.touchObject.curX=void 0!==h?h[0].pageX:a.clientX,b.touchObject.curY=void 0!==h?h[0].pageY:a.clientY,b.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(b.touchObject.curX-b.touchObject.startX,2))),b.options.verticalSwiping===!0&&(b.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(b.touchObject.curY-b.touchObject.startY,2)))),e=b.swipeDirection(),"vertical"!==e?(void 0!==a.originalEvent&&b.touchObject.swipeLength>4&&a.preventDefault(),g=(b.options.rtl===!1?1:-1)*(b.touchObject.curX>b.touchObject.startX?1:-1),b.options.verticalSwiping===!0&&(g=b.touchObject.curY>b.touchObject.startY?1:-1),f=b.touchObject.swipeLength,b.touchObject.edgeHit=!1,b.options.infinite===!1&&(0===b.currentSlide&&"right"===e||b.currentSlide>=b.getDotCount()&&"left"===e)&&(f=b.touchObject.swipeLength*b.options.edgeFriction,b.touchObject.edgeHit=!0),b.options.vertical===!1?b.swipeLeft=d+f*g:b.swipeLeft=d+f*(b.$list.height()/b.listWidth)*g,b.options.verticalSwiping===!0&&(b.swipeLeft=d+f*g),b.options.fade===!0||b.options.touchMove===!1?!1:b.animating===!0?(b.swipeLeft=null,!1):void b.setCSS(b.swipeLeft)):void 0)},b.prototype.swipeStart=function(a){var c,b=this;return 1!==b.touchObject.fingerCount||b.slideCount<=b.options.slidesToShow?(b.touchObject={},!1):(void 0!==a.originalEvent&&void 0!==a.originalEvent.touches&&(c=a.originalEvent.touches[0]),b.touchObject.startX=b.touchObject.curX=void 0!==c?c.pageX:a.clientX,b.touchObject.startY=b.touchObject.curY=void 0!==c?c.pageY:a.clientY,void(b.dragging=!0))},b.prototype.unfilterSlides=b.prototype.slickUnfilter=function(){var a=this;null!==a.$slidesCache&&(a.unload(),a.$slideTrack.children(this.options.slide).detach(),a.$slidesCache.appendTo(a.$slideTrack),a.reinit())},b.prototype.unload=function(){var b=this;a(".slick-cloned",b.$slider).remove(),b.$dots&&b.$dots.remove(),b.$prevArrow&&b.htmlExpr.test(b.options.prevArrow)&&b.$prevArrow.remove(),b.$nextArrow&&b.htmlExpr.test(b.options.nextArrow)&&b.$nextArrow.remove(),b.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},b.prototype.unslick=function(a){var b=this;b.$slider.trigger("unslick",[b,a]),b.destroy()},b.prototype.updateArrows=function(){var b,a=this;b=Math.floor(a.options.slidesToShow/2),a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&!a.options.infinite&&(a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),a.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===a.currentSlide?(a.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):a.currentSlide>=a.slideCount-a.options.slidesToShow&&a.options.centerMode===!1?(a.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):a.currentSlide>=a.slideCount-1&&a.options.centerMode===!0&&(a.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},b.prototype.updateDots=function(){var a=this;null!==a.$dots&&(a.$dots.find("li").removeClass("slick-active").attr("aria-hidden","true"),a.$dots.find("li").eq(Math.floor(a.currentSlide/a.options.slidesToScroll)).addClass("slick-active").attr("aria-hidden","false"))},b.prototype.visibility=function(){var a=this;document[a.hidden]?(a.paused=!0,a.autoPlayClear()):a.options.autoplay===!0&&(a.paused=!1,a.autoPlay())},b.prototype.initADA=function(){var b=this;b.$slides.add(b.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),b.$slideTrack.attr("role","listbox"),b.$slides.not(b.$slideTrack.find(".slick-cloned")).each(function(c){a(this).attr({role:"option","aria-describedby":"slick-slide"+b.instanceUid+c})}),null!==b.$dots&&b.$dots.attr("role","tablist").find("li").each(function(c){a(this).attr({role:"presentation","aria-selected":"false","aria-controls":"navigation"+b.instanceUid+c,id:"slick-slide"+b.instanceUid+c})}).first().attr("aria-selected","true").end().find("button").attr("role","button").end().closest("div").attr("role","toolbar"),b.activateADA()},b.prototype.activateADA=function(){var a=this;a.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},b.prototype.focusHandler=function(){var b=this;b.$slider.on("focus.slick blur.slick","*",function(c){c.stopImmediatePropagation();var d=a(this);setTimeout(function(){b.isPlay&&(d.is(":focus")?(b.autoPlayClear(),b.paused=!0):(b.paused=!1,b.autoPlay()))},0)})},a.fn.slick=function(){var f,g,a=this,c=arguments[0],d=Array.prototype.slice.call(arguments,1),e=a.length;for(f=0;e>f;f++)if("object"==typeof c||"undefined"==typeof c?a[f].slick=new b(a[f],c):g=a[f].slick[c].apply(a[f].slick,d),"undefined"!=typeof g)return g;return a}});;

/********************************
/site/resources/slick/slick-lightbox.min.js
********************************/
"use strict";!function(t){var i,n;i=function(){function i(i,n){var o;this.options=n,this.$element=t(i),this.didInit=!1,o=this,this.$element.on("click.slickLightbox",this.options.itemSelector,function(i){var n,e;if(i.preventDefault(),n=t(this),n.blur(),"function"!=typeof o.options.shouldOpen||o.options.shouldOpen(o,n,i))return e=o.$element.find(o.options.itemSelector),o.elementIsSlick()&&(e=o.filterOutSlickClones(e),n=o.handlePossibleCloneClick(n,e)),o.init(e.index(n))})}return i.prototype.init=function(t){return this.didInit=!0,this.detectIE(),this.createModal(),this.bindEvents(),this.initSlick(t),this.open()},i.prototype.createModalItems=function(){var i,n,o,e,s,l;return e=this.options.lazyPlaceholder||"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",o=function(t,i,n){return'<div class="slick-lightbox-slick-item">\n  <div class="slick-lightbox-slick-item-inner">\n    <img class="slick-lightbox-slick-img" '+(!0===n?' data-lazy="'+t+'" src="'+e+'" ':' src="'+t+'" ')+" />\n    "+i+"\n  </div>\n</div>"},this.options.images?l=t.map(this.options.images,function(t){return function(i){return o(i,t.options.lazy)}}(this)):(i=this.filterOutSlickClones(this.$element.find(this.options.itemSelector)),s=i.length,n=function(t){return function(i,n){var e,l,r;return l={index:n,length:s},e=t.getElementCaption(i,l),r=t.getElementSrc(i),o(r,e,t.options.lazy)}}(this),l=t.map(i,n)),l},i.prototype.createModal=function(){var i,n;return n=this.createModalItems(),i='<div class="slick-lightbox slick-lightbox-hide-init'+(this.isIE?" slick-lightbox-ie":"")+'" style="background: '+this.options.background+';">\n  <div class="slick-lightbox-inner">\n    <div class="slick-lightbox-slick slick-caption-'+this.options.captionPosition+'">'+n.join("")+"</div>\n  <div>\n<div>",this.$modalElement=t(i),this.$parts={},this.$parts.closeButton=t(this.options.layouts.closeButton),this.$modalElement.find(".slick-lightbox-inner").append(this.$parts.closeButton),t("body").append(this.$modalElement)},i.prototype.initSlick=function(i){var n;return n={initialSlide:i},this.options.lazy&&(n.lazyLoad="ondemand"),null!=this.options.slick?"function"==typeof this.options.slick?this.slick=this.options.slick(this.$modalElement):this.slick=this.$modalElement.find(".slick-lightbox-slick").slick(t.extend({},this.options.slick,n)):this.slick=this.$modalElement.find(".slick-lightbox-slick").slick(n),this.$modalElement.trigger("init.slickLightbox")},i.prototype.open=function(){return this.options.useHistoryApi&&this.writeHistory(),this.$element.trigger("show.slickLightbox"),setTimeout(function(t){return function(){return t.$element.trigger("shown.slickLightbox")}}(this),this.getTransitionDuration()),this.$modalElement.removeClass("slick-lightbox-hide-init")},i.prototype.close=function(){return this.$element.trigger("hide.slickLightbox"),setTimeout(function(t){return function(){return t.$element.trigger("hidden.slickLightbox")}}(this),this.getTransitionDuration()),this.$modalElement.addClass("slick-lightbox-hide"),this.destroy()},i.prototype.bindEvents=function(){var i;if(i=function(t){return function(){var i;return i=t.$modalElement.find(".slick-lightbox-inner").height(),t.$modalElement.find(".slick-lightbox-slick-item").height(i),t.$modalElement.find(".slick-lightbox-slick-img, .slick-lightbox-slick-item-inner").css("max-height",Math.round(t.options.imageMaxHeight*i))}}(this),t(window).on("orientationchange.slickLightbox resize.slickLightbox",i),this.options.useHistoryApi&&t(window).on("popstate.slickLightbox",function(t){return function(){return t.close()}}(this)),this.$modalElement.on("init.slickLightbox",i),this.$modalElement.on("destroy.slickLightbox",function(t){return function(){return t.destroy()}}(this)),this.$element.on("destroy.slickLightbox",function(t){return function(){return t.destroy(!0)}}(this)),this.$parts.closeButton.on("click.slickLightbox touchstart.slickLightbox",function(t){return function(i){return i.preventDefault(),t.close()}}(this)),(this.options.closeOnEscape||this.options.navigateByKeyboard)&&t(document).on("keydown.slickLightbox",function(t){return function(i){var n;if(n=i.keyCode?i.keyCode:i.which,t.options.navigateByKeyboard&&(37===n?t.slideSlick("left"):39===n&&t.slideSlick("right")),t.options.closeOnEscape&&27===n)return t.close()}}(this)),this.options.closeOnBackdropClick)return this.$modalElement.on("click.slickLightbox touchstart.slickLightbox",".slick-lightbox-slick-img",function(t){return t.stopPropagation()}),this.$modalElement.on("click.slickLightbox",".slick-lightbox-slick-item",function(t){return function(i){return i.preventDefault(),t.close()}}(this))},i.prototype.slideSlick=function(t){return"left"===t?this.slick.slick("slickPrev"):this.slick.slick("slickNext")},i.prototype.detectIE=function(){if(this.isIE=!1,/MSIE (\d+\.\d+);/.test(navigator.userAgent)&&new Number(RegExp.$1)<9)return this.isIE=!0},i.prototype.getElementCaption=function(i,n){return this.options.caption?'<span class="slick-lightbox-slick-caption">'+function(){switch(typeof this.options.caption){case"function":return this.options.caption(i,n);case"string":return t(i).data(this.options.caption)}}.call(this)+"</span>":""},i.prototype.getElementSrc=function(i){switch(typeof this.options.src){case"function":return this.options.src(i);case"string":return t(i).attr(this.options.src);default:return i.href}},i.prototype.unbindEvents=function(){return t(window).off(".slickLightbox"),t(document).off(".slickLightbox"),this.$modalElement.off(".slickLightbox")},i.prototype.destroy=function(t){if(null==t&&(t=!1),this.didInit&&(this.unbindEvents(),setTimeout(function(t){return function(){return t.$modalElement.remove()}}(this),this.options.destroyTimeout)),t)return this.$element.off(".slickLightbox"),this.$element.off(".slickLightbox",this.options.itemSelector)},i.prototype.destroyPrevious=function(){return t("body").children(".slick-lightbox").trigger("destroy.slickLightbox")},i.prototype.getTransitionDuration=function(){var t;return this.transitionDuration?this.transitionDuration:(t=this.$modalElement.css("transition-duration"),this.transitionDuration=void 0===t?500:t.indexOf("ms")>-1?parseFloat(t):1e3*parseFloat(t))},i.prototype.writeHistory=function(){return"undefined"!=typeof history&&null!==history&&"function"==typeof history.pushState?history.pushState(null,null,""):void 0},i.prototype.filterOutSlickClones=function(i){return this.elementIsSlick()?i=i.filter(function(){var i;return i=t(this),!i.hasClass("slick-cloned")&&0===i.parents(".slick-cloned").length}):i},i.prototype.handlePossibleCloneClick=function(i,n){var o;return this.elementIsSlick()&&i.closest(".slick-slide").hasClass("slick-cloned")?(o=i.attr("href"),n.filter(function(){return t(this).attr("href")===o}).first()):i},i.prototype.elementIsSlick=function(){return this.$element.hasClass("slick-slider")},i}(),n={background:"rgba(0,0,0,.8)",closeOnEscape:!0,closeOnBackdropClick:!0,destroyTimeout:500,itemSelector:"a",navigateByKeyboard:!0,src:!1,caption:!1,captionPosition:"dynamic",images:!1,slick:{},useHistoryApi:!1,layouts:{closeButton:'<button type="button" class="slick-lightbox-close"></button>'},shouldOpen:null,imageMaxHeight:.9,lazy:!1},t.fn.slickLightbox=function(o){return o=t.extend({},n,o),t(this).each(function(){return this.slickLightbox=new i(this,o)}),this},t.fn.unslickLightbox=function(){return t(this).trigger("destroy.slickLightbox").each(function(){return this.slickLightbox=null})}}(jQuery);
//# sourceMappingURL=slick-lightbox.min.js.map;

/********************************
/site/resources/elevatezoom-master/jquery.elevatezoom.js
********************************/
/*
 *	jQuery elevateZoom 3.0.8
 *	Demo's and documentation:
 *	www.elevateweb.co.uk/image-zoom
 *
 *	Copyright (c) 2012 Andrew Eades
 *	www.elevateweb.co.uk
 *
 *	Dual licensed under the GPL and MIT licenses.
 *	http://en.wikipedia.org/wiki/MIT_License
 *	http://en.wikipedia.org/wiki/GNU_General_Public_License
 *

/*
 *	jQuery elevateZoom 3.0.3
 *	Demo's and documentation:
 *	www.elevateweb.co.uk/image-zoom
 *
 *	Copyright (c) 2012 Andrew Eades
 *	www.elevateweb.co.uk
 *
 *	Dual licensed under the GPL and MIT licenses.
 *	http://en.wikipedia.org/wiki/MIT_License
 *	http://en.wikipedia.org/wiki/GNU_General_Public_License
 */


if ( typeof Object.create !== 'function' ) {
	Object.create = function( obj ) {
		function F() {};
		F.prototype = obj;
		return new F();
	};
}

(function( $, window, document, undefined ) {
	var ElevateZoom = {
			init: function( options, elem ) {
				var self = this;

				self.elem = elem;
				self.$elem = $( elem );

				self.imageSrc = self.$elem.data("zoom-image") ? self.$elem.data("zoom-image") : self.$elem.attr("src");

				self.options = $.extend( {}, $.fn.elevateZoom.options, options );

				//TINT OVERRIDE SETTINGS
				if(self.options.tint) {
					self.options.lensColour = "none", //colour of the lens background
					self.options.lensOpacity =  "1" //opacity of the lens
				}
				//INNER OVERRIDE SETTINGS
				if(self.options.zoomType == "inner") {self.options.showLens = false;}


				//Remove alt on hover

				self.$elem.parent().removeAttr('title').removeAttr('alt');

				self.zoomImage = self.imageSrc;

				self.refresh( 1 );



				//Create the image swap from the gallery 
				$('#'+self.options.gallery + ' a').click( function(e) { 

					//Set a class on the currently active gallery image
					if(self.options.galleryActiveClass){
						$('#'+self.options.gallery + ' a').removeClass(self.options.galleryActiveClass);
						$(this).addClass(self.options.galleryActiveClass);
					}
					//stop any link on the a tag from working
					e.preventDefault();

					//call the swap image function            
					if($(this).data("zoom-image")){self.zoomImagePre = $(this).data("zoom-image")}
					else{self.zoomImagePre = $(this).data("image");}
					self.swaptheimage($(this).data("image"), self.zoomImagePre);
					return false;
				});

			},

			refresh: function( length ) {
				var self = this;

				setTimeout(function() {
					self.fetch(self.imageSrc);

				}, length || self.options.refresh );
			},

			fetch: function(imgsrc) {
				//get the image
				var self = this;
				var newImg = new Image();
				newImg.onload = function() {
					//set the large image dimensions - used to calculte ratio's
					self.largeWidth = newImg.width;
					self.largeHeight = newImg.height;
					//once image is loaded start the calls
					self.startZoom();
					self.currentImage = self.imageSrc;
					//let caller know image has been loaded
					self.options.onZoomedImageLoaded(self.$elem);
				}
				newImg.src = imgsrc; // this must be done AFTER setting onload

				return;

			},

			startZoom: function( ) {
				var self = this;
				//get dimensions of the non zoomed image
				self.nzWidth = self.$elem.width();
				self.nzHeight = self.$elem.height();

				//activated elements
				self.isWindowActive = false;
				self.isLensActive = false;
				self.isTintActive = false;
				self.overWindow = false;    

				//CrossFade Wrappe
				if(self.options.imageCrossfade){
					self.zoomWrap = self.$elem.wrap('<div style="height:'+self.nzHeight+'px;width:'+self.nzWidth+'px;" class="zoomWrapper" />');        
					self.$elem.css('position', 'absolute'); 
				}

				self.zoomLock = 1;
				self.scrollingLock = false;
				self.changeBgSize = false;
				self.currentZoomLevel = self.options.zoomLevel;


				//get offset of the non zoomed image
				self.nzOffset = self.$elem.offset();
				//calculate the width ratio of the large/small image
				self.widthRatio = (self.largeWidth/self.currentZoomLevel) / self.nzWidth;
				self.heightRatio = (self.largeHeight/self.currentZoomLevel) / self.nzHeight; 


				//if window zoom        
				if(self.options.zoomType == "window") {
					self.zoomWindowStyle = "overflow: hidden;"
						+ "background-position: 0px 0px;text-align:center;"  
						+ "background-color: " + String(self.options.zoomWindowBgColour)            
						+ ";width: " + String(self.options.zoomWindowWidth) + "px;"
						+ "height: " + String(self.options.zoomWindowHeight)
						+ "px;float: left;"
						+ "background-size: "+ self.largeWidth/self.currentZoomLevel+ "px " +self.largeHeight/self.currentZoomLevel + "px;"
						+ "display: none;z-index:100;"
						+ "border: " + String(self.options.borderSize) 
						+ "px solid " + self.options.borderColour 
						+ ";background-repeat: no-repeat;"
						+ "position: absolute;";
				}    


				//if inner  zoom    
				if(self.options.zoomType == "inner") {
					//has a border been put on the image? Lets cater for this

					var borderWidth = self.$elem.css("border-left-width");

					self.zoomWindowStyle = "overflow: hidden;"
						+ "margin-left: " + String(borderWidth) + ";" 
						+ "margin-top: " + String(borderWidth) + ";"         
						+ "background-position: 0px 0px;"
						+ "width: " + String(self.nzWidth) + "px;"
						+ "height: " + String(self.nzHeight) + "px;"
						+ "px;float: left;"
						+ "display: none;"
						+ "cursor:"+(self.options.cursor)+";"
						+ "px solid " + self.options.borderColour 
						+ ";background-repeat: no-repeat;"
						+ "position: absolute;";
				}    



				//lens style for window zoom
				if(self.options.zoomType == "window") {


					// adjust images less than the window height

					if(self.nzHeight < self.options.zoomWindowWidth/self.widthRatio){
						lensHeight = self.nzHeight;              
					}
					else{
						lensHeight = String((self.options.zoomWindowHeight/self.heightRatio))
					}
					if(self.largeWidth < self.options.zoomWindowWidth){
						lensWidth = self.nzWidth;
					}       
					else{
						lensWidth =  (self.options.zoomWindowWidth/self.widthRatio);
					}


					self.lensStyle = "background-position: 0px 0px;width: " + String((self.options.zoomWindowWidth)/self.widthRatio) + "px;height: " + String((self.options.zoomWindowHeight)/self.heightRatio)
					+ "px;float: right;display: none;"
					+ "overflow: hidden;"
					+ "z-index: 999;"   
					+ "-webkit-transform: translateZ(0);"               
					+ "opacity:"+(self.options.lensOpacity)+";filter: alpha(opacity = "+(self.options.lensOpacity*100)+"); zoom:1;"
					+ "width:"+lensWidth+"px;"
					+ "height:"+lensHeight+"px;"
					+ "background-color:"+(self.options.lensColour)+";"					
					+ "cursor:"+(self.options.cursor)+";"
					+ "border: "+(self.options.lensBorderSize)+"px" +
					" solid "+(self.options.lensBorderColour)+";background-repeat: no-repeat;position: absolute;";
				} 


				//tint style
				self.tintStyle = "display: block;"
					+ "position: absolute;"
					+ "background-color: "+self.options.tintColour+";"	
					+ "filter:alpha(opacity=0);"		
					+ "opacity: 0;"	
					+ "width: " + self.nzWidth + "px;"
					+ "height: " + self.nzHeight + "px;"

					;

				//lens style for lens zoom with optional round for modern browsers
				self.lensRound = '';

				if(self.options.zoomType == "lens") {

					self.lensStyle = "background-position: 0px 0px;"
						+ "float: left;display: none;"
						+ "border: " + String(self.options.borderSize) + "px solid " + self.options.borderColour+";"
						+ "width:"+ String(self.options.lensSize) +"px;"
						+ "height:"+ String(self.options.lensSize)+"px;"
						+ "background-repeat: no-repeat;position: absolute;";


				}


				//does not round in all browsers
				if(self.options.lensShape == "round") {
					self.lensRound = "border-top-left-radius: " + String(self.options.lensSize / 2 + self.options.borderSize) + "px;"
					+ "border-top-right-radius: " + String(self.options.lensSize / 2 + self.options.borderSize) + "px;"
					+ "border-bottom-left-radius: " + String(self.options.lensSize / 2 + self.options.borderSize) + "px;"
					+ "border-bottom-right-radius: " + String(self.options.lensSize / 2 + self.options.borderSize) + "px;";

				}

				//create the div's                                                + ""
				//self.zoomContainer = $('<div/>').addClass('zoomContainer').css({"position":"relative", "height":self.nzHeight, "width":self.nzWidth});

				self.zoomContainer = $('<div class="zoomContainer" style="-webkit-transform: translateZ(0);position:absolute;left:'+self.nzOffset.left+'px;top:'+self.nzOffset.top+'px;height:'+self.nzHeight+'px;width:'+self.nzWidth+'px;"></div>');
				$('body').append(self.zoomContainer);	


				//this will add overflow hidden and contrain the lens on lens mode       
				if(self.options.containLensZoom && self.options.zoomType == "lens"){
					self.zoomContainer.css("overflow", "hidden");
				}
				if(self.options.zoomType != "inner") {
					self.zoomLens = $("<div class='zoomLens' style='" + self.lensStyle + self.lensRound +"'>&nbsp;</div>")
					.appendTo(self.zoomContainer)
					.click(function () {
						self.$elem.trigger('click');
					});


					if(self.options.tint) {
						self.tintContainer = $('<div/>').addClass('tintContainer');	
						self.zoomTint = $("<div class='zoomTint' style='"+self.tintStyle+"'></div>");


						self.zoomLens.wrap(self.tintContainer);


						self.zoomTintcss = self.zoomLens.after(self.zoomTint);	

						//if tint enabled - set an image to show over the tint

						self.zoomTintImage = $('<img style="position: absolute; left: 0px; top: 0px; max-width: none; width: '+self.nzWidth+'px; height: '+self.nzHeight+'px;" src="'+self.imageSrc+'">')
						.appendTo(self.zoomLens)
						.click(function () {

							self.$elem.trigger('click');
						});

					}          

				}







				//create zoom window 
				if(isNaN(self.options.zoomWindowPosition)){
					self.zoomWindow = $("<div style='z-index:999;left:"+(self.windowOffsetLeft)+"px;top:"+(self.windowOffsetTop)+"px;" + self.zoomWindowStyle + "' class='zoomWindow'>&nbsp;</div>")
					.appendTo('body')
					.click(function () {
						self.$elem.trigger('click');
					});
				}else{
					self.zoomWindow = $("<div style='z-index:999;left:"+(self.windowOffsetLeft)+"px;top:"+(self.windowOffsetTop)+"px;" + self.zoomWindowStyle + "' class='zoomWindow'>&nbsp;</div>")
					.appendTo(self.zoomContainer)
					.click(function () {
						self.$elem.trigger('click');
					});
				}              
				self.zoomWindowContainer = $('<div/>').addClass('zoomWindowContainer').css("width",self.options.zoomWindowWidth);
				self.zoomWindow.wrap(self.zoomWindowContainer);


				//  self.captionStyle = "text-align: left;background-color: black;color: white;font-weight: bold;padding: 10px;font-family: sans-serif;font-size: 11px";                                                                                                                                                                                                                                          
				// self.zoomCaption = $('<div class="elevatezoom-caption" style="'+self.captionStyle+'display: block; width: 280px;">INSERT ALT TAG</div>').appendTo(self.zoomWindow.parent());

				if(self.options.zoomType == "lens") {
					self.zoomLens.css({ backgroundImage: "url('" + self.imageSrc + "')" }); 
				}
				if(self.options.zoomType == "window") {
					self.zoomWindow.css({ backgroundImage: "url('" + self.imageSrc + "')" }); 
				}
				if(self.options.zoomType == "inner") {
					self.zoomWindow.css({ backgroundImage: "url('" + self.imageSrc + "')" }); 
				}
				/*-------------------END THE ZOOM WINDOW AND LENS----------------------------------*/
				//touch events
				self.$elem.bind('touchmove', function(e){    
					e.preventDefault();
					var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];  
					self.setPosition(touch);

				});  
				self.zoomContainer.bind('touchmove', function(e){ 
					if(self.options.zoomType == "inner") {
						self.showHideWindow("show");

					}
					e.preventDefault();
					var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];  
					self.setPosition(touch); 

				});  	
				self.zoomContainer.bind('touchend', function(e){ 
					self.showHideWindow("hide");
					if(self.options.showLens) {self.showHideLens("hide");}
					if(self.options.tint && self.options.zoomType != "inner") {self.showHideTint("hide");}
				});  	

				self.$elem.bind('touchend', function(e){ 
					self.showHideWindow("hide");
					if(self.options.showLens) {self.showHideLens("hide");}
					if(self.options.tint && self.options.zoomType != "inner") {self.showHideTint("hide");}
				});  	
				if(self.options.showLens) {
					self.zoomLens.bind('touchmove', function(e){ 

						e.preventDefault();
						var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];  
						self.setPosition(touch); 
					});    


					self.zoomLens.bind('touchend', function(e){ 
						self.showHideWindow("hide");
						if(self.options.showLens) {self.showHideLens("hide");}
						if(self.options.tint && self.options.zoomType != "inner") {self.showHideTint("hide");}
					});  
				}
				//Needed to work in IE
				self.$elem.bind('mousemove', function(e){   
					if(self.overWindow == false){self.setElements("show");}
					//make sure on orientation change the setposition is not fired
					if(self.lastX !== e.clientX || self.lastY !== e.clientY){
						self.setPosition(e);
						self.currentLoc = e;
					}   
					self.lastX = e.clientX;
					self.lastY = e.clientY;    

				});  	

				self.zoomContainer.bind('mousemove', function(e){ 

					if(self.overWindow == false){self.setElements("show");} 

					//make sure on orientation change the setposition is not fired 
					if(self.lastX !== e.clientX || self.lastY !== e.clientY){
						self.setPosition(e);
						self.currentLoc = e;
					}   
					self.lastX = e.clientX;
					self.lastY = e.clientY;    
				});  	
				if(self.options.zoomType != "inner") {
					self.zoomLens.bind('mousemove', function(e){      
						//make sure on orientation change the setposition is not fired
						if(self.lastX !== e.clientX || self.lastY !== e.clientY){
							self.setPosition(e);
							self.currentLoc = e;
						}   
						self.lastX = e.clientX;
						self.lastY = e.clientY;    
					});
				}
				if(self.options.tint && self.options.zoomType != "inner") {
					self.zoomTint.bind('mousemove', function(e){ 
						//make sure on orientation change the setposition is not fired
						if(self.lastX !== e.clientX || self.lastY !== e.clientY){
							self.setPosition(e);
							self.currentLoc = e;
						}   
						self.lastX = e.clientX;
						self.lastY = e.clientY;    
					});

				}
				if(self.options.zoomType == "inner") {
					self.zoomWindow.bind('mousemove', function(e) {
						//self.overWindow = true;
						//make sure on orientation change the setposition is not fired
						if(self.lastX !== e.clientX || self.lastY !== e.clientY){
							self.setPosition(e);
							self.currentLoc = e;
						}   
						self.lastX = e.clientX;
						self.lastY = e.clientY;    
					});

				}


				//  lensFadeOut: 500,  zoomTintFadeIn
				self.zoomContainer.add(self.$elem).mouseenter(function(){

					if(self.overWindow == false){self.setElements("show");} 


				}).mouseleave(function(){
					if(!self.scrollLock){
						self.setElements("hide");
            self.options.onDestroy(self.$elem);
					}
				});
				//end ove image





				if(self.options.zoomType != "inner") {
					self.zoomWindow.mouseenter(function(){
						self.overWindow = true;   
						self.setElements("hide");                  
					}).mouseleave(function(){

						self.overWindow = false;
					});
				}
				//end ove image



//				var delta = parseInt(e.originalEvent.wheelDelta || -e.originalEvent.detail);

				//      $(this).empty();    
				//    return false;

				//fix for initial zoom setting
				if (self.options.zoomLevel != 1){
					//	self.changeZoomLevel(self.currentZoomLevel);
				}
				//set the min zoomlevel
				if(self.options.minZoomLevel){
					self.minZoomLevel = self.options.minZoomLevel;
				}
				else{
					self.minZoomLevel = self.options.scrollZoomIncrement * 2;
				}


				if(self.options.scrollZoom){


					self.zoomContainer.add(self.$elem).bind('mousewheel DOMMouseScroll MozMousePixelScroll', function(e){


//						in IE there is issue with firing of mouseleave - So check whether still scrolling
//						and on mouseleave check if scrolllock          
						self.scrollLock = true;
						clearTimeout($.data(this, 'timer'));
						$.data(this, 'timer', setTimeout(function() {
							self.scrollLock = false;
							//do something
						}, 250));

						var theEvent = e.originalEvent.wheelDelta || e.originalEvent.detail*-1


						//this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
						//   e.preventDefault();


						e.stopImmediatePropagation();
						e.stopPropagation();
						e.preventDefault();


						if(theEvent /120 > 0) {
							//scrolling up
							if(self.currentZoomLevel >= self.minZoomLevel){ 
								self.changeZoomLevel(self.currentZoomLevel-self.options.scrollZoomIncrement);        
							}

						}
						else{
							//scrolling down


							if(self.options.maxZoomLevel){
								if(self.currentZoomLevel <= self.options.maxZoomLevel){           
									self.changeZoomLevel(parseFloat(self.currentZoomLevel)+self.options.scrollZoomIncrement);
								}
							}
							else{
								//andy 

								self.changeZoomLevel(parseFloat(self.currentZoomLevel)+self.options.scrollZoomIncrement);
							}

						}
						return false;
					});
				}


			},
			setElements: function(type) {
				var self = this;
        if(!self.options.zoomEnabled){return false;}
				if(type=="show"){
					if(self.isWindowSet){
						if(self.options.zoomType == "inner") {self.showHideWindow("show");}
						if(self.options.zoomType == "window") {self.showHideWindow("show");}
						if(self.options.showLens) {self.showHideLens("show");}
						if(self.options.tint && self.options.zoomType != "inner") {self.showHideTint("show");
						}
					}
				}

				if(type=="hide"){
					if(self.options.zoomType == "window") {self.showHideWindow("hide");}
					if(!self.options.tint) {self.showHideWindow("hide");}
					if(self.options.showLens) {self.showHideLens("hide");}
					if(self.options.tint) {	self.showHideTint("hide");}
				}   
			},
			setPosition: function(e) {
      
				var self = this;
        
        if(!self.options.zoomEnabled){return false;}

				//recaclc offset each time in case the image moves
				//this can be caused by other on page elements
				self.nzHeight = self.$elem.height();
				self.nzWidth = self.$elem.width();
				self.nzOffset = self.$elem.offset();

				if(self.options.tint && self.options.zoomType != "inner") {
					self.zoomTint.css({ top: 0});
					self.zoomTint.css({ left: 0});
				}
				//set responsive       
				//will checking if the image needs changing before running this code work faster?
				if(self.options.responsive && !self.options.scrollZoom){
					if(self.options.showLens){ 
						if(self.nzHeight < self.options.zoomWindowWidth/self.widthRatio){
							lensHeight = self.nzHeight;              
						}
						else{
							lensHeight = String((self.options.zoomWindowHeight/self.heightRatio))
						}
						if(self.largeWidth < self.options.zoomWindowWidth){
							lensWidth = self.nzWidth;
						}       
						else{
							lensWidth =  (self.options.zoomWindowWidth/self.widthRatio);
						}
						self.widthRatio = self.largeWidth / self.nzWidth;
						self.heightRatio = self.largeHeight / self.nzHeight;        
						if(self.options.zoomType != "lens") {


							//possibly dont need to keep recalcalculating
							//if the lens is heigher than the image, then set lens size to image size
							if(self.nzHeight < self.options.zoomWindowWidth/self.widthRatio){
								lensHeight = self.nzHeight;  

							}
							else{
								lensHeight = String((self.options.zoomWindowHeight/self.heightRatio))
							}

							if(self.nzWidth < self.options.zoomWindowHeight/self.heightRatio){
								lensWidth = self.nzWidth;
							}       
							else{
								lensWidth =  String((self.options.zoomWindowWidth/self.widthRatio));
							}            

							self.zoomLens.css('width', lensWidth);    
							self.zoomLens.css('height', lensHeight); 

							if(self.options.tint){    
								self.zoomTintImage.css('width', self.nzWidth);    
								self.zoomTintImage.css('height', self.nzHeight); 
							}

						}                     
						if(self.options.zoomType == "lens") {  

							self.zoomLens.css({ width: String(self.options.lensSize) + 'px', height: String(self.options.lensSize) + 'px' })      


						}        
						//end responsive image change
					}
				}

				//container fix
				self.zoomContainer.css({ top: self.nzOffset.top});
				self.zoomContainer.css({ left: self.nzOffset.left});
				self.mouseLeft = parseInt(e.pageX - self.nzOffset.left);
				self.mouseTop = parseInt(e.pageY - self.nzOffset.top);
				//calculate the Location of the Lens

				//calculate the bound regions - but only if zoom window
				if(self.options.zoomType == "window") {
					self.Etoppos = (self.mouseTop < (self.zoomLens.height()/2));
					self.Eboppos = (self.mouseTop > self.nzHeight - (self.zoomLens.height()/2)-(self.options.lensBorderSize*2));
					self.Eloppos = (self.mouseLeft < 0+((self.zoomLens.width()/2))); 
					self.Eroppos = (self.mouseLeft > (self.nzWidth - (self.zoomLens.width()/2)-(self.options.lensBorderSize*2)));  
				}
				//calculate the bound regions - but only for inner zoom
				if(self.options.zoomType == "inner"){ 
					self.Etoppos = (self.mouseTop < ((self.nzHeight/2)/self.heightRatio) );
					self.Eboppos = (self.mouseTop > (self.nzHeight - ((self.nzHeight/2)/self.heightRatio)));
					self.Eloppos = (self.mouseLeft < 0+(((self.nzWidth/2)/self.widthRatio)));
					self.Eroppos = (self.mouseLeft > (self.nzWidth - (self.nzWidth/2)/self.widthRatio-(self.options.lensBorderSize*2)));  
				}

				// if the mouse position of the slider is one of the outerbounds, then hide  window and lens
				if (self.mouseLeft < 0 || self.mouseTop < 0 || self.mouseLeft > self.nzWidth || self.mouseTop > self.nzHeight ) {				          
					self.setElements("hide");
					return;
				}
				//else continue with operations
				else {


					//lens options
					if(self.options.showLens) {
						//		self.showHideLens("show");
						//set background position of lens
						self.lensLeftPos = String(Math.floor(self.mouseLeft - self.zoomLens.width() / 2));
						self.lensTopPos = String(Math.floor(self.mouseTop - self.zoomLens.height() / 2));


					}
					//adjust the background position if the mouse is in one of the outer regions 

					//Top region
					if(self.Etoppos){
						self.lensTopPos = 0;
					}
					//Left Region
					if(self.Eloppos){
						self.windowLeftPos = 0;
						self.lensLeftPos = 0;
						self.tintpos=0;
					}     
					//Set bottom and right region for window mode
					if(self.options.zoomType == "window") {
						if(self.Eboppos){
							self.lensTopPos = Math.max( (self.nzHeight)-self.zoomLens.height()-(self.options.lensBorderSize*2), 0 );
						} 
						if(self.Eroppos){
							self.lensLeftPos = (self.nzWidth-(self.zoomLens.width())-(self.options.lensBorderSize*2));
						}  
					}  
					//Set bottom and right region for inner mode
					if(self.options.zoomType == "inner") {
						if(self.Eboppos){
							self.lensTopPos = Math.max( ((self.nzHeight)-(self.options.lensBorderSize*2)), 0 );
						} 
						if(self.Eroppos){
							self.lensLeftPos = (self.nzWidth-(self.nzWidth)-(self.options.lensBorderSize*2));
						}  

					}
					//if lens zoom
					if(self.options.zoomType == "lens") {  
						self.windowLeftPos = String(((e.pageX - self.nzOffset.left) * self.widthRatio - self.zoomLens.width() / 2) * (-1));   
						self.windowTopPos = String(((e.pageY - self.nzOffset.top) * self.heightRatio - self.zoomLens.height() / 2) * (-1));

						self.zoomLens.css({ backgroundPosition: self.windowLeftPos + 'px ' + self.windowTopPos + 'px' });

						if(self.changeBgSize){  

							if(self.nzHeight>self.nzWidth){  
								if(self.options.zoomType == "lens"){       
									self.zoomLens.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
								}   

								self.zoomWindow.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
							}
							else{     
								if(self.options.zoomType == "lens"){       
									self.zoomLens.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });
								}   
								self.zoomWindow.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });            
							}
							self.changeBgSize = false;
						}    

						self.setWindowPostition(e);  
					}
					//if tint zoom   
					if(self.options.tint && self.options.zoomType != "inner") {
						self.setTintPosition(e);

					}
					//set the css background position 
					if(self.options.zoomType == "window") {
						self.setWindowPostition(e);   
					}
					if(self.options.zoomType == "inner") {
						self.setWindowPostition(e);   
					}
					if(self.options.showLens) {

						if(self.fullwidth && self.options.zoomType != "lens"){
							self.lensLeftPos = 0;

						}
						self.zoomLens.css({ left: self.lensLeftPos + 'px', top: self.lensTopPos + 'px' })  
					}

				} //end else



			},
			showHideWindow: function(change) {
				var self = this;           
				if(change == "show"){      
					if(!self.isWindowActive && $(self.options.mainContainer + ':hover').length != 0){
						if(self.options.zoomWindowFadeIn){
							self.zoomWindow.stop(true, true, false).fadeIn(self.options.zoomWindowFadeIn);
						}
						else{self.zoomWindow.show();}
						self.isWindowActive = true;
					}            
				}
				if(change == "hide"){
					if(self.isWindowActive){
						if(self.options.zoomWindowFadeOut){
							self.zoomWindow.stop(true, true).fadeOut(self.options.zoomWindowFadeOut, function () {
								if (self.loop) {
									//stop moving the zoom window when zoom window is faded out
									clearInterval(self.loop);
									self.loop = false;
								}
							});
						}
						else{self.zoomWindow.hide();}
						self.isWindowActive = false;        
					}      
				}
			},
			showHideLens: function(change) {
				var self = this;              
				if(change == "show"){      
					if(!self.isLensActive && $(self.options.mainContainer + ':hover').length != 0){
						if(self.options.lensFadeIn){
							self.zoomLens.stop(true, true, false).fadeIn(self.options.lensFadeIn);
						}
						else{self.zoomLens.show();}
						self.isLensActive = true;
					}            
				}
				if(change == "hide"){
					if(self.isLensActive){
						if(self.options.lensFadeOut){
							self.zoomLens.stop(true, true).fadeOut(self.options.lensFadeOut);
						}
						else{self.zoomLens.hide();}
						self.isLensActive = false;        
					}      
				}
			},
			showHideTint: function(change) {
				var self = this;              
				if(change == "show"){      
					if(!self.isTintActive){

						if(self.options.zoomTintFadeIn){
							self.zoomTint.css({opacity:self.options.tintOpacity}).animate().stop(true, true).fadeIn("slow");
						}
						else{
							self.zoomTint.css({opacity:self.options.tintOpacity}).animate();
							self.zoomTint.show();


						}
						self.isTintActive = true;
					}            
				}
				if(change == "hide"){      
					if(self.isTintActive){ 

						if(self.options.zoomTintFadeOut){
							self.zoomTint.stop(true, true).fadeOut(self.options.zoomTintFadeOut);
						}
						else{self.zoomTint.hide();}
						self.isTintActive = false;        
					}      
				}
			},
			setLensPostition: function( e ) {


			},
			setWindowPostition: function( e ) {
				//return obj.slice( 0, count );
				var self = this;

				if(!isNaN(self.options.zoomWindowPosition)){

					switch (self.options.zoomWindowPosition) { 
					case 1: //done         
						self.windowOffsetTop = (self.options.zoomWindowOffety);//DONE - 1
						self.windowOffsetLeft =(+self.nzWidth); //DONE 1, 2, 3, 4, 16
						break;
					case 2:
						if(self.options.zoomWindowHeight > self.nzHeight){ //positive margin

							self.windowOffsetTop = ((self.options.zoomWindowHeight/2)-(self.nzHeight/2))*(-1);
							self.windowOffsetLeft =(self.nzWidth); //DONE 1, 2, 3, 4, 16
						}
						else{ //negative margin

						}
						break;
					case 3: //done        
						self.windowOffsetTop = (self.nzHeight - self.zoomWindow.height() - (self.options.borderSize*2)); //DONE 3,9
						self.windowOffsetLeft =(self.nzWidth); //DONE 1, 2, 3, 4, 16
						break;      
					case 4: //done  
						self.windowOffsetTop = (self.nzHeight); //DONE - 4,5,6,7,8
						self.windowOffsetLeft =(self.nzWidth); //DONE 1, 2, 3, 4, 16
						break;
					case 5: //done  
						self.windowOffsetTop = (self.nzHeight); //DONE - 4,5,6,7,8
						self.windowOffsetLeft =(self.nzWidth-self.zoomWindow.width()-(self.options.borderSize*2)); //DONE - 5,15
						break;
					case 6: 
						if(self.options.zoomWindowHeight > self.nzHeight){ //positive margin
							self.windowOffsetTop = (self.nzHeight);  //DONE - 4,5,6,7,8

							self.windowOffsetLeft =((self.options.zoomWindowWidth/2)-(self.nzWidth/2)+(self.options.borderSize*2))*(-1);  
						}
						else{ //negative margin

						}


						break;
					case 7: //done  
						self.windowOffsetTop = (self.nzHeight);  //DONE - 4,5,6,7,8
						self.windowOffsetLeft = 0; //DONE 7, 13
						break;
					case 8: //done  
						self.windowOffsetTop = (self.nzHeight); //DONE - 4,5,6,7,8
						self.windowOffsetLeft =(self.zoomWindow.width()+(self.options.borderSize*2) )* (-1);  //DONE 8,9,10,11,12
						break;
					case 9:  //done  
						self.windowOffsetTop = (self.nzHeight - self.zoomWindow.height() - (self.options.borderSize*2)); //DONE 3,9
						self.windowOffsetLeft =(self.zoomWindow.width()+(self.options.borderSize*2) )* (-1);  //DONE 8,9,10,11,12
						break;
					case 10: 
						if(self.options.zoomWindowHeight > self.nzHeight){ //positive margin

							self.windowOffsetTop = ((self.options.zoomWindowHeight/2)-(self.nzHeight/2))*(-1);
							self.windowOffsetLeft =(self.zoomWindow.width()+(self.options.borderSize*2) )* (-1);  //DONE 8,9,10,11,12
						}
						else{ //negative margin

						}
						break;
					case 11: 
						self.windowOffsetTop = (self.options.zoomWindowOffety);
						self.windowOffsetLeft =(self.zoomWindow.width()+(self.options.borderSize*2) )* (-1);  //DONE 8,9,10,11,12
						break;
					case 12: //done  
						self.windowOffsetTop = (self.zoomWindow.height()+(self.options.borderSize*2))*(-1); //DONE 12,13,14,15,16
						self.windowOffsetLeft =(self.zoomWindow.width()+(self.options.borderSize*2) )* (-1);  //DONE 8,9,10,11,12
						break;
					case 13: //done  
						self.windowOffsetTop = (self.zoomWindow.height()+(self.options.borderSize*2))*(-1); //DONE 12,13,14,15,16
						self.windowOffsetLeft =(0); //DONE 7, 13
						break;
					case 14: 
						if(self.options.zoomWindowHeight > self.nzHeight){ //positive margin
							self.windowOffsetTop = (self.zoomWindow.height()+(self.options.borderSize*2))*(-1); //DONE 12,13,14,15,16

							self.windowOffsetLeft =((self.options.zoomWindowWidth/2)-(self.nzWidth/2)+(self.options.borderSize*2))*(-1);  
						}
						else{ //negative margin

						}

						break;
					case 15://done   
						self.windowOffsetTop = (self.zoomWindow.height()+(self.options.borderSize*2))*(-1); //DONE 12,13,14,15,16
						self.windowOffsetLeft =(self.nzWidth-self.zoomWindow.width()-(self.options.borderSize*2)); //DONE - 5,15
						break;
					case 16:  //done  
						self.windowOffsetTop = (self.zoomWindow.height()+(self.options.borderSize*2))*(-1); //DONE 12,13,14,15,16
						self.windowOffsetLeft =(self.nzWidth); //DONE 1, 2, 3, 4, 16
						break;            
					default: //done  
						self.windowOffsetTop = (self.options.zoomWindowOffety);//DONE - 1
					self.windowOffsetLeft =(self.nzWidth); //DONE 1, 2, 3, 4, 16
					} 
				} //end isNAN
				else{
					//WE CAN POSITION IN A CLASS - ASSUME THAT ANY STRING PASSED IS
					self.externalContainer = $('#'+self.options.zoomWindowPosition);
					self.externalContainerWidth = self.externalContainer.width();
					self.externalContainerHeight = self.externalContainer.height();
					self.externalContainerOffset = self.externalContainer.offset();

					self.windowOffsetTop = self.externalContainerOffset.top;//DONE - 1
					self.windowOffsetLeft =self.externalContainerOffset.left; //DONE 1, 2, 3, 4, 16

				}
				self.isWindowSet = true;
				self.windowOffsetTop = self.windowOffsetTop + self.options.zoomWindowOffety;
				self.windowOffsetLeft = self.windowOffsetLeft + self.options.zoomWindowOffetx;

				self.zoomWindow.css({ top: self.windowOffsetTop});
				self.zoomWindow.css({ left: self.windowOffsetLeft});

				if(self.options.zoomType == "inner") {
					self.zoomWindow.css({ top: 0});
					self.zoomWindow.css({ left: 0});

				}   


				self.windowLeftPos = String(((e.pageX - self.nzOffset.left) * self.widthRatio - self.zoomWindow.width() / 2) * (-1));   
				self.windowTopPos = String(((e.pageY - self.nzOffset.top) * self.heightRatio - self.zoomWindow.height() / 2) * (-1));
				if(self.Etoppos){self.windowTopPos = 0;}
				if(self.Eloppos){self.windowLeftPos = 0;}     
				if(self.Eboppos){self.windowTopPos = (self.largeHeight/self.currentZoomLevel-self.zoomWindow.height())*(-1);  } 
				if(self.Eroppos){self.windowLeftPos = ((self.largeWidth/self.currentZoomLevel-self.zoomWindow.width())*(-1));}    

				//stops micro movements
				if(self.fullheight){
					self.windowTopPos = 0;

				}
				if(self.fullwidth){
					self.windowLeftPos = 0;

				}
				//set the css background position 


				if(self.options.zoomType == "window" || self.options.zoomType == "inner") {

					if(self.zoomLock == 1){
						//overrides for images not zoomable
						if(self.widthRatio <= 1){

							self.windowLeftPos = 0;
						}
						if(self.heightRatio <= 1){ 
							self.windowTopPos = 0;
						}
					}
					// adjust images less than the window height

					if (self.options.zoomType == "window") {
						if (self.largeHeight < self.options.zoomWindowHeight) {

							self.windowTopPos = 0;
						}
						if (self.largeWidth < self.options.zoomWindowWidth) {
							self.windowLeftPos = 0;
						}
					}

					//set the zoomwindow background position
					if (self.options.easing){

						//     if(self.changeZoom){
						//           clearInterval(self.loop);
						//           self.changeZoom = false;
						//           self.loop = false;

						//            }
						//set the pos to 0 if not set
						if(!self.xp){self.xp = 0;}
						if(!self.yp){self.yp = 0;}  
						//if loop not already started, then run it 
						if (!self.loop){           
							self.loop = setInterval(function(){                
								//using zeno's paradox    

								self.xp += (self.windowLeftPos  - self.xp) / self.options.easingAmount; 
								self.yp += (self.windowTopPos  - self.yp) / self.options.easingAmount;
								if(self.scrollingLock){


									clearInterval(self.loop);
									self.xp = self.windowLeftPos;
									self.yp = self.windowTopPos            

									self.xp = ((e.pageX - self.nzOffset.left) * self.widthRatio - self.zoomWindow.width() / 2) * (-1);
									self.yp = (((e.pageY - self.nzOffset.top) * self.heightRatio - self.zoomWindow.height() / 2) * (-1));                         

									if(self.changeBgSize){    
										if(self.nzHeight>self.nzWidth){  
											if(self.options.zoomType == "lens"){      
												self.zoomLens.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
											}   
											self.zoomWindow.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
										}
										else{   
											if(self.options.zoomType != "lens"){      
												self.zoomLens.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
											}            
											self.zoomWindow.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });            

										}

										/*
             if(!self.bgxp){self.bgxp = self.largeWidth/self.newvalue;}
						if(!self.bgyp){self.bgyp = self.largeHeight/self.newvalue ;}  
                 if (!self.bgloop){   
                 	self.bgloop = setInterval(function(){   

                 self.bgxp += (self.largeWidth/self.newvalue  - self.bgxp) / self.options.easingAmount; 
								self.bgyp += (self.largeHeight/self.newvalue  - self.bgyp) / self.options.easingAmount;

           self.zoomWindow.css({ "background-size": self.bgxp + 'px ' + self.bgyp + 'px' });


                  }, 16);

                 }
										 */
										self.changeBgSize = false;
									}

									self.zoomWindow.css({ backgroundPosition: self.windowLeftPos + 'px ' + self.windowTopPos + 'px' });
									self.scrollingLock = false;
									self.loop = false;

								}
								else if (Math.round(Math.abs(self.xp - self.windowLeftPos) + Math.abs(self.yp - self.windowTopPos)) < 1) {
									//stops micro movements
									clearInterval(self.loop);
									self.zoomWindow.css({ backgroundPosition: self.windowLeftPos + 'px ' + self.windowTopPos + 'px' });
									self.loop = false;
								}
								else{
									if(self.changeBgSize){    
										if(self.nzHeight>self.nzWidth){ 
											if(self.options.zoomType == "lens"){      
												self.zoomLens.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
											}         
											self.zoomWindow.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
										}
										else{                 
											if(self.options.zoomType != "lens"){     
												self.zoomLens.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });
											}      
											self.zoomWindow.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });            
										}
										self.changeBgSize = false;
									}                   

									self.zoomWindow.css({ backgroundPosition: self.xp + 'px ' + self.yp + 'px' });
								}       
							}, 16);
						}
					}   
					else{    
						if(self.changeBgSize){  
							if(self.nzHeight>self.nzWidth){  
								if(self.options.zoomType == "lens"){      
									self.zoomLens.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
								} 

								self.zoomWindow.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });
							}
							else{     
								if(self.options.zoomType == "lens"){      
									self.zoomLens.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });
								} 
								if((self.largeHeight/self.newvaluewidth) < self.options.zoomWindowHeight){ 

									self.zoomWindow.css({ "background-size": self.largeWidth/self.newvaluewidth + 'px ' + self.largeHeight/self.newvaluewidth + 'px' });            
								}
								else{

									self.zoomWindow.css({ "background-size": self.largeWidth/self.newvalueheight + 'px ' + self.largeHeight/self.newvalueheight + 'px' });   
								}

							}
							self.changeBgSize = false;
						}     

						self.zoomWindow.css({ backgroundPosition: self.windowLeftPos + 'px ' + self.windowTopPos + 'px' });       
					}
				} 
			},
			setTintPosition: function(e){
				var self = this;
				self.nzOffset = self.$elem.offset();
				self.tintpos = String(((e.pageX - self.nzOffset.left)-(self.zoomLens.width() / 2)) * (-1)); 
				self.tintposy = String(((e.pageY - self.nzOffset.top) - self.zoomLens.height() / 2) * (-1));	
				if(self.Etoppos){
					self.tintposy = 0;
				}
				if(self.Eloppos){
					self.tintpos=0;
				}     
				if(self.Eboppos){
					self.tintposy = (self.nzHeight-self.zoomLens.height()-(self.options.lensBorderSize*2))*(-1);
				} 
				if(self.Eroppos){
					self.tintpos = ((self.nzWidth-self.zoomLens.width()-(self.options.lensBorderSize*2))*(-1));
				}    
				if(self.options.tint) {
					//stops micro movements
					if(self.fullheight){
						self.tintposy = 0;

					}
					if(self.fullwidth){ 
						self.tintpos = 0;

					}   
					self.zoomTintImage.css({'left': self.tintpos+'px'});
					self.zoomTintImage.css({'top': self.tintposy+'px'});
				}
			},

			swaptheimage: function(smallimage, largeimage){
				var self = this;
				var newImg = new Image(); 

				if(self.options.loadingIcon){
					self.spinner = $('<div style="background: url(\''+self.options.loadingIcon+'\') no-repeat center;height:'+self.nzHeight+'px;width:'+self.nzWidth+'px;z-index: 2000;position: absolute; background-position: center center;"></div>');
					self.$elem.after(self.spinner);
				}

				self.options.onImageSwap(self.$elem);

				newImg.onload = function() {
					self.largeWidth = newImg.width;
					self.largeHeight = newImg.height;
					self.zoomImage = largeimage;
					self.zoomWindow.css({ "background-size": self.largeWidth + 'px ' + self.largeHeight + 'px' });
					self.swapAction(smallimage, largeimage);
					return;              
				}          
				newImg.src = largeimage; // this must be done AFTER setting onload

			},
			swapAction: function(smallimage, largeimage){


				var self = this;    

				var newImg2 = new Image(); 
				newImg2.onload = function() {
					//re-calculate values
					self.nzHeight = newImg2.height;
					self.nzWidth = newImg2.width;
					self.options.onImageSwapComplete(self.$elem);

					self.doneCallback();  
					return;      
				}          
				newImg2.src = smallimage; 

				//reset the zoomlevel to that initially set in options
				self.currentZoomLevel = self.options.zoomLevel;
				self.options.maxZoomLevel = false;

				//swaps the main image
				//self.$elem.attr("src",smallimage);
				//swaps the zoom image     
				if(self.options.zoomType == "lens") {
					self.zoomLens.css({ backgroundImage: "url('" + largeimage + "')" }); 
				}
				if(self.options.zoomType == "window") {
					self.zoomWindow.css({ backgroundImage: "url('" + largeimage + "')" }); 
				}
				if(self.options.zoomType == "inner") {
					self.zoomWindow.css({ backgroundImage: "url('" + largeimage + "')" }); 
				} 



				self.currentImage = largeimage;

				if(self.options.imageCrossfade){
					var oldImg = self.$elem;
					var newImg = oldImg.clone();         
					self.$elem.attr("src",smallimage)
					self.$elem.after(newImg);
					newImg.stop(true).fadeOut(self.options.imageCrossfade, function() {
						$(this).remove();         
					});

					//       				if(self.options.zoomType == "inner"){
					//remove any attributes on the cloned image so we can resize later
					self.$elem.width("auto").removeAttr("width");
					self.$elem.height("auto").removeAttr("height");
					//   }

					oldImg.fadeIn(self.options.imageCrossfade);

					if(self.options.tint && self.options.zoomType != "inner") {

						var oldImgTint = self.zoomTintImage;
						var newImgTint = oldImgTint.clone();         
						self.zoomTintImage.attr("src",largeimage)
						self.zoomTintImage.after(newImgTint);
						newImgTint.stop(true).fadeOut(self.options.imageCrossfade, function() {
							$(this).remove();         
						});



						oldImgTint.fadeIn(self.options.imageCrossfade);


						//self.zoomTintImage.attr("width",elem.data("image"));

						//resize the tint window
						self.zoomTint.css({ height: self.$elem.height()});
						self.zoomTint.css({ width: self.$elem.width()});
					}    

					self.zoomContainer.css("height", self.$elem.height());
					self.zoomContainer.css("width", self.$elem.width());

					if(self.options.zoomType == "inner"){ 
						if(!self.options.constrainType){
							self.zoomWrap.parent().css("height", self.$elem.height());
							self.zoomWrap.parent().css("width", self.$elem.width());

							self.zoomWindow.css("height", self.$elem.height());
							self.zoomWindow.css("width", self.$elem.width());
						}
					} 

					if(self.options.imageCrossfade){  
						self.zoomWrap.css("height", self.$elem.height());
						self.zoomWrap.css("width", self.$elem.width());
					} 
				}
				else{
					self.$elem.attr("src",smallimage); 
					if(self.options.tint) {
						self.zoomTintImage.attr("src",largeimage);
						//self.zoomTintImage.attr("width",elem.data("image"));
						self.zoomTintImage.attr("height",self.$elem.height());
						//self.zoomTintImage.attr('src') = elem.data("image");
						self.zoomTintImage.css({ height: self.$elem.height()}); 
						self.zoomTint.css({ height: self.$elem.height()});

					}
					self.zoomContainer.css("height", self.$elem.height());
					self.zoomContainer.css("width", self.$elem.width());

					if(self.options.imageCrossfade){  
						self.zoomWrap.css("height", self.$elem.height());
						self.zoomWrap.css("width", self.$elem.width());
					} 
				}              
				if(self.options.constrainType){     

					//This will contrain the image proportions
					if(self.options.constrainType == "height"){ 

						self.zoomContainer.css("height", self.options.constrainSize);
						self.zoomContainer.css("width", "auto");

						if(self.options.imageCrossfade){  
							self.zoomWrap.css("height", self.options.constrainSize);
							self.zoomWrap.css("width", "auto"); 
							self.constwidth = self.zoomWrap.width();


						}
						else{                  
							self.$elem.css("height", self.options.constrainSize);
							self.$elem.css("width", "auto");
							self.constwidth = self.$elem.width();
						} 

						if(self.options.zoomType == "inner"){

							self.zoomWrap.parent().css("height", self.options.constrainSize);
							self.zoomWrap.parent().css("width", self.constwidth);   
							self.zoomWindow.css("height", self.options.constrainSize);
							self.zoomWindow.css("width", self.constwidth);    
						}        
						if(self.options.tint){
							self.tintContainer.css("height", self.options.constrainSize);
							self.tintContainer.css("width", self.constwidth);
							self.zoomTint.css("height", self.options.constrainSize);
							self.zoomTint.css("width", self.constwidth);
							self.zoomTintImage.css("height", self.options.constrainSize);
							self.zoomTintImage.css("width", self.constwidth); 
						} 

					}
					if(self.options.constrainType == "width"){       
						self.zoomContainer.css("height", "auto");
						self.zoomContainer.css("width", self.options.constrainSize);

						if(self.options.imageCrossfade){
							self.zoomWrap.css("height", "auto");
							self.zoomWrap.css("width", self.options.constrainSize);
							self.constheight = self.zoomWrap.height();
						}
						else{            
							self.$elem.css("height", "auto");
							self.$elem.css("width", self.options.constrainSize); 
							self.constheight = self.$elem.height();              
						} 
						if(self.options.zoomType == "inner"){
							self.zoomWrap.parent().css("height", self.constheight);
							self.zoomWrap.parent().css("width", self.options.constrainSize);   
							self.zoomWindow.css("height", self.constheight);
							self.zoomWindow.css("width", self.options.constrainSize);    
						} 
						if(self.options.tint){
							self.tintContainer.css("height", self.constheight);
							self.tintContainer.css("width", self.options.constrainSize);
							self.zoomTint.css("height", self.constheight);
							self.zoomTint.css("width", self.options.constrainSize);
							self.zoomTintImage.css("height", self.constheight);
							self.zoomTintImage.css("width", self.options.constrainSize); 
						}   

					}        


				}

			},
			doneCallback: function(){

				var self = this;
				if(self.options.loadingIcon){
					self.spinner.hide();     
				}   

				self.nzOffset = self.$elem.offset();
				self.nzWidth = self.$elem.width();
				self.nzHeight = self.$elem.height();

				// reset the zoomlevel back to default
				self.currentZoomLevel = self.options.zoomLevel;

				//ratio of the large to small image
				self.widthRatio = self.largeWidth / self.nzWidth;
				self.heightRatio = self.largeHeight / self.nzHeight; 

				//NEED TO ADD THE LENS SIZE FOR ROUND
				// adjust images less than the window height
				if(self.options.zoomType == "window") {

					if(self.nzHeight < self.options.zoomWindowWidth/self.widthRatio){
						lensHeight = self.nzHeight;  

					}
					else{
						lensHeight = String((self.options.zoomWindowHeight/self.heightRatio))
					}

					if(self.options.zoomWindowWidth < self.options.zoomWindowWidth){
						lensWidth = self.nzWidth;
					}       
					else{
						lensWidth =  (self.options.zoomWindowWidth/self.widthRatio);
					}


					if(self.zoomLens){

						self.zoomLens.css('width', lensWidth);    
						self.zoomLens.css('height', lensHeight); 


					}
				}
			},
			getCurrentImage: function(){
				var self = this;  
				return self.zoomImage; 
			}, 
			getGalleryList: function(){
				var self = this;   
				//loop through the gallery options and set them in list for fancybox
				self.gallerylist = [];
				if (self.options.gallery){ 


					$('#'+self.options.gallery + ' a').each(function() {

						var img_src = '';
						if($(this).data("zoom-image")){
							img_src = $(this).data("zoom-image");
						}
						else if($(this).data("image")){
							img_src = $(this).data("image");
						}			
						//put the current image at the start
						if(img_src == self.zoomImage){
							self.gallerylist.unshift({
								href: ''+img_src+'',
								title: $(this).find('img').attr("title")
							});	
						}
						else{
							self.gallerylist.push({
								href: ''+img_src+'',
								title: $(this).find('img').attr("title")
							});
						}


					});
				}                                                       
				//if no gallery - return current image
				else{
					self.gallerylist.push({
						href: ''+self.zoomImage+'',
						title: $(this).find('img').attr("title")
					}); 
				}
				return self.gallerylist;

			},
			changeZoomLevel: function(value){
				var self = this;   

				//flag a zoom, so can adjust the easing during setPosition     
				self.scrollingLock = true;   

				//round to two decimal places
				self.newvalue = parseFloat(value).toFixed(2);
				newvalue = parseFloat(value).toFixed(2);




				//maxwidth & Maxheight of the image
				maxheightnewvalue = self.largeHeight/((self.options.zoomWindowHeight / self.nzHeight) * self.nzHeight);     
				maxwidthtnewvalue = self.largeWidth/((self.options.zoomWindowWidth / self.nzWidth) * self.nzWidth);   	




				//calculate new heightratio
				if(self.options.zoomType != "inner")
				{
					if(maxheightnewvalue <= newvalue){
						self.heightRatio = (self.largeHeight/maxheightnewvalue) / self.nzHeight;
						self.newvalueheight = maxheightnewvalue;
						self.fullheight = true;

					}
					else{
						self.heightRatio = (self.largeHeight/newvalue) / self.nzHeight; 
						self.newvalueheight = newvalue;
						self.fullheight = false;

					}


//					calculate new width ratio

					if(maxwidthtnewvalue <= newvalue){
						self.widthRatio = (self.largeWidth/maxwidthtnewvalue) / self.nzWidth;
						self.newvaluewidth = maxwidthtnewvalue;
						self.fullwidth = true;

					}
					else{
						self.widthRatio = (self.largeWidth/newvalue) / self.nzWidth; 
						self.newvaluewidth = newvalue;
						self.fullwidth = false;

					}
					if(self.options.zoomType == "lens"){
						if(maxheightnewvalue <= newvalue){
							self.fullwidth = true;
							self.newvaluewidth = maxheightnewvalue;

						} else{
							self.widthRatio = (self.largeWidth/newvalue) / self.nzWidth; 
							self.newvaluewidth = newvalue;

							self.fullwidth = false;
						}}
				}



				if(self.options.zoomType == "inner")
				{
					maxheightnewvalue = parseFloat(self.largeHeight/self.nzHeight).toFixed(2);     
					maxwidthtnewvalue = parseFloat(self.largeWidth/self.nzWidth).toFixed(2);      
					if(newvalue > maxheightnewvalue){
						newvalue = maxheightnewvalue;
					}
					if(newvalue > maxwidthtnewvalue){
						newvalue = maxwidthtnewvalue;
					}      


					if(maxheightnewvalue <= newvalue){


						self.heightRatio = (self.largeHeight/newvalue) / self.nzHeight; 
						if(newvalue > maxheightnewvalue){
							self.newvalueheight = maxheightnewvalue;
						}else{
							self.newvalueheight = newvalue;
						}
						self.fullheight = true;


					}
					else{



						self.heightRatio = (self.largeHeight/newvalue) / self.nzHeight; 

						if(newvalue > maxheightnewvalue){

							self.newvalueheight = maxheightnewvalue;
						}else{
							self.newvalueheight = newvalue;
						}
						self.fullheight = false;
					}




					if(maxwidthtnewvalue <= newvalue){   

						self.widthRatio = (self.largeWidth/newvalue) / self.nzWidth; 
						if(newvalue > maxwidthtnewvalue){

							self.newvaluewidth = maxwidthtnewvalue;
						}else{
							self.newvaluewidth = newvalue;
						}

						self.fullwidth = true;


					}
					else{  

						self.widthRatio = (self.largeWidth/newvalue) / self.nzWidth; 
						self.newvaluewidth = newvalue;
						self.fullwidth = false;
					}        


				} //end inner
				scrcontinue = false;

				if(self.options.zoomType == "inner"){

					if(self.nzWidth >= self.nzHeight){
						if( self.newvaluewidth <= maxwidthtnewvalue){
							scrcontinue = true;
						}
						else{

							scrcontinue = false;
							self.fullheight = true;
							self.fullwidth = true;
						}
					}
					if(self.nzHeight > self.nzWidth){     
						if( self.newvaluewidth <= maxwidthtnewvalue){
							scrcontinue = true;
						}
						else{
							scrcontinue = false;  

							self.fullheight = true;
							self.fullwidth = true;
						}
					}
				}

				if(self.options.zoomType != "inner"){
					scrcontinue = true;
				}

				if(scrcontinue){



					self.zoomLock = 0;
					self.changeZoom = true;

					//if lens height is less than image height


					if(((self.options.zoomWindowHeight)/self.heightRatio) <= self.nzHeight){


						self.currentZoomLevel = self.newvalueheight; 
						if(self.options.zoomType != "lens" && self.options.zoomType != "inner") {
							self.changeBgSize = true;

							self.zoomLens.css({height: String((self.options.zoomWindowHeight)/self.heightRatio) + 'px' }) 
						}
						if(self.options.zoomType == "lens" || self.options.zoomType == "inner") {  
							self.changeBgSize = true;  
						}	


					} 




					if((self.options.zoomWindowWidth/self.widthRatio) <= self.nzWidth){



						if(self.options.zoomType != "inner"){
							if(self.newvaluewidth > self.newvalueheight)   {
								self.currentZoomLevel = self.newvaluewidth;                 

							}
						}

						if(self.options.zoomType != "lens" && self.options.zoomType != "inner") {
							self.changeBgSize = true;

							self.zoomLens.css({width: String((self.options.zoomWindowWidth)/self.widthRatio) + 'px' })
						}
						if(self.options.zoomType == "lens" || self.options.zoomType == "inner") {  
							self.changeBgSize = true;
						}	

					}
					if(self.options.zoomType == "inner"){
						self.changeBgSize = true;  

						if(self.nzWidth > self.nzHeight){
							self.currentZoomLevel = self.newvaluewidth;
						}
						if(self.nzHeight > self.nzWidth){
							self.currentZoomLevel = self.newvaluewidth;
						}
					}

				}      //under

				//sets the boundry change, called in setWindowPos
				self.setPosition(self.currentLoc);
				//
			},
			closeAll: function(){
				if(self.zoomWindow){self.zoomWindow.hide();}
				if(self.zoomLens){self.zoomLens.hide();}
				if(self.zoomTint){self.zoomTint.hide();}
			},
			changeState: function(value){
      	var self = this;
				if(value == 'enable'){self.options.zoomEnabled = true;}
				if(value == 'disable'){self.options.zoomEnabled = false;}

			}

	};




	$.fn.elevateZoom = function( options ) {
		return this.each(function() {
			var elevate = Object.create( ElevateZoom );

			elevate.init( options, this );

			$.data( this, 'elevateZoom', elevate );

		});
	};

	$.fn.elevateZoom.options = {
			zoomActivation: "hover", // Can also be click (PLACEHOLDER FOR NEXT VERSION)
      zoomEnabled: true, //false disables zoomwindow from showing
			preloading: 1, //by default, load all the images, if 0, then only load images after activated (PLACEHOLDER FOR NEXT VERSION)
			zoomLevel: 1, //default zoom level of image
			scrollZoom: false, //allow zoom on mousewheel, true to activate
			scrollZoomIncrement: 0.1,  //steps of the scrollzoom
			minZoomLevel: false,
			maxZoomLevel: false,
			easing: false,
			easingAmount: 12,
			lensSize: 200,
			zoomWindowWidth: 400,
			zoomWindowHeight: 400,
			zoomWindowOffetx: 0,
			zoomWindowOffety: 0,
			zoomWindowPosition: 1,
			zoomWindowBgColour: "#fff",
			lensFadeIn: false,
			lensFadeOut: false,
			debug: false,
			zoomWindowFadeIn: false,
			zoomWindowFadeOut: false,
			zoomWindowAlwaysShow: false,
			zoomTintFadeIn: false,
			zoomTintFadeOut: false,
			borderSize: 4,
			showLens: true,
			borderColour: "#888",
			lensBorderSize: 1,
			lensBorderColour: "#000",
			lensShape: "square", //can be "round"
			zoomType: "window", //window is default,  also "lens" available -
			containLensZoom: false,
			lensColour: "white", //colour of the lens background
			lensOpacity: 0.4, //opacity of the lens
			lenszoom: false,
			tint: false, //enable the tinting
			tintColour: "#333", //default tint color, can be anything, red, #ccc, rgb(0,0,0)
			tintOpacity: 0.4, //opacity of the tint
			gallery: false,
			galleryActiveClass: "zoomGalleryActive",
			imageCrossfade: false,
			constrainType: false,  //width or height
			constrainSize: false,  //in pixels the dimensions you want to constrain on
			loadingIcon: false, //http://www.example.com/spinner.gif
			cursor:"default", // user should set to what they want the cursor as, if they have set a click function
			responsive:true,
			onComplete: $.noop,
      onDestroy: function() {},
			onZoomedImageLoaded: function() {},
			onImageSwap: $.noop,
			onImageSwapComplete: $.noop,
            mainContainer: 'html'
	};

})( jQuery, window, document );;

/********************************
/site/resources/jquery.mousewheel-3.0.6.pack.js
********************************/
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.6
 * 
 * Requires: 1.2.2+
 */
(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=
d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);;

/********************************
/site/resources/jquery.fancybox.pack.js
********************************/
/*! fancyBox v2.1.4 fancyapps.com | fancyapps.com/fancybox/#license */
(function(C,z,f,r){var q=f(C),n=f(z),b=f.fancybox=function(){b.open.apply(this,arguments)},H=navigator.userAgent.match(/msie/),w=null,s=z.createTouch!==r,t=function(a){return a&&a.hasOwnProperty&&a instanceof f},p=function(a){return a&&"string"===f.type(a)},F=function(a){return p(a)&&0<a.indexOf("%")},l=function(a,d){var e=parseInt(a,10)||0;d&&F(a)&&(e*=b.getViewport()[d]/100);return Math.ceil(e)},x=function(a,b){return l(a,b)+"px"};f.extend(b,{version:"2.1.4",defaults:{padding:15,margin:20,width:800,
height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!0,autoCenter:!s,fitToView:!0,aspectRatio:!1,topRatio:0.5,leftRatio:0.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3E3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},keys:{next:{13:"left",
34:"up",39:"left",40:"up"},prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'+
(H?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',closeBtn:'<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:"fade",openSpeed:250,openEasing:"swing",openOpacity:!0,
openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:f.noop,beforeLoad:f.noop,afterLoad:f.noop,beforeShow:f.noop,afterShow:f.noop,beforeChange:f.noop,beforeClose:f.noop,afterClose:f.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:!1,
isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(a,d){if(a&&(f.isPlainObject(d)||(d={}),!1!==b.close(!0)))return f.isArray(a)||(a=t(a)?f(a).get():[a]),f.each(a,function(e,c){var k={},g,h,j,m,l;"object"===f.type(c)&&(c.nodeType&&(c=f(c)),t(c)?(k={href:c.data("fancybox-href")||c.attr("href"),title:c.data("fancybox-title")||c.attr("title"),isDom:!0,element:c},f.metadata&&f.extend(!0,k,
c.metadata())):k=c);g=d.href||k.href||(p(c)?c:null);h=d.title!==r?d.title:k.title||"";m=(j=d.content||k.content)?"html":d.type||k.type;!m&&k.isDom&&(m=c.data("fancybox-type"),m||(m=(m=c.prop("class").match(/fancybox\.(\w+)/))?m[1]:null));p(g)&&(m||(b.isImage(g)?m="image":b.isSWF(g)?m="swf":"#"===g.charAt(0)?m="inline":p(c)&&(m="html",j=c)),"ajax"===m&&(l=g.split(/\s+/,2),g=l.shift(),l=l.shift()));j||("inline"===m?g?j=f(p(g)?g.replace(/.*(?=#[^\s]+$)/,""):g):k.isDom&&(j=c):"html"===m?j=g:!m&&(!g&&
k.isDom)&&(m="inline",j=c));f.extend(k,{href:g,type:m,content:j,title:h,selector:l});a[e]=k}),b.opts=f.extend(!0,{},b.defaults,d),d.keys!==r&&(b.opts.keys=d.keys?f.extend({},b.defaults.keys,d.keys):!1),b.group=a,b._start(b.opts.index)},cancel:function(){var a=b.coming;a&&!1!==b.trigger("onCancel")&&(b.hideLoading(),b.ajaxLoad&&b.ajaxLoad.abort(),b.ajaxLoad=null,b.imgPreload&&(b.imgPreload.onload=b.imgPreload.onerror=null),a.wrap&&a.wrap.stop(!0,!0).trigger("onReset").remove(),b.coming=null,b.current||
b._afterZoomOut(a))},close:function(a){b.cancel();!1!==b.trigger("beforeClose")&&(b.unbindEvents(),b.isActive&&(!b.isOpen||!0===a?(f(".fancybox-wrap").stop(!0).trigger("onReset").remove(),b._afterZoomOut()):(b.isOpen=b.isOpened=!1,b.isClosing=!0,f(".fancybox-item, .fancybox-nav").remove(),b.wrap.stop(!0,!0).removeClass("fancybox-opened"),b.transitions[b.current.closeMethod]())))},play:function(a){var d=function(){clearTimeout(b.player.timer)},e=function(){d();b.current&&b.player.isActive&&(b.player.timer=
setTimeout(b.next,b.current.playSpeed))},c=function(){d();f("body").unbind(".player");b.player.isActive=!1;b.trigger("onPlayEnd")};if(!0===a||!b.player.isActive&&!1!==a){if(b.current&&(b.current.loop||b.current.index<b.group.length-1))b.player.isActive=!0,f("body").bind({"afterShow.player onUpdate.player":e,"onCancel.player beforeClose.player":c,"beforeLoad.player":d}),e(),b.trigger("onPlayStart")}else c()},next:function(a){var d=b.current;d&&(p(a)||(a=d.direction.next),b.jumpto(d.index+1,a,"next"))},
prev:function(a){var d=b.current;d&&(p(a)||(a=d.direction.prev),b.jumpto(d.index-1,a,"prev"))},jumpto:function(a,d,e){var c=b.current;c&&(a=l(a),b.direction=d||c.direction[a>=c.index?"next":"prev"],b.router=e||"jumpto",c.loop&&(0>a&&(a=c.group.length+a%c.group.length),a%=c.group.length),c.group[a]!==r&&(b.cancel(),b._start(a)))},reposition:function(a,d){var e=b.current,c=e?e.wrap:null,k;c&&(k=b._getPosition(d),a&&"scroll"===a.type?(delete k.position,c.stop(!0,!0).animate(k,200)):(c.css(k),e.pos=f.extend({},
e.dim,k)))},update:function(a){var d=a&&a.type,e=!d||"orientationchange"===d;e&&(clearTimeout(w),w=null);b.isOpen&&!w&&(w=setTimeout(function(){var c=b.current;c&&!b.isClosing&&(b.wrap.removeClass("fancybox-tmp"),(e||"load"===d||"resize"===d&&c.autoResize)&&b._setDimension(),"scroll"===d&&c.canShrink||b.reposition(a),b.trigger("onUpdate"),w=null)},e&&!s?0:300))},toggle:function(a){b.isOpen&&(b.current.fitToView="boolean"===f.type(a)?a:!b.current.fitToView,s&&(b.wrap.removeAttr("style").addClass("fancybox-tmp"),
b.trigger("onUpdate")),b.update())},hideLoading:function(){n.unbind(".loading");f("#fancybox-loading").remove()},showLoading:function(){var a,d;b.hideLoading();a=f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body");n.bind("keydown.loading",function(a){if(27===(a.which||a.keyCode))a.preventDefault(),b.cancel()});b.defaults.fixed||(d=b.getViewport(),a.css({position:"absolute",top:0.5*d.h+d.y,left:0.5*d.w+d.x}))},getViewport:function(){var a=b.current&&b.current.locked||
!1,d={x:q.scrollLeft(),y:q.scrollTop()};a?(d.w=a[0].clientWidth,d.h=a[0].clientHeight):(d.w=s&&C.innerWidth?C.innerWidth:q.width(),d.h=s&&C.innerHeight?C.innerHeight:q.height());return d},unbindEvents:function(){b.wrap&&t(b.wrap)&&b.wrap.unbind(".fb");n.unbind(".fb");q.unbind(".fb")},bindEvents:function(){var a=b.current,d;a&&(q.bind("orientationchange.fb"+(s?"":" resize.fb")+(a.autoCenter&&!a.locked?" scroll.fb":""),b.update),(d=a.keys)&&n.bind("keydown.fb",function(e){var c=e.which||e.keyCode,k=
e.target||e.srcElement;if(27===c&&b.coming)return!1;!e.ctrlKey&&(!e.altKey&&!e.shiftKey&&!e.metaKey&&(!k||!k.type&&!f(k).is("[contenteditable]")))&&f.each(d,function(d,k){if(1<a.group.length&&k[c]!==r)return b[d](k[c]),e.preventDefault(),!1;if(-1<f.inArray(c,k))return b[d](),e.preventDefault(),!1})}),f.fn.mousewheel&&a.mouseWheel&&b.wrap.bind("mousewheel.fb",function(d,c,k,g){for(var h=f(d.target||null),j=!1;h.length&&!j&&!h.is(".fancybox-skin")&&!h.is(".fancybox-wrap");)j=h[0]&&!(h[0].style.overflow&&
"hidden"===h[0].style.overflow)&&(h[0].clientWidth&&h[0].scrollWidth>h[0].clientWidth||h[0].clientHeight&&h[0].scrollHeight>h[0].clientHeight),h=f(h).parent();if(0!==c&&!j&&1<b.group.length&&!a.canShrink){if(0<g||0<k)b.prev(0<g?"down":"left");else if(0>g||0>k)b.next(0>g?"up":"right");d.preventDefault()}}))},trigger:function(a,d){var e,c=d||b.coming||b.current;if(c){f.isFunction(c[a])&&(e=c[a].apply(c,Array.prototype.slice.call(arguments,1)));if(!1===e)return!1;c.helpers&&f.each(c.helpers,function(d,
e){e&&(b.helpers[d]&&f.isFunction(b.helpers[d][a]))&&(e=f.extend(!0,{},b.helpers[d].defaults,e),b.helpers[d][a](e,c))});f.event.trigger(a+".fb")}},isImage:function(a){return p(a)&&a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp)((\?|#).*)?$)/i)},isSWF:function(a){return p(a)&&a.match(/\.(swf)((\?|#).*)?$/i)},_start:function(a){var d={},e,c;a=l(a);e=b.group[a]||null;if(!e)return!1;d=f.extend(!0,{},b.opts,e);e=d.margin;c=d.padding;"number"===f.type(e)&&(d.margin=[e,e,e,e]);"number"===f.type(c)&&
(d.padding=[c,c,c,c]);d.modal&&f.extend(!0,d,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}});d.autoSize&&(d.autoWidth=d.autoHeight=!0);"auto"===d.width&&(d.autoWidth=!0);"auto"===d.height&&(d.autoHeight=!0);d.group=b.group;d.index=a;b.coming=d;if(!1===b.trigger("beforeLoad"))b.coming=null;else{c=d.type;e=d.href;if(!c)return b.coming=null,b.current&&b.router&&"jumpto"!==b.router?(b.current.index=a,b[b.router](b.direction)):!1;b.isActive=
!0;if("image"===c||"swf"===c)d.autoHeight=d.autoWidth=!1,d.scrolling="visible";"image"===c&&(d.aspectRatio=!0);"iframe"===c&&s&&(d.scrolling="scroll");d.wrap=f(d.tpl.wrap).addClass("fancybox-"+(s?"mobile":"desktop")+" fancybox-type-"+c+" fancybox-tmp "+d.wrapCSS).appendTo(d.parent||"body");f.extend(d,{skin:f(".fancybox-skin",d.wrap),outer:f(".fancybox-outer",d.wrap),inner:f(".fancybox-inner",d.wrap)});f.each(["Top","Right","Bottom","Left"],function(a,b){d.skin.css("padding"+b,x(d.padding[a]))});b.trigger("onReady");
if("inline"===c||"html"===c){if(!d.content||!d.content.length)return b._error("content")}else if(!e)return b._error("href");"image"===c?b._loadImage():"ajax"===c?b._loadAjax():"iframe"===c?b._loadIframe():b._afterLoad()}},_error:function(a){f.extend(b.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:a,content:b.coming.tpl.error});b._afterLoad()},_loadImage:function(){var a=b.imgPreload=new Image;a.onload=function(){this.onload=this.onerror=null;b.coming.width=
this.width;b.coming.height=this.height;b._afterLoad()};a.onerror=function(){this.onload=this.onerror=null;b._error("image")};a.src=b.coming.href;!0!==a.complete&&b.showLoading()},_loadAjax:function(){var a=b.coming;b.showLoading();b.ajaxLoad=f.ajax(f.extend({},a.ajax,{url:a.href,error:function(a,e){b.coming&&"abort"!==e?b._error("ajax",a):b.hideLoading()},success:function(d,e){"success"===e&&(a.content=d,b._afterLoad())}}))},_loadIframe:function(){var a=b.coming,d=f(a.tpl.iframe.replace(/\{rnd\}/g,
(new Date).getTime())).attr("scrolling",s?"auto":a.iframe.scrolling).attr("src",a.href);f(a.wrap).bind("onReset",function(){try{f(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(a){}});a.iframe.preload&&(b.showLoading(),d.one("load",function(){f(this).data("ready",1);s||f(this).bind("load.fb",b.update);f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show();b._afterLoad()}));a.content=d.appendTo(a.inner);a.iframe.preload||b._afterLoad()},_preloadImages:function(){var a=
b.group,d=b.current,e=a.length,c=d.preload?Math.min(d.preload,e-1):0,f,g;for(g=1;g<=c;g+=1)f=a[(d.index+g)%e],"image"===f.type&&f.href&&((new Image).src=f.href)},_afterLoad:function(){var a=b.coming,d=b.current,e,c,k,g,h;b.hideLoading();if(a&&!1!==b.isActive)if(!1===b.trigger("afterLoad",a,d))a.wrap.stop(!0).trigger("onReset").remove(),b.coming=null;else{d&&(b.trigger("beforeChange",d),d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove());b.unbindEvents();
e=a.content;c=a.type;k=a.scrolling;f.extend(b,{wrap:a.wrap,skin:a.skin,outer:a.outer,inner:a.inner,current:a,previous:d});g=a.href;switch(c){case "inline":case "ajax":case "html":a.selector?e=f("<div>").html(e).find(a.selector):t(e)&&(e.data("fancybox-placeholder")||e.data("fancybox-placeholder",f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()),e=e.show().detach(),a.wrap.bind("onReset",function(){f(this).find(e).length&&e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder",
!1)}));break;case "image":e=a.tpl.image.replace("{href}",g);break;case "swf":e='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+g+'"></param>',h="",f.each(a.swf,function(a,b){e+='<param name="'+a+'" value="'+b+'"></param>';h+=" "+a+'="'+b+'"'}),e+='<embed src="'+g+'" type="application/x-shockwave-flash" width="100%" height="100%"'+h+"></embed></object>"}(!t(e)||!e.parent().is(a.inner))&&a.inner.append(e);b.trigger("beforeShow");
a.inner.css("overflow","yes"===k?"scroll":"no"===k?"hidden":k);b._setDimension();b.reposition();b.isOpen=!1;b.coming=null;b.bindEvents();if(b.isOpened){if(d.prevMethod)b.transitions[d.prevMethod]()}else f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove();b.transitions[b.isOpened?a.nextMethod:a.openMethod]();b._preloadImages()}},_setDimension:function(){var a=b.getViewport(),d=0,e=!1,c=!1,e=b.wrap,k=b.skin,g=b.inner,h=b.current,c=h.width,j=h.height,m=h.minWidth,u=h.minHeight,n=h.maxWidth,
v=h.maxHeight,s=h.scrolling,q=h.scrollOutside?h.scrollbarWidth:0,y=h.margin,p=l(y[1]+y[3]),r=l(y[0]+y[2]),z,A,t,D,B,G,C,E,w;e.add(k).add(g).width("auto").height("auto").removeClass("fancybox-tmp");y=l(k.outerWidth(!0)-k.width());z=l(k.outerHeight(!0)-k.height());A=p+y;t=r+z;D=F(c)?(a.w-A)*l(c)/100:c;B=F(j)?(a.h-t)*l(j)/100:j;if("iframe"===h.type){if(w=h.content,h.autoHeight&&1===w.data("ready"))try{w[0].contentWindow.document.location&&(g.width(D).height(9999),G=w.contents().find("body"),q&&G.css("overflow-x",
"hidden"),B=G.height())}catch(H){}}else if(h.autoWidth||h.autoHeight)g.addClass("fancybox-tmp"),h.autoWidth||g.width(D),h.autoHeight||g.height(B),h.autoWidth&&(D=g.width()),h.autoHeight&&(B=g.height()),g.removeClass("fancybox-tmp");c=l(D);j=l(B);E=D/B;m=l(F(m)?l(m,"w")-A:m);n=l(F(n)?l(n,"w")-A:n);u=l(F(u)?l(u,"h")-t:u);v=l(F(v)?l(v,"h")-t:v);G=n;C=v;h.fitToView&&(n=Math.min(a.w-A,n),v=Math.min(a.h-t,v));A=a.w-p;r=a.h-r;h.aspectRatio?(c>n&&(c=n,j=l(c/E)),j>v&&(j=v,c=l(j*E)),c<m&&(c=m,j=l(c/E)),j<u&&
(j=u,c=l(j*E))):(c=Math.max(m,Math.min(c,n)),h.autoHeight&&"iframe"!==h.type&&(g.width(c),j=g.height()),j=Math.max(u,Math.min(j,v)));if(h.fitToView)if(g.width(c).height(j),e.width(c+y),a=e.width(),p=e.height(),h.aspectRatio)for(;(a>A||p>r)&&(c>m&&j>u)&&!(19<d++);)j=Math.max(u,Math.min(v,j-10)),c=l(j*E),c<m&&(c=m,j=l(c/E)),c>n&&(c=n,j=l(c/E)),g.width(c).height(j),e.width(c+y),a=e.width(),p=e.height();else c=Math.max(m,Math.min(c,c-(a-A))),j=Math.max(u,Math.min(j,j-(p-r)));q&&("auto"===s&&j<B&&c+y+
q<A)&&(c+=q);g.width(c).height(j);e.width(c+y);a=e.width();p=e.height();e=(a>A||p>r)&&c>m&&j>u;c=h.aspectRatio?c<G&&j<C&&c<D&&j<B:(c<G||j<C)&&(c<D||j<B);f.extend(h,{dim:{width:x(a),height:x(p)},origWidth:D,origHeight:B,canShrink:e,canExpand:c,wPadding:y,hPadding:z,wrapSpace:p-k.outerHeight(!0),skinSpace:k.height()-j});!w&&(h.autoHeight&&j>u&&j<v&&!c)&&g.height("auto")},_getPosition:function(a){var d=b.current,e=b.getViewport(),c=d.margin,f=b.wrap.width()+c[1]+c[3],g=b.wrap.height()+c[0]+c[2],c={position:"absolute",
top:c[0],left:c[3]};d.autoCenter&&d.fixed&&!a&&g<=e.h&&f<=e.w?c.position="fixed":d.locked||(c.top+=e.y,c.left+=e.x);c.top=x(Math.max(c.top,c.top+(e.h-g)*d.topRatio));c.left=x(Math.max(c.left,c.left+(e.w-f)*d.leftRatio));return c},_afterZoomIn:function(){var a=b.current;a&&(b.isOpen=b.isOpened=!0,b.wrap.css("overflow","visible").addClass("fancybox-opened"),b.update(),(a.closeClick||a.nextClick&&1<b.group.length)&&b.inner.css("cursor","pointer").bind("click.fb",function(d){!f(d.target).is("a")&&!f(d.target).parent().is("a")&&
(d.preventDefault(),b[a.closeClick?"close":"next"]())}),a.closeBtn&&f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb",function(a){a.preventDefault();b.close()}),a.arrows&&1<b.group.length&&((a.loop||0<a.index)&&f(a.tpl.prev).appendTo(b.outer).bind("click.fb",b.prev),(a.loop||a.index<b.group.length-1)&&f(a.tpl.next).appendTo(b.outer).bind("click.fb",b.next)),b.trigger("afterShow"),!a.loop&&a.index===a.group.length-1?b.play(!1):b.opts.autoPlay&&!b.player.isActive&&(b.opts.autoPlay=!1,b.play()))},_afterZoomOut:function(a){a=
a||b.current;f(".fancybox-wrap").trigger("onReset").remove();f.extend(b,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null});b.trigger("afterClose",a)}});b.transitions={getOrigPosition:function(){var a=b.current,d=a.element,e=a.orig,c={},f=50,g=50,h=a.hPadding,j=a.wPadding,m=b.getViewport();!e&&(a.isDom&&d.is(":visible"))&&(e=d.find("img:first"),e.length||(e=d));t(e)?(c=e.offset(),e.is("img")&&(f=e.outerWidth(),g=e.outerHeight())):
(c.top=m.y+(m.h-g)*a.topRatio,c.left=m.x+(m.w-f)*a.leftRatio);if("fixed"===b.wrap.css("position")||a.locked)c.top-=m.y,c.left-=m.x;return c={top:x(c.top-h*a.topRatio),left:x(c.left-j*a.leftRatio),width:x(f+j),height:x(g+h)}},step:function(a,d){var e,c,f=d.prop;c=b.current;var g=c.wrapSpace,h=c.skinSpace;if("width"===f||"height"===f)e=d.end===d.start?1:(a-d.start)/(d.end-d.start),b.isClosing&&(e=1-e),c="width"===f?c.wPadding:c.hPadding,c=a-c,b.skin[f](l("width"===f?c:c-g*e)),b.inner[f](l("width"===
f?c:c-g*e-h*e))},zoomIn:function(){var a=b.current,d=a.pos,e=a.openEffect,c="elastic"===e,k=f.extend({opacity:1},d);delete k.position;c?(d=this.getOrigPosition(),a.openOpacity&&(d.opacity=0.1)):"fade"===e&&(d.opacity=0.1);b.wrap.css(d).animate(k,{duration:"none"===e?0:a.openSpeed,easing:a.openEasing,step:c?this.step:null,complete:b._afterZoomIn})},zoomOut:function(){var a=b.current,d=a.closeEffect,e="elastic"===d,c={opacity:0.1};e&&(c=this.getOrigPosition(),a.closeOpacity&&(c.opacity=0.1));b.wrap.animate(c,
{duration:"none"===d?0:a.closeSpeed,easing:a.closeEasing,step:e?this.step:null,complete:b._afterZoomOut})},changeIn:function(){var a=b.current,d=a.nextEffect,e=a.pos,c={opacity:1},f=b.direction,g;e.opacity=0.1;"elastic"===d&&(g="down"===f||"up"===f?"top":"left","down"===f||"right"===f?(e[g]=x(l(e[g])-200),c[g]="+=200px"):(e[g]=x(l(e[g])+200),c[g]="-=200px"));"none"===d?b._afterZoomIn():b.wrap.css(e).animate(c,{duration:a.nextSpeed,easing:a.nextEasing,complete:b._afterZoomIn})},changeOut:function(){var a=
b.previous,d=a.prevEffect,e={opacity:0.1},c=b.direction;"elastic"===d&&(e["down"===c||"up"===c?"top":"left"]=("up"===c||"left"===c?"-":"+")+"=200px");a.wrap.animate(e,{duration:"none"===d?0:a.prevSpeed,easing:a.prevEasing,complete:function(){f(this).trigger("onReset").remove()}})}};b.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!s,fixed:!0},overlay:null,fixed:!1,create:function(a){a=f.extend({},this.defaults,a);this.overlay&&this.close();this.overlay=f('<div class="fancybox-overlay"></div>').appendTo("body");
this.fixed=!1;a.fixed&&b.defaults.fixed&&(this.overlay.addClass("fancybox-overlay-fixed"),this.fixed=!0)},open:function(a){var d=this;a=f.extend({},this.defaults,a);this.overlay?this.overlay.unbind(".overlay").width("auto").height("auto"):this.create(a);this.fixed||(q.bind("resize.overlay",f.proxy(this.update,this)),this.update());a.closeClick&&this.overlay.bind("click.overlay",function(a){f(a.target).hasClass("fancybox-overlay")&&(b.isActive?b.close():d.close())});this.overlay.css(a.css).show()},
close:function(){f(".fancybox-overlay").remove();q.unbind("resize.overlay");this.overlay=null;!1!==this.margin&&(f("body").css("margin-right",this.margin),this.margin=!1);this.el&&this.el.removeClass("fancybox-lock")},update:function(){var a="100%",b;this.overlay.width(a).height("100%");H?(b=Math.max(z.documentElement.offsetWidth,z.body.offsetWidth),n.width()>b&&(a=n.width())):n.width()>q.width()&&(a=n.width());this.overlay.width(a).height(n.height())},onReady:function(a,b){f(".fancybox-overlay").stop(!0,
!0);this.overlay||(this.margin=n.height()>q.height()||"scroll"===f("body").css("overflow-y")?f("body").css("margin-right"):!1,this.el=z.all&&!z.querySelector?f("html"):f("body"),this.create(a));a.locked&&this.fixed&&(b.locked=this.overlay.append(b.wrap),b.fixed=!1);!0===a.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(a,b){b.locked&&(this.el.addClass("fancybox-lock"),!1!==this.margin&&f("body").css("margin-right",l(this.margin)+b.scrollbarWidth));this.open(a)},onUpdate:function(){this.fixed||
this.update()},afterClose:function(a){this.overlay&&!b.isActive&&this.overlay.fadeOut(a.speedOut,f.proxy(this.close,this))}};b.helpers.title={defaults:{type:"float",position:"bottom"},beforeShow:function(a){var d=b.current,e=d.title,c=a.type;f.isFunction(e)&&(e=e.call(d.element,d));if(p(e)&&""!==f.trim(e)){d=f('<div class="fancybox-title fancybox-title-'+c+'-wrap">'+e+"</div>");switch(c){case "inside":c=b.skin;break;case "outside":c=b.wrap;break;case "over":c=b.inner;break;default:c=b.skin,d.appendTo("body"),
H&&d.width(d.width()),d.wrapInner('<span class="child"></span>'),b.current.margin[2]+=Math.abs(l(d.css("margin-bottom")))}d["top"===a.position?"prependTo":"appendTo"](c)}}};f.fn.fancybox=function(a){var d,e=f(this),c=this.selector||"",k=function(g){var h=f(this).blur(),j=d,k,l;!g.ctrlKey&&(!g.altKey&&!g.shiftKey&&!g.metaKey)&&!h.is(".fancybox-wrap")&&(k=a.groupAttr||"data-fancybox-group",l=h.attr(k),l||(k="rel",l=h.get(0)[k]),l&&(""!==l&&"nofollow"!==l)&&(h=c.length?f(c):e,h=h.filter("["+k+'="'+l+
'"]'),j=h.index(this)),a.index=j,!1!==b.open(h,a)&&g.preventDefault())};a=a||{};d=a.index||0;!c||!1===a.live?e.unbind("click.fb-start").bind("click.fb-start",k):n.undelegate(c,"click.fb-start").delegate(c+":not('.fancybox-item, .fancybox-nav')","click.fb-start",k);this.filter("[data-fancybox-start=1]").trigger("click");return this};n.ready(function(){f.scrollbarWidth===r&&(f.scrollbarWidth=function(){var a=f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),b=a.children(),
b=b.innerWidth()-b.height(99).innerWidth();a.remove();return b});if(f.support.fixedPosition===r){var a=f.support,d=f('<div style="position:fixed;top:20px;"></div>').appendTo("body"),e=20===d[0].offsetTop||15===d[0].offsetTop;d.remove();a.fixedPosition=e}f.extend(b.defaults,{scrollbarWidth:f.scrollbarWidth(),fixed:f.support.fixedPosition,parent:f("body")})})})(window,document,jQuery);;

/********************************
/site/resources/ui.totop/jquery.ui.totop.js
********************************/
/*
|--------------------------------------------------------------------------
| UItoTop jQuery Plugin 1.2 by Matt Varone
| http://www.mattvarone.com/web-design/uitotop-jquery-plugin/
|--------------------------------------------------------------------------
*/
(function($){
	$.fn.UItoTop = function(options) {

 		var defaults = {
    			text: 'To Top',
    			min: 200,
    			inDelay:600,
    			outDelay:400,
      			containerID: 'toTop',
    			containerHoverID: 'toTopHover',
    			scrollSpeed: 1200,
    			easingType: 'linear'
 		    },
            settings = $.extend(defaults, options),
            containerIDhash = '#' + settings.containerID,
            containerHoverIDHash = '#'+settings.containerHoverID;
		
		$('body').append('<a href="#" id="'+settings.containerID+'">'+settings.text+'</a>');
		$(containerIDhash).hide().on('click.UItoTop',function(){
			$('html, body').animate({scrollTop:0}, settings.scrollSpeed, settings.easingType);
			$('#'+settings.containerHoverID, this).stop().animate({'opacity': 0 }, settings.inDelay, settings.easingType);
			return false;
		})
		.prepend('<span id="'+settings.containerHoverID+'"></span>')
		.hover(function() {
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 1
				}, 600, 'linear');
			}, function() { 
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 0
				}, 700, 'linear');
			});
					
		$(window).scroll(function() {
			var sd = $(window).scrollTop();
			if(typeof document.body.style.maxHeight === "undefined") {
				$(containerIDhash).css({
					'position': 'absolute',
					'top': sd + $(window).height() - 50
				});
			}
			if ( sd > settings.min ) 
				$(containerIDhash).fadeIn(settings.inDelay);
			else 
				$(containerIDhash).fadeOut(settings.Outdelay);
		});
};
})(jQuery);;

/********************************
/site/controller/client.js
********************************/
var URL_SOAP_CUSTOMER = "/site/controller/CustomerService.asmx";

window.ecomUserSettings = {
	onAddToCart: websiteAddToCart,
    cartTemplate: "/site/view/cartTemplate.html"
};

var timer;

$(document).ready(function() {	
 
 	$('#menu').mmenu({
		counters	: true,
		navbar 		: {
		  title		: 'Menu'
		},
		dragOpen: {
		  open: $( document ).width()<975,
		  pageNode: $('html')
		},
		extensions: ["effect-slide-menu", "effect-slide-listitems"]
	});
	
	$('#menu').css('display', '');
	  	
 	$().UItoTop({ easingType: 'easeOutQuart' });

    $('body').click(function(evt){
        if(!$(evt.target).is('#search, .submit, .icon-search')) {
            $('.search-bar-cont .options').show();
            $('.search-bar').removeClass('visible');
        }
        
        if(!$(evt.target).is('.divmenu > ul > li a span, .divmenu > ul > li a, .divcategoriesmenu')) {
            $('.divmenu > ul > li').removeClass('clicked');
        }
    });
    
    $('.divmenu > ul > li').click(function() {
        if($(this).hasClass('clicked')) {
            $('.divmenu > ul > li').removeClass('clicked');
        } else {
            $('.divmenu > ul > li').removeClass('clicked');
            $(this).addClass('clicked');
        }
    });
    
    sticky();
    categoriesCont();
	

    /*
    $('.menu-category').each(function() {
        var a = $(this).children().first();
        var li = '<li><a href="' + a.attr('data-url') + '">' + a.attr('data-all') + '</a></li>';
        $(this).find('ul').append(li);
    });
    */

    //EcomUI.LoadCurrencies();
    //LoadCurrencies();
    
    var pl = $('.divselectdiv a[data-value="' + pricelist + '-' + board_culture_key + '"]');
    pl.addClass('current');
    $('#a-select').text(pl.attr('data-text'));
	$('#a-select1').text(pl.attr('data-text'));
    
    $('.divselect').click(function() {
        if($(this).hasClass('show')) {
            $(this).removeClass('show');
            $('.divselectdiv').removeClass('show');
        } else {
            $(this).addClass('show');
            $('.divselectdiv').addClass('show');
        }
    });
    
    $('.divselectdiv a').click(function() {
        var ar = $(this).attr('data-value').split('-');
      
        setCookie('pricelist', ar[0], 1);

       if (pricelist != ar[0] && Order.data.items.length > 0) {
			for (i = 0; i < Order.data.items.length; i++) {
				if (ar[0] == "1") {
					Order.data.items[i]["price"] = Order.data.items[i]["priceUSD"];
				}
				else {
					Order.data.items[i]["price"] = Order.data.items[i]["priceCAD"];
				}
			}
			Order.SaveCartContents();
		}

        if(board_culture_key == ar[1]) {
        	setTimeout("location.reload()", 750);
        } else {
        	setTimeout("reload()", 750);
        }
    });

    // Mobile
    var pl = $('.divselectmobile a[data-value="' + pricelist + '-' + board_culture_key + '"]');
    pl.addClass('current');

    $('.divselectmobile a').click(function() {
        var ar = $(this).attr('data-value').split('-');
        console.log(ar);
        setCookie('pricelist', ar[0], 1);

        if (pricelist != ar[0] && Order.data.items.length > 0) {
        	//Order.data.items.length = 0;
			for (i = 0; i < Order.data.items.length; i++) {
				if (ar[0] == "USD")
					Order.data.items[i]["price"] = Order.data.items[i]["priceUSD"];
				else
					Order.data.items[i]["price"] = Order.data.items[i]["priceCAD"];
			}
			Order.SaveCartContents();
			//alert(SBPhrases["website_EMPTY_CART"]);
		}

        if(board_culture_key == ar[1]) {
            location.reload();
        } else {
        	location = mirrorUrls[0][1].replace("default.fr-ca.aspx","fr") + location.search;
        }
    });
    
    $('.viewmore').html($('#viewmore').val());
    $('.viewmore').each(function() {
    	$(this).clone().appendTo($(this).prev()).before(' ');
    	$(this).remove();
    });
    
    $('.product-tab').css('width', 100 / $('.product-tab').length + '%').css('display', 'block');

    if (AdeoApp.Newsletter)
 	{ 		
		var newsletterAppId = AdeoApp.Newsletter.prototype.ID;
		AdeoPlatform.Factory.GetApp(newsletterAppId).FrontLoad(newsletterAppId, newsletterAppId, $(".divnewsletter")[0], 100, 100);	
	}
	/*
    loadjscssfile('/cms/resources/fancyBox/source/jquery.fancybox.css', 'css');
	loadjscssfile('/cms/view/controls/PopupSqueeze/PopupSqueeze.css', 'css');
	if (!$.fancybox)
	{
		loadjscssfile('/cms/resources/fancyBox/lib/jquery.mousewheel-3.0.6.pack.js', 'js');
		loadjscssfile('/cms/resources/fancyBox/source/jquery.fancybox.js', 'js');
	}
    */
    //$('.divnewsletter').append('<div class="icon icon-send-button" onclick="<%= Abludo.CMS.SBCommon.BuildUrl((Abludo.CMS.MyStandard)Page, ((Abludo.CMS.MyStandard)Page).Common.Board.Settings.NumericValue("DefaultRewriteKey"), ((Abludo.CMS.MyStandard)Page).Common.Board.Settings.NumericValue("NewsletterPageKey")) %>"></div>');

    $('.search-bar form').submit(function( event ) {
      /*if($('#search').val().length < 3) {
          alert( SBPhrases['SEARCH_MIN_CHAR'] );
          event.preventDefault();
          return false;
      }*/
    });
    
    if(window.currencyCode == "CAD") {
    	$('.phone-cad').show();
    } else {
    	$('.phone-usd').show();
    }
	
	$('.ca-fr').hide();
	$('.ca-en').hide();
	$('.us-en').hide();
	
	if(window.currencyCode == "CAD") {
		if (board_culture_key == 1) {
			$('.ca-en').show();
			
		} else {
			$('.ca-fr').show();
			
		}
    } else {	
    	$('.us-en').show();
		
    }

    // newsletter form
    if($('.divforminterests').length > 0) {
    	timer = setInterval(function() {
    		if($('.ctct-form-custom').length > 0) {
    			clearInterval(timer);
    			customNewsletter();
    		}
    	}, 250);
    }

    var ifmUpload = document.getElementById("ifmUpload");
	if (ifmUpload)
	{
		if (board_culture == "fr-CA")
			ifmUpload.src = "/cms/view/controls/ClientAjaxUpload.aspx?guid=" + campaignGuid + "&folder=UPLOAD&lang=fr";	
		else
			ifmUpload.src = "/cms/view/controls/ClientAjaxUpload.aspx?guid=" + campaignGuid + "&folder=UPLOAD";	
	}
});

function reload() {
	 location = mirrorUrls[0][1].replace("default.fr-ca.aspx","fr") + location.search;
}
function regexE(sender){
	var regName=/^[a-zA-Z ]+$/;
	var regEmail=/\S+@\S+\.\S+/;
	var name=document.getElementById("quotename").value;
	var email=document.getElementById("quoteemail").value;
	console.log(name);
		console.log(email);
	if(regName.test(name) && regEmail.test(email)){
		console.log("work");
	doSaveCampaign(sender);
	}
	else{
		console.log("allo");
		console.log(name);
		console.log(email);
		console.log("didnt work at all");
		alert("Email Invalid");
	}
}
function addEmailAddress(){
	if(document.getElementById("contactemail1").classList.contains("shownAddEmail")){
	console.log("yes");
	}
	else{
		document.getElementById("contactemail1").classList.add("shownAddEmail");
		return;
	}
	if(document.getElementById("contactemail2").classList.contains("shownAddEmail")){
	console.log("yes");
	}
	else{
		document.getElementById("contactemail2").classList.add("shownAddEmail");
		return;
	}
	if(document.getElementById("contactemail3").classList.contains("shownAddEmail")){
	console.log("yes");
	}
	else{
		document.getElementById("contactemail3").classList.add("shownAddEmail");
		return;
	}
	if(document.getElementById("contactemail4").classList.contains("shownAddEmail")){
	console.log("yes");
	}
	else{
		document.getElementById("contactemail4").classList.add("shownAddEmail");
		return;
	}
	if(document.getElementById("contactemail5").classList.contains("shownAddEmail")){
	console.log("yes");
	alert("Maximum Email");
	}
	else{
		document.getElementById("contactemail5").classList.add("shownAddEmail");
		return;
	}
	
}
function sendQuote1() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail1").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail1').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Incorrect field values");
	}
	
}
function sendQuote2() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail2").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail2').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Incorrect field values");
	}
}
function sendQuote3() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail3").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail3').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Incorrect field values");
	}
}
function sendQuote4() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail4").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail4').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Incorrect field values");
	}
}
function sendQuote5() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail5").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail5').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Incorrect field values");
	}
}

//function regexCon(sender){
//	var regName=/^[a-zA-Z ]+$/;
//	var regEmail=/\S+@\S+\.\S+/;
//	var name=document.getElementById("contactname").value;
//	var email=document.getElementById("contactemail").value;
//	console.log(name);
//		console.log(email);
//	if(regName.test(name) && regEmail.test(email)){
//		console.log("work");
//	doSaveCampaign(sender);
//	}
//	else{
//		console.log("allo");
//		console.log(name);
//		console.log(email);
//		console.log("didnt work at all");
//		alert("Email Invalid");
//	}
//}

function validateRecaptchaRegexCon(sender) {
 	var token = document.querySelector('input[name="cf-turnstile-response"]')?.value;
 
 	if (!token) {
 		console.log("Complétez le recaptcha");
 		return false;
 	}
 
 	regexCon(sender, token);
 
 	return false;
 }
 
 function regexCon(sender, token = "") {
	debugger;
	var regName = /^[a-zA-Z ]+$/;
	var regEmail = /\S+@\S+\.\S+/;

	var firstName = $('#gvw-firstname').val()
	var lastName = $('#gvw-lastname').val()
	var name = '';
	if (!(firstName && lastName)) {
		//name = document.getElementById("contactname").value;
		name = $('#contactname').val();

		if (!name) {
			name = $('#mm-companyname').val();
		}
	}
	else {
		name = firstName + ' ' + lastName;
	}
	var email = $('#gvw-email').val();
	if (!email) {
		//email = document.getElementById("contactemail").value;
		email = $('#contactemail').val();
		if (!email) {
			email = $('#mm-email').val();
		}
	}
	console.log(name);
	console.log(email);
	if (regName.test(name) && regEmail.test(email)) {
		console.log("work");
		doSaveCampaign(sender, token);
	}
	else {
		console.log("allo");
		console.log(name);
		console.log(email);
		console.log("didnt work at all");
		alert("Email Invalid");
	}
}


function customNewsletter() {
	$('input[name="custom_field_string_interests"]').parents('.ctct-form-field').hide().after($('.divforminterests').clone());
	$('input[name="email_address"]').val(document.location.search.replace('?e=',''));
	$('.ctct-form-text').after('<img src="/site/view/images/laptop.png" />');

 	$('.divforminterests input[name="interests"]').change(function() {
    	var interests = [];
    	$('.divforminterests input[name="interests"]:checked').each(function() {
    		interests.push($(this).val());
    	});
    	$('input[name="custom_field_string_interests"]').val(interests.join(', '));
    });
}

$(window).scroll(function() {
    sticky();
});

$(window).resize(function() {
    sticky();
    categoriesCont();
});

function sticky() {
    if($(window).width() <= 1260) {
        $('.divmenucontainer').addClass('sticky');
		$('#hamburger').addClass('stickyHam');
    } else {
        if($(window).scrollTop() > 68) {
            $('.divmenucontainer').addClass('sticky');
			$('#hamburger').addClass('stickyHam');
        } else {
            $('.divmenucontainer').removeClass('sticky');
			$('#hamburger').removeClass('stickyHam');
        }
    }
}

function stickySearch() {
    $('.search-bar-cont .options').hide();
    $('.search-bar').addClass('visible');
}

function categoriesCont() {
    if($(window).width() > 975) {
        var h = $('.divhomecategories1').width();
        $('.divhomecategoriescontainer').css('height', h);
    }
    
    if($(window).width() > 1200) {
        var h = $('.divhomecategories0').width();
        $('.divhomecategoriescontainer').css('height', h);
    }
    
    if($(window).width() <= 975) {
        $('.divhomecategoriescontainer').css('height', 'auto');
    }
}


/*function changeCurrency(currency)
{	
	if (Order.data.items.length)
	{
		alert(SBPhrases["website_EMPTY_CART"]);
		Order.data.items.length = 0;
		Order.SaveCartContents();
	}
	showPrice();
}*/

function OnCartLoaded() {
    console.log('cartLoaded');
    LoadCurrencies();
    
    // cart footer
    if(Order.data.items.length > 0) $('.divcartfooter').show();
}

function LoadCurrencies()
{
	var oldCurrency = Order.data.currency;
 	if (window.orderUserSettings)
 	{
 	 	if (window.orderUserSettings.currency == null)
	 		Order.data.currency = window.currencyCode;
	 	else
			Order.data.currency = window.orderUserSettings.currency;
	}
	else
	{
		Order.data.currency = window.currencyCode;			
	}
    Order.SaveCartContents();
    console.log('TEST', window.orderUserSettings, window.currencyCode, oldCurrency);
	
}

function showPrice()
{
    console.log('price');    
}


$(window).load(function() {

});


var addToCart = websiteAddToCart;
function websiteAddToCart(type)
{
	debugger;
	if(type != '' && $('#quotesent').val() == 1) {
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);		
		SOAPClient.invoke(URL_SOAP_CART, "GetCartUrl", pl, true, function(data) {
			if (window.ecomUserSettings && window.ecomUserSettings.onGoToHttps)
				httpsUrl = "https://" + window.location.host;
	        type = '?t=' + type;
			document.location = httpsUrl + data + type;
		});
	} else {
		var popup = '<div class="divpopupquote"><span class="popupheader">' + SBPhrases['ITEM_ADDED_QUOTE'] + '</span><div>';
	    var item = {
	        productKey: $('#hidKey').val(),
	        sku: $('.product-sku').html() + $('#product-sku-plus-kit').html(),
	        description: {'en-CA': $('#hidDescriptionEn').html(), 'fr-CA': $('#hidDescriptionFr').html()},
	        title: {'en-CA': $('#hidTitleEn').html(), 'fr-CA': $('#hidTitleFr').html()},
	        subtitle: {'en-CA': $('#hidSubTitleEn').html(), 'fr-CA': $('#hidSubTitleFr').html()},
	        options: {'en-CA': $('#hidOptionsEn').html(), 'fr-CA': $('#hidOptionsFr').html()},
	        quantity: 1,
	        price: $('#hidPrice').val(),
	        priceUSD: $('#hidPriceUSD').val(),
	        priceCAD: $('#hidPriceCAD').val(),
	        'kitsize': 1,
	        sortOrder: (Order.data.items.length + 1),
	        'photo': $('#hidImage').val()
	    };
	    
	    popup += '<div><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	    if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	    popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
	    
		Order.data.items[Order.data.items.length] = item;

		//Frame
		if ($('#hidFrameKey').val()) {
			var item = {
				productKey: $('#hidFrameKey').val(),
				sku: $('#hidFrameSKU').val(),
				description: { 'en-CA': '', 'fr-CA': '' },
				title: { 'en-CA': $('#hidFrameTitleEn').val(), 'fr-CA': $('#hidFrameTitleFr').val() },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				options: { 'en-CA': '', 'fr-CA': '' },
				quantity: 1,
				price: $('#hidFramePrice').val(),
				priceUSD: $('#hidFramePriceUSD').val(),
				priceCAD: $('#hidFramePriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidFrameImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

		//Backsplash
		if ($('#hidBacksplashKey').val()) {
			var item = {
				productKey: $('#hidBacksplashKey').val(),
				sku: $('#hidBacksplashSKU').val(),
				description: { 'en-CA': '', 'fr-CA': '' },
				title: { 'en-CA': $('#hidBacksplashTitleEn').val(), 'fr-CA': $('#hidBacksplashTitleFr').val() },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				options: { 'en-CA': '', 'fr-CA': '' },
				quantity: 1,
				price: $('#hidBacksplashPrice').val(),
				priceUSD: $('#hidBacksplashPriceUSD').val(),
				priceCAD: $('#hidBacksplashPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidBacksplashImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

		//Drain
		if ($('#hidDrainKey').val()) {
			var item = {
				productKey: $('#hidDrainKey').val(),
				sku: $('#hidDrainSKU').val(),
				description: { 'en-CA': '', 'fr-CA': '' },
				title: { 'en-CA': $('#hidDrainTitleEn').val(), 'fr-CA': $('#hidDrainTitleFr').val() },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				options: { 'en-CA': '', 'fr-CA': '' },
				quantity: 1,
				price: $('#hidDrainPrice').val(),
				priceUSD: $('#hidDrainPriceUSD').val(),
				priceCAD: $('#hidDrainPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidDrainImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}


		//Pipe
		if ($('#hidPipeKey').val()) {
			var item = {
				productKey: $('#hidPipeKey').val(),
				sku: $('#hidPipeSKU').val(),
				description: { 'en-CA': '', 'fr-CA': '' },
				title: { 'en-CA': $('#hidPipeTitleEn').val(), 'fr-CA': $('#hidPipeTitleFr').val() },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				options: { 'en-CA': '', 'fr-CA': '' },
				quantity: 1,
				price: $('#hidPipePrice').val(),
				priceUSD: $('#hidPipePriceUSD').val(),
				priceCAD: $('#hidPipePriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidPipeImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

	    // Accessory
	    if ($('#hidAccessoryKey').val()) {
		    var item = {
		        productKey: $('#hidAccessoryKey').val(),
		        sku: $('#hidAccessorySku').val(),
		        description: {'en-CA': $('#hidAccessoryEn').val(), 'fr-CA': $('#hidAccessoryFr').val()},
	            title: {'en-CA': $('#hidAccessoryTitleEn').html(), 'fr-CA': $('#hidAccessoryTitleFr').html()},
	            subtitle: {'en-CA': $('#hidAccessorySubTitleEn').html(), 'fr-CA': $('#hidAccessorySubTitleFr').html()},
	            options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
		        quantity: 1,
		        price: $('#hidAccessoryPrice').val(),
		        priceUSD: $('#hidAccessoryPriceUSD').val(),
	        	priceCAD: $('#hidAccessoryPriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidAccessoryImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
		    
		    Order.data.items[Order.data.items.length] = item;
	    }
		
		// Install Kit
	    if ($('#hidInstallKey').val()) {
		    var item = {
		        productKey: $('#hidInstallKey').val(),
		        sku: $('#hidInstallSku').val(),
		        description: {'en-CA': "", 'fr-CA': ""},
	            title: {'en-CA': "", 'fr-CA': ""},
	            subtitle: {'en-CA': '', 'fr-CA': ''},
	            //options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: {'en-CA': "", 'fr-CA': ""},
		        quantity: 1,
		        price: 0,
		        priceUSD: 0,
	        	priceCAD: 0,
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidInstallImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//
		    
		    Order.data.items[Order.data.items.length] = item;
	    }
		
		// Accent Panel
	    if ($('#hidAccentKey').val()) {
		    var item = {
		        productKey: $('#hidAccentKey').val(),
		        sku: $('#hidAccentSku').val(),
		        description: {'en-CA': "", 'fr-CA': ""},
	            title: {'en-CA': "", 'fr-CA': ""},
	            subtitle: {'en-CA': '', 'fr-CA': ''},
	            //options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: {'en-CA': "", 'fr-CA': ""},
		        quantity: 1,
		        price: $('#hidAccentPrice').val(),
		        priceUSD: $('#hidAccentPriceUSD').val(),
	        	priceCAD: $('#hidAccentPriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidAccentImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//
		    
		    Order.data.items[Order.data.items.length] = item;
	    }
		
		// FIBO Grip
	    if ($('#hidGripKey').val()) {
		    var item = {
		        productKey: $('#hidGripKey').val(),
		        sku: $('#hidGripSku').val(),
		        description: {'en-CA': "", 'fr-CA': ""},
	            title: {'en-CA': "", 'fr-CA': ""},
	            subtitle: {'en-CA': '', 'fr-CA': ''},
	            //options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: {'en-CA': "", 'fr-CA': ""},
		        quantity: 1,
		        price: $('#hidGripPrice').val(),
		        priceUSD: $('#hidGripPriceUSD').val(),
	        	priceCAD: $('#hidGripPriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidGripImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//
		    
		    Order.data.items[Order.data.items.length] = item;
	    }
		
		// FIBO Grip
	    if ($('#hidSpacerKey').val()) {
		    var item = {
		        productKey: $('#hidSpacerKey').val(),
		        sku: $('#hidSpacerSku').val(),
		        description: {'en-CA': "", 'fr-CA': ""},
	            title: {'en-CA': "", 'fr-CA': ""},
	            subtitle: {'en-CA': '', 'fr-CA': ''},
	            //options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: {'en-CA': "", 'fr-CA': ""},
		        quantity: 1,
		        price: $('#hidSpacerPrice').val(),
		        priceUSD: $('#hidSpacerPriceUSD').val(),
	        	priceCAD: $('#hidSpacerPriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidSpacerImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//
		    
		    Order.data.items[Order.data.items.length] = item;
	    }

		// Hardware kit
	    if ($('#hidHardwareKitKey').val()) {
		    var item = {
		        productKey: $('#hidHardwareKitKey').val(),
		        sku: $('#hidHardwareKitSku').val(),
		        description: {'en-CA': "", 'fr-CA': ""},
	            title: {'en-CA': $('#hidHardwareKitTitleEn').val(), 'fr-CA': $('#hidHardwareKitTitleFr').val()},
	            subtitle: {'en-CA': '', 'fr-CA': ''},
	            //options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: {'en-CA': "", 'fr-CA': ""},
		        quantity: 1,
		        price: $('#hidHardwareKitPrice').val(),
		        priceUSD: $('#hidHardwareKitPriceUSD').val(),
	        	priceCAD: $('#hidHardwareKitPriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidHardwareKitImage').val()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//
		    
		    Order.data.items[Order.data.items.length] = item;
	    }

	    // Option
	    $('.divaccessorychosen .itemAccessory').each(function() {
	    	 var dt = $(this);
	    	 var item = {
		        productKey: $(this).find('.accessoryKey').html(),
		        sku: $(this).find('.accessorySku').html(),
		        description: {'en-CA': $(this).find('.accessoryEn').html(), 'fr-CA': $(this).find('.accessoryFr').html()},
	            title: {'en-CA': $(this).find('.accessoryTitleEn').html(), 'fr-CA': $(this).find('.accessoryTitleFr').html()},
	            subtitle: {'en-CA': $(this).find('.accessorySubTitleEn').html(), 'fr-CA': $(this).find('.accessorySubTitleFr').html()},
	            options: {'en-CA': $(this).find('.accessoryOptionEn').html(), 'fr-CA': $(this).find('.accessoryOptionFr').html()},
		        quantity: $(this).find('.accessoryQuantity').html(),
		        price: $(this).find('.accessoryPrice').html(),
		        priceUSD: $(this).find('.accessoryPriceUSD').html(),
	        	priceCAD: $(this).find('.accessoryPriceCAD').html(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $(this).find('.accessoryImage').html()
		    };
	        
	        popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
		    
		    Order.data.items[Order.data.items.length] = item;
	    });

	    // Base
	    if ($('#hidBaseKey').val()) {
	 		var item = {
		        productKey: $('#hidBaseKey').val(),
		        sku: $('#hidBaseSku').val(),
		        description: {'en-CA': $('#hidBaseDescriptionEn').html(), 'fr-CA': $('#hidBaseDescriptionFr').html()},
	            title: {'en-CA': $('#hidBaseTitleEn').html(), 'fr-CA': $('#hidBaseTitleFr').html()},
	            subtitle: {'en-CA': $('#hidBaseSubTitleEn').html(), 'fr-CA': $('#hidBaseSubTitleFr').html()},
	            options: {'en-CA': $('#hidBaseOptionsEn').html(), 'fr-CA': $('#hidBaseOptionsFr').html()},
		        quantity: 1,
		        price: $('#hidBasePrice').val(),
		        priceUSD: $('#hidBasePriceUSD').val(),
	        	priceCAD: $('#hidBasePriceCAD').val(),
		        'kitsize': 1,
		        sortOrder: (Order.data.items.length + 1),
		        'photo': $('#hidBaseImage').val()
		    };
	        
		    popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
	        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
	        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
		    
		    Order.data.items[Order.data.items.length] = item;
		}

		// Second Base for Fibo wall/Base
		if ($('#hidSecondBaseKey').val()) {
			var item = {
				productKey: $('#hidSecondBaseKey').val(),
				sku: $('#hidSecondBaseSku').val(),
				description: { 'en-CA': $('#hidSecondBaseDescriptionEn').html(), 'fr-CA': $('#hidSecondBaseDescriptionFr').html() },
				title: { 'en-CA': $('#hidSecondBaseTitleEn').html(), 'fr-CA': $('#hidSecondBaseTitleFr').html() },
				subtitle: { 'en-CA': $('#hidSecondBaseSubTitleEn').html(), 'fr-CA': $('#hidSecondBaseSubTitleFr').html() },
				options: { 'en-CA': $('#hidSecondBaseOptionsEn').html(), 'fr-CA': $('#hidSecondBaseOptionsFr').html() },
				quantity: 1,
				price: $('#hidSecondBasePrice').val(),
				priceUSD: $('#hidSecondBasePriceUSD').val(),
				priceCAD: $('#hidSecondBasePriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidSecondBaseImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

		// Base Accessories
		if ($('#hidBaseAccessoryKey').val()) {
			var item = {
				productKey: $('#hidBaseAccessoryKey').val(),
				sku: $('#hidBaseAccessorySku').val(),
				description: { 'en-CA': $('#hidBaseAccessoryEn').html(), 'fr-CA': $('#hidBaseAccessoryFr').html() },
				title: { 'en-CA': $('#hidBaseAccessoryTitleEn').html(), 'fr-CA': $('#hidBaseAccessoryTitleFr').html() },
				subtitle: { 'en-CA': $('#hidBaseAccessorySubTitleEn').html(), 'fr-CA': $('#hidBaseAccessorySubTitleFr').html() },
				options: { 'en-CA': $('#hidBaseAccessoryOptionsEn').html(), 'fr-CA': $('#hidBaseAccessoryOptionsFr').html() },
				quantity: 1,
				price: $('#hidBaseAccessoryPrice').val(),
				priceUSD: $('#hidBaseAccessoryPriceUSD').val(),
				priceCAD: $('#hidBaseAccessoryPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidBaseAccessoryImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

		//bathtub on shower door
		if ($('#hidBathtubSKU').val() && $('.divBathtubAfter') ){
			var bathtubDescription = '';
			var selectedBathTub = $('.stepBathtub0 input[name="rdoBathtub"]:checked');
			if (selectedBathTub) {
				//bathtubDescription += selectedBathTub.attr('data-title') + ', ';
				bathtubDescription += 'length ' + selectedBathTub.attr('data-length') + '", ';
				bathtubDescription += 'width ' + selectedBathTub.attr('data-width') + '", ';
				bathtubDescription += 'height ' + selectedBathTub.attr('data-height') + '", ';
				bathtubDescription += 'capacity ' + selectedBathTub.attr('data-length') + 'U.S. gal, ';
			}

			var bathtubDirection = $('input[name="rdoSideBathtub"]:checked').val();
			if (bathtubDirection && bathtubDirection === 'L') {
				bathtubDescription += 'Left';
			}
			else {
				bathtubDescription += 'Right';
			}

			var item = {
				productKey : $('.stepBathtub0 input[name="rdoBathtub"]:checked').val(),
				sku : $('#hidBathtubSKU').val(),
				description: { 'en-CA': bathtubDescription, 'fr-CA': bathtubDescription},
				title: { 'en-CA': $('.stepBathtub0 input[name="rdoBathtub"]').attr('data-title'), 'fr-CA': $('.stepBathtub0 input[name="rdoBathtub"]').attr('data-title')},
				subtitle: { 'en-CA': bathtubDescription, 'fr-CA': bathtubDescription},
				options: { 'en-CA': '', 'fr-CA': '' },
				quantity: 1,
				price: price[$('#hidBathtubSKU').val()],
				priceUSD: price[$('#hidBathtubSKU').val()],
				priceCAD: price[$('#hidBathtubSKU').val()],
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('.stepBathtub0 input[name="rdoBathtub"]:checked').attr('data-photo')
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;

		}

		$('.stepBathtub3 .divdraintype').each(function () {
			//debugger;
			var dt = $(this);
			if (dt.find('.drpDrain').val()) {
				var s = dt.find('.drpDrain');
				var o = s.find('option:selected');
				var item = {
					productKey: s.val(),
					sku: o.attr('data-sku'),
					description: { 'en-CA': '', 'fr-CA': '' },
					title: { 'en-CA': o.attr('data-title'), 'fr-CA': o.attr('data-title') },
					subtitle: { 'en-CA': '', 'fr-CA': '' },
					options: { 'en-CA': '', 'fr-CA': '' },
					quantity: 1,
					price: o.attr('data-price' + currencyCode.toLowerCase()).replace(',', '.'),
					priceUSD: o.attr('data-priceusd').replace(',', '.'),
					priceCAD: o.attr('data-pricecad').replace(',', '.'),
					'kitsize': 1,
					sortOrder: (Order.data.items.length + 1),
					'photo': ''
				};

				popup += '<div class="added"><span>' + item['title'][board_culture] + '</span>';
				if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
				popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

				Order.data.items[Order.data.items.length] = item;
			}
		});

		if ($('.stepBathtub4 input[name="rdoDrainCover"]').length) {
			//debugger;
			if ($('.stepBathtub4 input[name="rdoDrainCover"]:checked').val()) {
				var i = $('input[name="rdoDrainCover"]:checked');
				//console.log(i);
				var item = {
					productKey: i.attr('data-key'),
					sku: i.attr('data-sku'),
					description: { 'en-CA': '', 'fr-CA': '' },
					title: { 'en-CA': i.attr('data-title'), 'fr-CA': i.attr('data-title') },
					subtitle: { 'en-CA': '', 'fr-CA': '' },
					options: { 'en-CA': '', 'fr-CA': '' },
					quantity: 1,
					price: i.attr('data-price' + currencyCode.toLowerCase()).replace(',', '.'),
					priceUSD: i.attr('data-priceusd').replace(',', '.'),
					priceCAD: i.attr('data-pricecad').replace(',', '.'),
					'kitsize': 1,
					sortOrder: (Order.data.items.length + 1),
					'photo': i.attr('data-photo')
				};

				popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
				if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
				popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

				Order.data.items[Order.data.items.length] = item;
			}
		}
	    
	    // Bathtubs drains
	    
		$('.step3 .divdraintype').each(function () {
			//debugger;
	    	var dt = $(this);
	    	if(dt.find('.drpDrain').val() != '') {
	    		var s = dt.find('.drpDrain');
	    		var o = s.find('option:selected');
	    		var item = {
			        productKey: s.val(),
			        sku: o.attr('data-sku'),
			        description: {'en-CA': drain_en[s.val()].description, 'fr-CA': drain_fr[s.val()].description},
		            title: {'en-CA': draintype_en[dt.attr('data-type')], 'fr-CA': draintype_fr[dt.attr('data-type')]},
		            subtitle: {'en-CA': drain_en[s.val()].title, 'fr-CA': drain_fr[s.val()].title},
		            options: {'en-CA': '', 'fr-CA': ''},
			        quantity: 1,
			        price: o.attr('data-price' + currencyCode.toLowerCase()).replace(',','.'),
			        priceUSD: o.attr('data-priceusd').replace(',','.'),
			        priceCAD: o.attr('data-pricecad').replace(',','.'),
			        'kitsize': 1,
			        sortOrder: (Order.data.items.length + 1),
			        'photo': ''
			    };
		        
			    popup += '<div class="added"><span>' + item['title'][board_culture] + '</span>';
		        if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
		        popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			    
			    Order.data.items[Order.data.items.length] = item;
	    	}
	    });
	    
		if ($('.step4 input[name="rdoDrainCover"]').length) {
			//debugger;
			if($('.step4 input[name="rdoDrainCover"]:checked').val() != '') {
				var i = $('input[name="rdoDrainCover"]:checked');
				//console.log(i);
				var item = {
					productKey: i.attr('data-key'),
					sku: i.attr('data-sku'),
					description: {'en-CA': '', 'fr-CA': ''},
					title: {'en-CA': draincover_en[i.attr('data-key')], 'fr-CA': draincover_fr[i.attr('data-key')]},
					subtitle: {'en-CA': '', 'fr-CA': ''},
					options: {'en-CA': '', 'fr-CA': ''},
					quantity: 1,
					price: i.attr('data-price' + currencyCode.toLowerCase()).replace(',','.'),
					priceUSD: i.attr('data-priceusd').replace(',','.'),
			        priceCAD: i.attr('data-pricecad').replace(',','.'),
					'kitsize': 1,
					sortOrder: (Order.data.items.length + 1),
					'photo': i.attr('data-photo')
				};
				
				popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
				if(item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
				popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
				
				Order.data.items[Order.data.items.length] = item;
			}
		}
		//debugger;
		if ($('#hidBathTubAddOns').val()) {
			var bathTubAddOns = JSON.parse($('#hidBathTubAddOns').val());

			$.each(bathTubAddOns, function (index, item) {
				if (item) { 
					popup += '<div class="added">';
					if (item['photo']) {
						popup += '<img src="' + item['photo'] + '" /><span>';
					}
					popup += item['title'][board_culture] + '</span>';
					if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
					popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

					Order.data.items[Order.data.items.length] = item;
				}
			});
		}


		// Fibo wall from Shower door
		// Fibo wall
		if ($('#hidFibowallKey').val()) {
			var item = {
				productKey: $('#hidFibowallKey').val(),
				sku: $('#hidFibowallSku').val(),
				description: { 'en-CA': $('#hidFibowallDescriptionEn').html(), 'fr-CA': $('#hidFibowallDescriptionFr').html() },
				title: { 'en-CA': $('#hidFibowallTitleEn').html(), 'fr-CA': $('#hidFibowallTitleFr').html() },
				subtitle: { 'en-CA': $('#hidFibowallSubTitleEn').html(), 'fr-CA': $('#hidFibowallSubTitleFr').html() },
				options: { 'en-CA': "", 'fr-CA': "" },
				quantity: 1,
				price: $('#hidFibowallPrice').val(),
				priceUSD: $('#hidFibowallPriceUSD').val(),
				priceCAD: $('#hidFibowallPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidFibowallImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';

			Order.data.items[Order.data.items.length] = item;
		}

		// Install Kit
		if ($('#hidInstallFibowallKey').val()) {
			var item = {
				productKey: $('#hidInstallKey').val(),
				sku: $('#hidInstallFibowallSku').val(),
				description: { 'en-CA': "", 'fr-CA': "" },
				title: { 'en-CA': "", 'fr-CA': "" },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				//options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: { 'en-CA': "", 'fr-CA': "" },
				quantity: 1,
				price: $('#hidInstallFibowallPrice').val(),
				priceUSD: $('#hidInstallFibowallPriceUSD').val(),
				priceCAD: $('#hidInstallFibowallPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidInstallFibowallImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//

			Order.data.items[Order.data.items.length] = item;
		}

		// Accent Panel
		if ($('#hidAccentFibowallKey').val()) {
			var item = {
				productKey: $('#hidAccentFibowallKey').val(),
				sku: $('#hidAccentFibowallSku').val(),
				description: { 'en-CA': "", 'fr-CA': "" },
				title: { 'en-CA': "", 'fr-CA': "" },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				//options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: { 'en-CA': "", 'fr-CA': "" },
				quantity: 1,
				price: $('#hidAccentFibowallPrice').val(),
				priceUSD: $('#hidAccentFibowallPriceUSD').val(),
				priceCAD: $('#hidAccentFibowallPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidAccentFibowallImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//

			Order.data.items[Order.data.items.length] = item;
		}

		// FIBO Grip
		if ($('#hidGripFibowallKey').val()) {
			var item = {
				productKey: $('#hidGripFibowallKey').val(),
				sku: $('#hidGripFibowallSku').val(),
				description: { 'en-CA': "", 'fr-CA': "" },
				title: { 'en-CA': "", 'fr-CA': "" },
				subtitle: { 'en-CA': '', 'fr-CA': '' },
				//options: {'en-CA': $('#hidAccessoryOptionsEn').html(), 'fr-CA': $('#hidAccessoryOptionsFr').html()},
				options: { 'en-CA': "", 'fr-CA': "" },
				quantity: 1,
				price: $('#hidGripFibowallPrice').val(),
				priceUSD: $('#hidGripFibowallPriceUSD').val(),
				priceCAD: $('#hidGripFibowallPriceCAD').val(),
				'kitsize': 1,
				sortOrder: (Order.data.items.length + 1),
				'photo': $('#hidGripFibowallImage').val()
			};

			popup += '<div class="added"><img src="' + item['photo'] + '" /><span>' + item['title'][board_culture] + '</span>';
			if (item['subtitle'][board_culture] != '') popup += item['subtitle'][board_culture] + '<br/>';
			popup += item['sku'] + '<div class="divquoteoptions">' + item['options'][board_culture] + '</div></div>';
			//

			Order.data.items[Order.data.items.length] = item;
		}





	    popup += '<div style="clear:both"></div></div><a href="javascript:;" onclick="$.fancybox.close();">OK</a></div>';

	    Order.SaveCartContents(false); 
	    $('#quotesent').val(1);       
	    //EcomUI.GoToCart(); 
	    
	    $.fancybox({
	        content:popup,
	        width:800,
	        autoSize: false,
	        afterClose: function() {
	            if(type != '') {    	
	        	    var pl = new SOAPClientParameters();
	        		pl.add("CultureCode", board_culture);		
	        		SOAPClient.invoke(URL_SOAP_CART, "GetCartUrl", pl, true, function(data) {
	        			if (window.ecomUserSettings && window.ecomUserSettings.onGoToHttps)
	        				httpsUrl = "https://" + window.location.host;
	        	        if(type != '') type = '?t=' + type;
	        			document.location = httpsUrl + data + type;
	        		});
	        	}
	        }
	    });

	    $(".btnaddnew").show();
	}
    
}


/* BUILD */
function stepRadio(step, option) {

	if (option == undefined)
		option = "";

	$(".step" + option + step).show();

	if (hasOneItem(step, option))
		selectFirst(step, option);
	else
		$(".step" + option + step + " .show input:radio:not(:disabled)").prop('checked', false);
}

function stepRadioData(step, data, option) {
	debugger;
	if (option == undefined)
		option = "";

	$(".step" + option + step + " input:radio:not(:disabled)").prop('checked', false);
	if (data) {
		var json = $.parseJSON(data);

		if (json && json.empty == "false") {
			$(".step" + option + step).show();
			updateRadio(step, json.data, option);


			if (json.oneitem == "true") {
				selectFirst(step, option);
			}
			else {			
				$(".step" + option + step + " .show input:radio:not(:disabled)").prop('checked', false);
			}
		}
	}
	else {
		$(".step" + step).hide();

		if (option == "base")
			nextStepBase(step);
		else if (option == "accessory")
			nextStepAccessory(step);
		else if (option == "Bathtub")
			nextStepBathtub(step);
		else
			nextStep(step);
	}
}

function updateRadio(step, items, option) {

	if (option == undefined)
		option = "";

	var data = $.parseJSON(items);

	$('.step' + option + step + " .imagelbl:not(.item0)").removeClass("show");

	for (i = 0; i < data.length; i++) {
	   $('.step' + option + step +' .imagelbl.item' + data[i].key).addClass("show");
	} 
}

function stepSelectData(step, data, option) {

	debugger;
	if (option == undefined)
		option = "";

	var json = $.parseJSON(data);
	//alert(data);
	if (json.empty == "false") {
		$(".step" + option + step).show();
		updateSelect(step, json.data, option);
		if (json.oneitem == "true") {
			selectFirst(step, option);
		}
	}
	else {
		$('.step' + option + step).find('select').find('option:not(:first)').remove();
		$('.step' + option + step).find('select').prop("selectedIndex", 1);
		if (option == "base")
			nextStepBase(step);
		else if (option == "accessory")
			nextStepAccessory(step);
		else
			nextStep(step);
	}
}

function updateSelect(step, items, option) {

	if (option == undefined)
		option = "";

	var data = $.parseJSON(items);

	$('.step' + option + step).find('select').find('option:not(:first)').remove();
	$('.step' + option + step).find('select').prop("selectedIndex", 1);

	for (i = 0; i < data.length; i++) {
	   var datakey = (data[i].datakey) ? '" data-key="' + escape(data[i].datakey) + '">' : '">';
	   $('.step' + option + step).find('select').append('<option value="' + data[i].key + datakey + data[i].value + '</option>');
	} 
}

function hasItem(step, option) {

	if (option == undefined)
		option = "";

	return $(".step" + option + step + " .show").length > 0;
}

function hasOneItem(step, option) {

	if (option == undefined)
		option = "";

	return $(".step" + option + step + " .show").length == 1;
}

function selectFirst(step, option) {

	if (option == undefined)
		option = "";

	$(".step" + option + step + " select").prop("selectedIndex", 1);
	$(".step" + option + step + " input:radio:not(:disabled):first").prop('checked', 'checked');
	$(".step" + option + step + " .show input:radio:not(:disabled):first").prop('checked', 'checked');

	if (option == "base")
		nextStepBase(step);
	else if (option == "accessory")
		nextStepAccessory(step);
	else if (option == "Bathtub")
		nextStepBathtub(step);
	else if (option == "fibowall")
		nextStepFibowall(step);
	else
		nextStep(step);
}

function hideStep(step) {
	var i;
	for (i = step + 1; i < 16; i++) {
	    $(".step" + i).hide();
        $(".step" + i + ':not(.no-init)').find('select').val('');
        $(".step" + i + ':not(.no-init)').find('input[type="radio"]').prop('checked', false);
	} 

	$(".product-total").hide();
	$('.product-sku, #product-total-amount').html('');
	$('#quotesent').val(0); 
}

function createCode(option, nofinish, pageName) {
	var i, value, code = "";
	var build = coding;

	if (option == undefined)
		option = "";
	else
		build = codingbase;
	
	console.log("yo");
	console.log(option);
	console.log(build);
	for (i = 0; i < template.length; i++) {
		console.log(build[template[i]]);
		let buildTemplateVar = build[template[i]];
		if (buildTemplateVar.object == "value") {
			code += buildTemplateVar.value;
		}
		else if (buildTemplateVar.object == "rdoFinish" && nofinish) {
			console.log('nofinish');
			// alert("abhi");
		}

		/*else if (build[template[i]].object == "drpDepth") {
			console.log('drpDepth');
			console.log($("#" + build[template[i]].object + option).val());
			if($("#" + build[template[i]].object + option).val()==38.5){
				console.log("oui c'est 38.5");
			//$("#" + build[template[i]].object + option).val("38");
			}
		}*/

		else {
			//else if (build[template[i]].object == "drpFront") {
			console.log($("#" + build[template[i]].object + option).val());
			let buildTemplateOptionVar = $("#" + build[template[i]].object + option);
			if (buildTemplateOptionVar.val() == 53) {
				console.log("53");
				$("#" + "hidFiboCode").val('FBA48-');
				$("#" + "hidFiboCodePrimCode").val(4838);
				if (!pageName) {
					buildTemplateOptionVar.val(null);
				}
			}
			else if (buildTemplateOptionVar.val() == 62) {
				console.log("62");
				//$("#" + "hidFiboCode").val(60);
				$("#" + "hidFiboCodePrimCode").val(6038);
				if (!pageName) {
					buildTemplateOptionVar.val(null);
				}
			}
			else if (buildTemplateVar.object != "drpHeight") {
				if (buildTemplateOptionVar.val() == 77) {
					console.log("77");
					//$("#" + "hidFiboCode").val(60);
					$("#" + "hidFiboCodePrimCode").val(7238);
					if (!pageName) {
						buildTemplateOptionVar.val(null);
					}

				} else if (buildTemplateOptionVar.val() == 38.5){
					console.log("38.5");
					//$("#" + "hidFiboCode").val(60);
					$("#" + "hidFiboCodePrimCode").val(3838);
					if (!pageName) {
						buildTemplateOptionVar.val(null);
					}
				}
			}
			value = buildTemplateOptionVar.val();
		      if (value === undefined) {
				  value = $('input[name="' + buildTemplateVar.object + option + '"]:checked').val();
			} 
			if (value !== undefined) {
				if(value == null) value = "";
				code += value;
			}
		} 
	} 
    if(code.charAt(code.length-1) == '-') code = code.slice(0,-1);
    code = code.replace('--', '-');
	return code;
}


function updateBaseDescription(option) {

	if (option == undefined)
		option = "";

    var description_en = "";
    var description_fr = "";

    if (option == "") {
    	description_en = base_en[$('#hidKey').val()]['title'].trim();
        if(base_en[$('#hidKey').val()]['subtitle'] != '') description_en += ' ' + base_en[$('#hidKey').val()]['subtitle'].trim();
    }
    else {
    	description_en = $('#hid' + option + 'En').val();
    }
    	
    if($('input[name="rdoMaterial' + option + '"]:checked').val()) description_en += ', ' + material_en[$('input[name="rdoMaterial' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoDrainCover' + option + '"]:checked').val()) description_en += ', Drain cover: ' + draincover_en[$('input[name="rdoDrainCover' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoFinish' + option + '"]:checked').val()) description_en += ', Finish: ' + finish_en[$('input[name="rdoFinish' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoTexture' + option + '"]:checked').val()) description_en += ', Texture: ' + texture_en[$('input[name="rdoTexture' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoTrim' + option + '"]:checked').val()) description_en += ', Trim Color: ' + trim_en[$('input[name="rdoTrim' + option + '"]:checked').attr('data-key')];
   
	if($('input[name="rdoSide' + option + '"]:checked').val()) description_en += ', ' + direction_en[$('input[name="rdoSide' + option + '"]:checked').val()];
    description_en += ', ' + $('#drpDepth' + option).val() + ' x ' + $('#drpFront' + option).val();
    

    if (option == "") {
    	description_fr = base_fr[$('#hidKey').val()]['title'].trim();
        if(base_fr[$('#hidKey').val()]['subtitle'] != '') description_fr += ' ' + base_fr[$('#hidKey').val()]['subtitle'].trim();
    }
    else {
    	description_fr = $('#hid' + option + 'Fr').val();
    }

    if($('input[name="rdoMaterial' + option + '"]:checked').val()) description_fr += ', ' + material_fr[$('input[name="rdoMaterial' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoDrainCover' + option + '"]:checked').val()) description_fr += ', Drain: ' + draincover_fr[$('input[name="rdoDrainCover' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoFinish' + option + '"]:checked').val()) description_fr += ', Finition: ' + finish_fr[$('input[name="rdoFinish' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoTexture' + option + '"]:checked').val()) description_fr += ', Texture: ' + texture_fr[$('input[name="rdoTexture' + option + '"]:checked').attr('data-key')];
    if($('input[name="rdoTrim' + option + '"]:checked').val()) description_fr += ', Couleur de Trim: ' + trim_fr[$('input[name="rdoTrim' + option + '"]:checked').attr('data-key')];
    
	if($('input[name="rdoSide' + option + '"]:checked').val()) description_fr += ', ' + direction_fr[$('input[name="rdoSide' + option + '"]:checked').val()];
    description_fr += ', ' + $('#drpDepth' + option).val() + ' x ' + $('#drpFront' + option).val();
    
    console.log(description_en, description_fr);
    $('#hid' + option + 'DescriptionEn').html(description_en);
    $('#hid' + option + 'DescriptionFr').html(description_fr);
    
    var baseKey = (option == "") ? $('#hidKey').val() : $('input[name="rdoBase"]:checked').val();
    $('#hid' + option + 'TitleEn').html(base_en[baseKey]['title'].trim());
    $('#hid' + option + 'TitleFr').html(base_fr[baseKey]['title'].trim());
        
    $('#hid' + option + 'SubTitleEn').html(base_en[baseKey]['subtitle'].trim());
    $('#hid' + option + 'SubTitleFr').html(base_fr[baseKey]['subtitle'].trim());
    
    var options_en = new Array();
    var options_fr = new Array();
    
    if($('input[name="rdoMaterial' + option + '"]:checked').val()) options_en.push(material_en[$('input[name="rdoMaterial' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoMaterial' + option + '"]:checked').val()) options_fr.push(material_fr[$('input[name="rdoMaterial' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoDrainCover' + option + '"]:checked').val()) options_en.push('Drain cover: ' + draincover_en[$('input[name="rdoDrainCover' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoDrainCover' + option + '"]:checked').val()) options_fr.push('Drain: ' + draincover_fr[$('input[name="rdoDrainCover' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoFinish' + option + '"]:checked').val()) options_en.push('Finish: ' + finish_en[$('input[name="rdoFinish' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoFinish' + option + '"]:checked').val()) options_fr.push('Finition: ' + finish_fr[$('input[name="rdoFinish' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoTexture' + option + '"]:checked').val()) options_en.push('Texture: ' + texture_en[$('input[name="rdoTexture' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoTexture' + option + '"]:checked').val()) options_fr.push('Texture: ' + texture_fr[$('input[name="rdoTexture' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoTrim' + option + '"]:checked').val()) options_en.push('Trim Color: ' + trim_en[$('input[name="rdoTrim' + option + '"]:checked').attr('data-key')]);
    if($('input[name="rdoTrim' + option + '"]:checked').val()) options_fr.push('Couleur de Trim: ' + trim_fr[$('input[name="rdoTrim' + option + '"]:checked').attr('data-key')]);
   
	if($('input[name="rdoSide' + option + '"]:checked').val()) options_en.push(direction_en[$('input[name="rdoSide' + option + '"]:checked').val()]);
    if($('input[name="rdoSide' + option + '"]:checked').val()) options_fr.push(direction_fr[$('input[name="rdoSide' + option + '"]:checked').val()]);
    
    options_en.push($('#drpDepth' + option).val() + ' x ' + $('#drpFront' + option).val());
    options_fr.push($('#drpDepth' + option).val() + ' x ' + $('#drpFront' + option).val());
    
    $('#hid' + option + 'OptionsEn').html(options_en.join('<br/>'));
    $('#hid' + option + 'OptionsFr').html(options_fr.join('<br/>'));
    
    return true;
}


function sendQuote() {
	var regEmail=/\S+@\S+\.\S+/;
	var email=document.getElementById("contactemail").value;
		console.log(email);
	if(regEmail.test(email)){
		console.log("work");
    var name = $('#contactname').val();
    var phone = $('#contactphone').val();
    var email = $('#contactemail').val();
    var bottomtext = $('.divcartwarning .visible').html() + '<br/>' + $('.divcartwarning .quotedate').html();
    var message = "";
    var agree = ($('#contactagree:checked').val() == 'agree') ? 'agree' : '';
    
    if (agree == '') {
        $('#contactagreemessage').html(SBPhrases["AGREE"]).show();
        return false;
    }
    
    if (name == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_NAME"]) + '\n';
    if (phone == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_PHONE"]) + '\n';
    if (email == '')
		 message += String.format(SBPhrases["REQUIRED_FIELD"], SBPhrases["CART_EMAIL"]) + '\n';
    
    
    if(message != "") {
        alert(message);
        return false;
    } else {
        var data = {name:name, phone:phone, email:email, bottomtext:bottomtext, agree:agree};
        var pl = new SOAPClientParameters();
        pl.add("Items", JSON.stringify(Order.data.items));
        pl.add("Data", JSON.stringify(data));
    	pl.add("CultureCode", board_culture);
    
    	SOAPClient.invoke(URL_SOAP_CUSTOMER, "SendQuote", pl, true, function(data) {
    		alert(SBPhrases["EMAIL_SENT"]);
    	});
     }
	}
	else{
		console.log(email);
		console.log("didnt work at all");
		alert("Email Invalid");
	}
	if(document.getElementById("contactemail1").classList.contains("shownAddEmail")){		
		sendQuote1();
		console.log("sent quote 1");
		if(document.getElementById("contactemail2").classList.contains("shownAddEmail")){
			sendQuote2();
			if(document.getElementById("contactemail3").classList.contains("shownAddEmail")){
				sendQuote3();
				if(document.getElementById("contactemail4").classList.contains("shownAddEmail")){
					sendQuote4();
					if(document.getElementById("contactemail5").classList.contains("shownAddEmail")){
						sendQuote5();
					}
		}
		}
	}
}
}





collectCampaignData = function(sender, key, step)
{
	var form = sender;
	var name, lastname;
	var cancelled = false;
	var returnValue = {};
	var done = false;
	var unsortedData = [];

	if (!ValidateCaptcha()) {
		if (SBPhrases["REQUIRED_CAPTCHA"])
		  	alert(SBPhrases["REQUIRED_CAPTCHA"]);
		else
			alert("Please check the captcha form.");
		return false;
	}

	while (form.parentNode && !cancelled && !done)
	{
		form = form.parentNode;
		if (step)
			done = form.className && (form.className.toLowerCase() == "step" || form.className.toLowerCase() == "divstep" || form.className.toLowerCase() == "divcampaigncontainer");
		else
			done = form.className && form.className.toLowerCase() == "divcampaigncontainer";
				
		var inputs = form.getElementsByTagName("INPUT");
		var selects = form.getElementsByTagName("SELECT");
		var textareas = form.getElementsByTagName("TEXTAREA");

		var requiredFields = "";

		for (var i = 0; i < selects.length; i++)
		{
			var selections = "";
			var multipleSelections = false;
			for (j = 0; j < selects[i].options.length; j++)
			{
				if (selects[i].options[j].selected)
				{
					if (selections != "")
					{
						selections += "\n\t";
						multipleSelections = true;
					}
					selections += selects[i].options[j].text;
				}
			}
			var breaker = "";
			if (multipleSelections)
			{
				breaker = "\n\t";
			}
			
			if (key)
				name = selects[i].name;
			else
				name = getMailFormFieldCaption(selects[i]);
					
			
			if ((selects[i].getAttribute("required")) && (selects[i].getAttribute("required").toLowerCase() == "yes" || selects[i].getAttribute("required").toLowerCase() == "required") && (selections == "" || selections.toLowerCase() == "- select -" || selections.toLowerCase() == "- selectionnez -" ))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(selects[i])) + "\n";
			}
			//campaignData[name] = breaker + selections;	
			unsortedData.push({
				'seq': selects[i].attributes["seq"].value,
				'name': name,
				'value': breaker + selections
			});
		}

		for (var i = 0; i < inputs.length; i++)
		{
			if ((inputs[i].name != "panel") && (inputs[i].type != "button") && (inputs[i].name != "__VIEWSTATE") && (inputs[i].name != "cf-turnstile-response") && (inputs[i].name.toLowerCase() != "viewstateuserkey") && (inputs[i].type != "radio") && (((inputs[i].type != "checkbox")) || (inputs[i].checked)))
			{
				lastname = name;
				if (key)
					name = inputs[i].name;
				else
					name = getMailFormFieldCaption(inputs[i]);
				if (inputs[i].value)
				{
					if (lastname != name)
					{
						//campaignData[name] = inputs[i].value;
						unsortedData.push({
							'seq': inputs[i].attributes["seq"].value,
							'name': name,
							'value': inputs[i].value
						});
					}
					else
					{
						campaignData[name] += ", " + inputs[i].value;
					}
				}
				if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && ((inputs[i].value == "") || (inputs[i].value == inputs[i].defaultValue)))
				{
					requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(inputs[i])) + "\n";
					inputs[i].focus();
					cancelled = true; /* breaks loop. */
				}
			} 
		}

		/* RADIO */
		name = "";
		var hasValue = false;
		var hasRadio = false;
		var isRequired = false;
		for (var i = 0; i < inputs.length; i++)
		{
			if (inputs[i].type == "radio")
			{
				hasRadio = true;
				lastname = name;
				if (key)
					name = inputs[i].name;
				else
					name = getMailFormFieldCaption(inputs[i]);

				if (lastname != name && lastname != "")
				{
					if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required") && !hasValue)
					{
						requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(inputs[i])) + "\n";
						cancelled = true; /* breaks loop. */
					}
				}
				else
				{
					if (inputs[i].getAttribute("required") && (inputs[i].getAttribute("required").toLowerCase() == "yes" || inputs[i].getAttribute("required").toLowerCase() == "required")) {
						isRequired = true;
					}

					if (inputs[i].checked) {
						hasValue = true;
						//campaignData[name] = inputs[i].value;
						unsortedData.push({
							'seq': inputs[i].seq,
							'name': name,
							'value': inputs[i].value
						});
					}
				}
			} 
		}

		if (hasRadio) {
			if (isRequired && !hasValue)
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], lastname) + "\n";
				cancelled = true; /* breaks loop. */
			}
		}

		for (var i = 0; i < textareas.length; i++)
		{
			if (key)
				name = textareas[i].name;
			else
				name = getMailFormFieldCaption(textareas[i]);
			//campaignData[name] = textareas[i].value;
			unsortedData.push({
				'seq': textareas[i].attributes["seq"].value,
				'name': name,
				'value': textareas[i].value
			});
			if ((textareas[i].getAttribute("required") == "yes" || textareas[i].getAttribute("required") == "required") && (textareas[i].value == ""))
			{
				requiredFields += String.format(SBPhrases["REQUIRED_FIELD"], getMailFormFieldCaption(textareas[i])) + "\n";
				textareas[i].focus();
			}
		}
	}

	tempData = unsortedData.slice(0);
	sortedData = tempData.sort(function (a, b) { return a.seq - b.seq; });
	for (var cnt = 0; cnt < sortedData.length; cnt++) {
		campaignData[sortedData[cnt].name] = sortedData[cnt].value;
	}

	if (requiredFields)
	{
		$(sender).show();
		alert(requiredFields);
		return false;
	}
	else if (cancelled)
		return	false;
	else
		return true;
}


doSaveCampaign = function(sender, token = "")
{
	debugger;
	$(sender).hide();
	var spanCampaignTitle = document.getElementById("spanCampaignTitle");
	var spanCampaignGuid = document.getElementById("spanCampaignGuid");

	subject = "";
	$('.subject').each(function(){
		if (subject != "")
			subject += " - "
	    subject+=$(this).val();
	});

	if (collectCampaignData(sender, true, false))
	{	
		pl = new SOAPClientParameters();
		pl.add("Campaign", spanCampaignTitle.innerHTML);
		pl.add("Subject", subject);
		pl.add("Data", JSON.stringify(campaignData));		
		pl.add("DealerGuid", spanCampaignGuid.innerHTML);
		pl.add("LastStep", true);
		pl.add("CultureCode", board_culture);
		if (token == "") {
 			SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaign", pl, true, function(url) {
 				// Thanks page
 				document.location = url;
 			});
 		}
 		else {
 			pl.add("CaptchaToken", token);
 			SOAPClient.invoke(URL_SOAP_TOOLBOX, "SaveCampaignWithRecaptchaValidation", pl, true, function(url) {
 				if (url === "CAPTCHA_FAILED") {
 					alert("CAPTCHA validation failed.");
 				} else {
 					// Thanks page
 					document.location = url;
 				}
 			});
 		}
	}
	else 
	{	
		$(sender).show();
	}	
};

/********************************
/modules/Adeo.SpringBoard.Ecommerce/controller/Adeo.Ecommerce.js
********************************/
var httpsUrl = ""; //"https://" + window.location.host + ":" + window.location.port;

if (window.httpsUrl)
	httpsUrl = window.httpsUrl;

//loadjscssfile(httpsUrl + '/modules/Adeo.SpringBoard.Ecommerce/view/ecommerce.css', 'css');
//loadjscssfile(httpsUrl + '/site/view/css/ecommerce.css', 'css');

/******************************************************************************************
File: Adeo.Ecommerce.js
Date: 20/10/2011

Possible extern function

- onChangeCurrency:
	Event on change currency (drpCurrency)

- onAfterLoadCurrencies:
	Event after load currencies (drpCurrency)
	
- onAddToCart: 
	For add item into the cart
	
- onProcessShipping: 
	For override the shipping price

- onBeforeShowCart: 
	Event before the function ShowCart

- onBeforeUpdateItem:
	Event before the function UpdateItem
	
- onBeforeProcessPayment
    Event before the function ProcessPayment (for special validate)

- onGoToHttps
	For redirect to https
	
- onAfterGetPaymentMethods:
	Event after loading payment methods

------------------------------------------
exemple:

window.ecomUserSettings = {
	onAddToCart: websiteAddToCart,
	... : ...
};

function websiteAddToCart()
{
	// code here
}
------------------------------------------
*******************************************************************************************/

function AdeoOrder(orderUserSettings)
{
	/* Load cart contents from cookie if possible */
	//var CART_CONTENTS = "CART_CONTENTS_COOKIE";
	var CART_CONTENTS_VERSION = "CART_CONTENTS_VERSION";
	this.CART_TOKEN = "Cart_Token";
	this.CAMPAIGN_TRACKING_CODE = "CampaignTrackingCode";
	
	this.VERSION_NUMBER = "2.33";
		
	//this.CART_CONTENTS = CART_CONTENTS;
	var data = {
		ip: board_clientIP,
		currency: null,
		email: null,
		confirmEmail: null,
		phone: null,
		fax: null,
		extension: null,
		mailingList: null,
		createAccount: null,
		password: null,
		confirmPassword: null,
		hear: null,
		browser: navigator.userAgent,
		billingAddress: {
			customerName: null, 
			address1: null,
			address2: null,
			city: null,
			country: null,
			state: null,
			postalCode: null,
			phone: null,
			extension: null
		}, 
		shippingAddress: {
			useBilling: null,
			customerName: null, 
			address1: null,
			address2: null,
			city: null,
			country: null,
			state: null,
			postalCode: null,
			phone: null,
			extension: null,
			email: null
		},
		comments: "",
		items: [],
		shipping: 0,
		tax: [],
		taxlabel: "0.00$",
		discount: 0,
		giftCards: [],
		giftcard: 0,
		token: null,
		coupons: [],
		TrackCouponsOnly: false,
		payment: {},
		recurringDescription: '',
		recurringUnit: 'month', // day, week, month, eom
		recurringNow: 'true',   // 
		recurringStart: '',   // Start date (default: now) format yyyy/mm/dd
		recurringTime: 12,      //
		recurringPeriod: 1,     // 
		recurringAmount: 0,
		recurringTax: 0,
		recurringTaxLabel: "0.00$"
	};

	this.DefaultSettings = orderUserSettings;
	this.data = data;
	this.LoadDefaults = function () {
	    /* override default settings */
	    if (this.DefaultSettings) {
	        for (var key in this.DefaultSettings) {
	            this.data[key] = this.DefaultSettings[key];
	        }
	    }
	}
	this.LoadDefaults();

	var PromoHandlers = [];
	this.PromoHandlers = PromoHandlers;

	/*
	var cartCookie = getCookie(CART_CONTENTS);
	if (cartCookie && this.VERSION_NUMBER == getCookie(CART_CONTENTS_VERSION))
	{
		this.data = $.evalJSON(cartCookie);
		this.LoadCouponHandlers();
	}
	EcomUI.CartUpdateHandler();
	*/
	var Loaded = false;
	this.Loaded = Loaded;
	var pl = new SOAPClientParameters();
	SOAPClient.invoke(URL_SOAP_CART, "LoadCart", pl, true, function(data) {
		Order.Loaded = true;
		//alert(data);
		if (data)
		{
			Order.data = $.parseJSON(data);			
			EcomUI.ApplyCouponGlobal();
			Order.LoadCouponHandlers();
		}
		if (window.OnCartLoaded)
			window.OnCartLoaded();
		EcomUI.CartUpdateHandler(false);
	});
	
	this.LoadCouponHandlers = function()
	{		
		this.PromoHandlers.length = 0;
		
		for (var i = 0; i < this.data.coupons.length; i++)
		{
			this.PromoHandlers[i] = PromoFactory.CreatePromoHandler(this.data.coupons[i].type, this.data.coupons[i]);
		}
	}
	this.LoadCouponHandlers();

	/* Loads the checkout inputs into JSON data and saves to persistent cookie */
	this.InputValue = function(json, key, controlName, save)
	{
		var control = $("#" + controlName);
		if (control.length)
		{
			if (save)
			{
				json[key] = control.val();
			}
			else if (json[key])
			{
				control.val(json[key]);
			}
		}
	}

	this.RecurseInput = function(data, json, inputs, save)
	{
		for (var key in json) 
		{
			if (typeof(json[key]) == 'string')
			{
				this.InputValue(data, key, inputs[key], save);
			}
			else
			{
				this.RecurseInput(data[key], json[key], inputs[key], save);
			}
		}
	}

	this.SaveFormContents = function(Callback)
	{
		this.RecurseInput(Order.data, EcomUI.Settings.inputNames, EcomUI.Settings.inputNames, true);
		this.SaveCartContents(true, false, Callback);
	}

	this.LoadFormContents = function()
	{
		this.Loaded = true;
		this.RecurseInput(Order.data, EcomUI.Settings.inputNames, EcomUI.Settings.inputNames, false);
		
	}

	/* Places cart content in persistent cookie */
	this.SaveCartContents = function(noRefresh, IsMiniCart, Callback)
	{
	    if (EcomUI.Settings.onBeforeSaveCartContents) {	       
            validateCustom = EcomUI.Settings.onBeforeSaveCartContents();	        
        }
		var payment = this.data.payment;
		var comments = this.data.comments;
		this.data.payment = {}; //don't save the CC information in a cookie
		this.data.comments = "";
		this.data.campaignSourceCode = getCookie(this.CAMPAIGN_TRACKING_CODE);
		
		//setCookie(CART_CONTENTS, JSON.stringify(this.data));
		setCookie(CART_CONTENTS_VERSION, this.VERSION_NUMBER);
		var pl = new SOAPClientParameters();
		pl.add("CartContents", JSON.stringify(this.data));
		SOAPClient.invoke(URL_SOAP_CART, "SaveCart", pl, true, function(data) {
			if (!noRefresh)
			{
				EcomUI.CartUpdateHandler(true);
				EcomUI.ShowCart(IsMiniCart); //ASSumes something changed and we want to refresh	
			}			
			if (Callback)
				Callback();
		});
		this.data.payment = payment;
		this.data.comments = comments;
	}

	/* adds item to basket */
	this.AddItem = function(productKey, qty)
	{
		var pl = new SOAPClientParameters();
		pl.add("productKey", productKey);
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "GetProduct", pl, true, function(data) {
			/* Basic product data */
			var product = eval("(" + data + ")"); //Workaround for known bug "Invalid label" - http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel
			var actualSku = product.sku;
			var desc = product.description;
			var pric = product.price;
			if (!qty) qty = 1;
			/* Options are trickier */
			var validated = true;
			var additionalDescription = "";
			for (var i = 0; i < product.options.length; i++)
			{
				var option = product.options[i];
				/* retrieve value */
				var control = document.getElementById("productOption" + i);
				var value = control.value
				if (control.options) //<select> control
				{
					value = control.options[control.selectedIndex].text;
				}
				/* fail validation if required */
				if (!value && option.required)
				{
					validated = false;
					control.className += " validationFailed";
					alert(option.name + " is required");
				}
				else if (value)
				{
					if (additionalDescription != "")
					{
						additionalDescription += ", ";
					}
					additionalDescription += option.name + ": " + value;
					/* sku and price */
					var optionIndex = control.selectedIndex - 1; //1st one is always blank
					if (option.sku)
					{
						actualSku = option.sku;
					}
					else if (option.values && option.values[optionIndex].sku)
					{
						actualSku = option.values[optionIndex].sku;
					}
					if (option.price)
					{
						pric = option.price;
					}
					else if (option.values && option.values[optionIndex].price)
					{
						pric = option.values[optionIndex].price;
					}
				}
			}
			if (additionalDescription)
			{
				desc += " (" + additionalDescription + ")";
			}
			/* Save and refresh */
			if (validated)
			{				
				Order.data.items[Order.data.items.length] = {productKey: productKey, sku: actualSku, description: desc, quantity: qty, price: pric, kitsize: 1, sortOrder: (Order.data.items.length + 1)};
				Order.SaveCartContents(true);
				if (EcomUI.Settings.onAddToCart)
				{
					EcomUI.Settings.onAddToCart();
				}
				else
				{
					EcomUI.GoToCart();
				}
			}
		});		
	}

	// Called in checkout.template.html
	this.Place = function()
	{
	    if (!AdeoUI.waitingForShipping) {
	        var validateCustom = true;
	        EcomUI.ClearMessages();
	    
	        if (EcomUI.Settings.onBeforeProcessPayment) {	       
	            validateCustom = EcomUI.Settings.onBeforeProcessPayment();	        
	        }

	        if (validateCustom && EcomUI.ValidateCustomer() && EcomUI.ValidateAddress() && EcomUI.ValidateConfirm() && EcomUI.ValidateShipping())
		    {
			    if (EcomUI.Settings.Payment.save)
				    EcomUI.Settings.Payment.save();
			    this.SaveFormContents();
			
			    var validated = true;
			    if (EcomUI.Settings.Payment.validate)
				    validated = EcomUI.Settings.Payment.validate();
		
			    if (validated)
				    Order.ProcessPayment();
			    else
				    this.Rebind();
			
		    }
		    else
			    this.Rebind();
	        }
	    else {
	            alert("Still waiting for shiping rates. Try reloading the page");
	    }
	}
	
	this.Rebind = function()
	{
		//alert("rebinding");
		$(".divbuttoncheckout").click(function(){
			if(window.processing) return;
			window.processing = true;
			// other shipping account
			if(Order.data.ShippingCode == "OTHER") {
				if($('#dothershippingaccountno').val() == '') {
					alert(String.format(SBPhrases["REQUIRED_FIELD"], $('#dothershippingaccountno').prev().html()));
					window.processing = false;
					return;
				}
				Order.data.ShippingCode = "OTHER|" + $('#drpothershippingcompany').val() + "|" + $('#dothershippingaccountno').val();
				Order.SaveCartContents(true);
			}	
			$(".divbuttoncheckout").unbind('click');
	 		Order.Place();
			window.processing = false;
		});
	}

	/* Do not call directly unless validated */
	this.ProcessPayment = function(Callback)
	{
		var pl = new SOAPClientParameters();
		pl.add("Code", Order.data.PaymentCode);
		pl.add("Order", JSON.stringify(Order.data));
		pl.add("CultureCode", board_culture);
		$('#divbuttoncheckout').hide();
		$('#divbuttoncheckout_enable').show();
		var Me = this;
		SOAPClient.invoke(URL_SOAP_CART, "ProcessPayment", pl, true, function(data) {				
			try
			{
				var payment = eval("(" + data + ")");
				//Order.data.token = payment.token;				
				//Order.SaveCartContents(true);	
				if (payment.message)
				{
					if (Callback)
					{
						Callback(payment.message);
					}
					else
					{
						//alert("payment.message: " + payment.message);
						EcomUI.showMessage(payment.message, 'error');
						$('#divbuttoncheckout_enable').hide();
						$('#divbuttoncheckout').show();
						if (payment.refresh)
						{							
							EcomUI.UpdateGiftCard();
							EcomUI.ApplyTax();
						}
					}
				}

				if (payment.success)
				{

					var redirected = false;
					var fullConfirmationUrl = EcomUI.Settings.ConfirmationUrl + "?token=" + payment.token + "&key=" + payment.orderKey;
					if (EcomUI.Settings.Payment.type == 'submit')
					{
						var paymentForms = $("#" + EcomUI.Settings.containerNames.paymentPrePanel + " form");
						if (paymentForms.length > 0)
						{
							redirected = true;
							if (paymentForms.find(".invoice").length > 0) {
								paymentForms.find(".invoice").val(payment.orderKey);
							}
							else {
								paymentForms.append('<input class="invoice" type="hidden" name="invoice" value="' + payment.orderKey + '" />');
							}	
							paymentForms.find(".returnUrl").val(fullConfirmationUrl + "&action=finalize");
							paymentForms[0].submit();
						}
						else
						{
							alert("There is no form to submit in the payments panel. Attempting to continue."); //Not even sure if this is a good idea.
						}
					} else if (EcomUI.Settings.Payment.type == 'redirect') {
						redirected = true;
						document.location = payment.redirect;
					}

					if (!redirected) // "fill" or just plain failed
					{
						Order.data = "";
						document.location = fullConfirmationUrl;
					}
				}
				else
				{					
					Me.Rebind();
				}
				/*
				if (payment.reditect)
				{
					document.location = payment.reditect;
				}*/
				
			}
			catch (ex)
			{
				var msg = data.fileName;
				if (!msg)
					msg = ex.message;
				alert("Unexpected error: " + data);
				Me.Rebind();
			}
		});
	}

	/* Removes and refreshes */
	this.RemoveItem = function(index, IsMiniCart) {
		if (confirm(SBPhrases["CART_REMOVE_ITEM"])) {
			var group = Order.data.items[index].group;
			if (group)
			{
				while (index < Order.data.items.length && Order.data.items[index].group == group)
				    this.RemoveSingleItem(index, IsMiniCart)
			}
			else
			{
			    this.RemoveSingleItem(index, IsMiniCart);
			}
		}
	}
	
	this.RemoveSingleItem = function(index, IsMiniCart) {
		var okToRemove = true;
		if (EcomUI.Settings.OnRemoveItem)
			okToRemove = EcomUI.Settings.OnRemoveItem(index);
		if (okToRemove)
		{
			this.data.items.splice(index, 1);
			this.SaveCartContents(false, IsMiniCart);
		}
	}
	
	/* Updates quantity and refreshes */
	this.UpdateItem = function(index, qty)
	{
		if (window.beforeUpdateItem)
			window.beforeUpdateItem(index, qty);
			
		if (isNaN(parseInt(qty)))
		{
			qty = 1;			
			alert(SBPhrases["CART_QTY_INVALID"]);
		}
		qty = parseInt(qty, 10);
		
		if (window.beforeUpdateQty)
			qty = window.beforeUpdateQty(index, qty);
			
		if (qty <= 0)		
		{
			qty = 1;
			alert(SBPhrases["CART_QTY_INVALID"]);
		}
		
		var kitsize = this.data.items[index].kitsize;
		if (kitsize > 1)
		{
			var div3 = qty / kitsize;
			if (div3 != Math.round(div3))
			{
				qty = Math.ceil(div3) * kitsize;
				alert("Invalid quantity, must be a multiple of " + kitsize + ". Quantity has been set to " + qty);
			}
		}
		
		this.data.items[index].quantity = qty;
		this.SaveCartContents();
	}
}

function AdeoUI(userSettings)
{
	/* Can be used for customizations */
	var Settings = {
		defaultProductPage: '/',
		optionsTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/options.template.html',
		miniCartTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/minicart.template.html',
		cartTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/cart.template.html',
		checkoutTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/checkout.template.html',
		accountTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/account.template.html',
		confirmationTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/confirmation.template.html',
		pdfTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/pdf.template.html',
		loginTemplate: '/modules/Adeo.SpringBoard.Ecommerce/view/login.template.html',
		homePage: '/',
		iFrameItem: null,
		inputNames: {
			currency: 'drpCurrency',
			email: 'txtEmail',
			confirmEmail: 'txtEmailConfirm',
			phone: 'txtPhone',
			extension: 'txtPhoneExt',
			mailingList: 'txtMailList',
			createAccount: 'chkNewLogin',
			password: 'txtPassword',
			confirmPassword: 'txtPasswordConfirm',
			comments: 'txtOrderComments',
			hear: 'txtHear',
			giftCode: 'txtGiftCode',
			giftPin: 'txtGiftPin',
			billingAddress: {
				customerName: 'txtName', 
				companyName: 'txtCompanyName', 
				address1: 'txtAddress1', 
				address2: 'txtAddress2', 
				city: 'txtCity',
				country: 'drpCountry', 
				state: 'drpState', 
				postalCode: 'txtPostal',
				phone: 'txtPhone',
				extension: 'txtPhoneExt'
				}, 
			shippingAddress: {
				useBilling: 'chkUseBilling',
				customerName: 'txtName1', 
				companyName: 'txtCompanyName1', 
				address1: 'txtAddress11', 
				address2: 'txtAddress21',
				city: 'txtCity1', 
				country: 'drpCountry1', 
				state: 'drpState1', 
				postalCode: 'txtPostal1',
				phone: 'txtPhone1',
				extension: 'txtPhoneExt1',
				email: 'txtEmail1'
				}
		}, 
		containerNames: {
			cartContainer: 'divEcommerce',
			miniCartDialog: 'miniCartDialog',
			paymentPanel: 'divPayment',
			giftCardPanel: 'giftCardBalance',
			paymentPrePanel: 'divPrePayment',
			shippingPanel: 'divShipping',
			subTotalLabel: 'spanSubTotalAmount',
			discountLabel: 'spanDiscountAmount',
			giftCardLabel: 'spanGiftCardAmount',
			shippingLabel: 'spanShippingAmount',
			taxLabel: 'spanTaxAmounts',
			totalLabel: 'spanTotalAmount',
			cartCountLabel: 'spanCartCount',
			cartCountPanel: 'divCartCount',
			recurringSubTotalLabel: 'spanRecurringSubTotalAmount',
			recurringTaxLabel: 'spanRecurringTaxAmounts',
			recurringTotalLabel: 'spanRecurringTotalAmount',
			recurringDescription: 'spanRecurringDescription'
		},
		controlNames: {
			btnPlaceOrder: 'divbuttoncheckout'
		},
		shipping: 0,
		tax: []
	};
	this.Settings = Settings;

	/* override default settings */
	if (userSettings)
	{
		for (var key in userSettings) 
		{
			Settings[key] = userSettings[key];
		}
	}

	/* Load cart contents from cookie if possible */
	var UI_SESSION = "UI_SESSION";
	var Session = {lastProductPage: Settings.defaultProductPage};
	var sessionCookie = getCookie(UI_SESSION);
	if (sessionCookie)
	{
		Session = $.parseJSON(sessionCookie);
	}
	this.Session = Session;


	/* Places cart content in persistent cookie */
	this.SaveSession = function()
	{
		setCookie(UI_SESSION, JSON.stringify(this.Session));
	}

	/* Private */
	var templates = new Array();
	this.templates = templates;

	var countries = {};
	this.countries = countries;

	/* Loads a remote template file */
	this.LoadTemplate = function(template, controlName, data, Callback)
	{
		var doComplete = function(html) {
			var html = parseTemplate(templates[template], data);
			$("#" + controlName).html(html);
			if (template == EcomUI.Settings.checkoutTemplate)
			{
				EcomUI.RebindCountryList(function() {
					EcomUI.GetShippingMethods(function() {
						EcomUI.ApplyTax();
						EcomUI.GetPaymentMethods();
						if(Callback)
							Callback();
					});
				});
			}
			else if (template == EcomUI.Settings.loginTemplate)
			{
				$("#" + controlName).dialog();
			}
		}
		if (this.templates[template])
		{
			doComplete();
		}
		else
		{
			$.ajax({
				url: template,
				success: function(html) {
					templates[template] = html;
					doComplete();
				},
				error: function(req, status) {
					alert("Could not load template [" + template + "].Cause:\n" + req.status + " " + status);
				}
			});
		}
	}
	
	this.FormatCurrency = function(Number)
	{
		if (typeof(Number) == "string")
			Number = this.ParseCurrency(Number);
		Number = this.FixFloat(Number);
		
		var currency = SBCurrency[Order.data.currency];
		var culture = FindCultureByCode(board_culture);
		var options = {
			symbol : currency.Symbol,
			decimal : culture.CurrencyDecimalSeparator,
			thousand: '',
			precision : culture.DecimalDigits,
			format: culture.CurrencyFormat
		};
		return accounting.formatMoney(Number, options);
	}

	
	this.ParseCurrency = function(NumberString, Currency)
	{
		if (!Currency)
			Currency = Order.data.currency;
		var currency = SBCurrency[Currency];
		var culture = FindCultureByCode(board_culture);
		
		var numString = NumberString.replace(currency.Symbol, "");
		numString = numString.replace(culture.CurrencyDecimalSeparator, ".");
		numString = numString.replace(culture.CurrencyGroupSeparator, "");
		numString = numString.replace(" ", "");
		numString = numString.replace("&nbsp;", "");
		
		return parseFloat(numString);
	}


	this.RevokeCoupon = function(Index, Template, Silent)
	{
		var remove = false;
		var revokingCode = Order.data.coupons[Index].code;
		if (Order.data.coupons[Index])
		{	
			if (Silent)
			{
				remove = true;
			}
			else if (confirm(SBPhrases["CART_COUPON_REVOKE"] + " [" + revokingCode + "]?"))
			{
				remove = true;				
			}
			
			if (remove)
			{
				Order.PromoHandlers[Index].OnRevoke();
				for (var i = 0; i < Order.data.items.length; i++)
				{
					if (Order.data.items[i].couponShippingCode == revokingCode)
					{
						delete Order.data.items[i]["couponShippingCode"];
						delete Order.data.items[i]["couponShipping"];
					}
				}
				Order.data.coupons.splice(Index, 1);
				Order.LoadCouponHandlers();
				Order.SaveCartContents(true);
				if (Template) {
					EcomUI.ApplyCouponGlobal();
					EcomUI.LoadTemplate(Template, 'divEcommerce', Order.data);
				}
			}
		}
	}

	this.ApplyCoupon = function(CouponCode, Template, noAlerts, TrackOnly)
	{
		var couponApplied = false;
		var couponDuplicate = false;
		var couponGlobal = false;	
		var couponGlobalDuplicate = false;	
		var couponCount = 0;
		CouponCode = CouponCode.replace(/^\s+|\s+$/gm,'');
		if (CouponCode)
		{
			for (var i = 0; i < Order.data.coupons.length; i++)
			{
				couponApplied = couponApplied || (Order.data.coupons[i].code.toLowerCase() == CouponCode.toLowerCase());
				couponGlobal = couponGlobal || Order.data.coupons[i].global == "-1";
				couponDuplicate	= couponDuplicate || (Order.data.coupons[i].allowcombination == "0" && Order.data.coupons[i].global == "0");
				couponGlobalDuplicate = couponGlobalDuplicate || (Order.data.coupons[i].allowcombination == "0" && Order.data.coupons[i].global == "-1");
				couponCount++;
			}
			if (!couponApplied)
			{				
				if (!couponDuplicate)
				{
					/* Load from server */
					var pl = new SOAPClientParameters();
					pl.add("CouponCode", CouponCode);
					pl.add("CultureCode", board_culture);
					SOAPClient.invoke(URL_SOAP_CART, "GetCoupon", pl, true, function(data) {
						var coupon = eval("(" + data + ")");					
						if (!coupon.invalid)
						{			
							coupon.TrackOnly = TrackOnly;
							if (coupon.overrideglobal == "-1")							
							{
								// Remove all global coupon
								couponCount = 0;
								for (var i = Order.data.coupons.length -1 ; i >= 0 ; i--)
								{
									if (Order.data.coupons[i].global == "0")
										couponCount++;
									else
									{									
										Order.LoadCouponHandlers();
										EcomUI.RevokeCoupon(i, false, true);																			
									}	
								}
							}

						  	if (couponCount > 0 && coupon.allowcombination == "0")
						  	{	
						  		if (!noAlerts)	
						  			alert(SBPhrases["CART_COUPON_NOTCOMBINE"]);														
							}
							else
							{
								Order.data.coupons[Order.data.coupons.length] = coupon;
								Order.LoadCouponHandlers();
								Order.SaveCartContents();
								//EcomUI.LoadTemplate(Template, 'divEcommerce', Order.data);
							}
						}
						else
						{
							if (!noAlerts)
								alert(SBPhrases["CART_COUPON_INVALID"]);
						}
					});					
				}
				else
				{
					if (!noAlerts)
						alert(SBPhrases["CART_COUPON_NOTCOMBINE"]);						
				}
			}
			else
			{				
				if (!noAlerts)
					if (couponGlobal)
						alert(SBPhrases["CART_COUPON_INVALID"]);
					else
						alert(SBPhrases["CART_COUPON_ALREADY"]);
			}
		}
		else
		{			
			if (!noAlerts)
				alert(SBPhrases["CART_COUPON_REQUIRED"]);
		}
	}
	
	this.FindCoupon = function(Code)
	{
		var couponIndex = this.FindCouponIndex(Code);
		var returnValue = null;
		if (couponIndex)
			returnValue = Order.data.coupons[couponIndex];
		return returnValue;	
	}
	
	this.FindCouponIndex = function(Code)
	{
		var index = -1;
		for (var i = 0; i < Order.data.coupons.length; i++)
		{
			index = i;
		}
		return index;	
	}

	this.ApplyCouponGlobal = function()
	{		
		var couponGlobal = false;
		var couponMaster = false;
		var remove = false;

		for (var i = Order.data.coupons.length -1 ; i >= 0 ; i--)
		{		
			if (Order.data.coupons[i].expire)
			{
				var DateNow = new Date();	
				var dateSplit = Order.data.coupons[i].expire.split("-");
				DateExpire = new Date(parseInt(dateSplit[0]), parseInt(dateSplit[1]) - 1, parseInt(dateSplit[2]));
			
				if (Math.ceil((DateExpire - DateNow)/1000/60/60/24) <= 0)
				{
					Order.LoadCouponHandlers();
					EcomUI.RevokeCoupon(i, EcomUI.Settings.cartTemplate, true);
					remove = true;
				}
				else
				{
					couponGlobal = couponGlobal || (Order.data.coupons[i].global == "-1");
					couponMaster = couponMaster || (Order.data.coupons[i].overrideglobal == "-1");
				}
			}

			if (!remove) {
				for (var j = i - 1 ; j >= 0 ; j--)
				{
					if (Order.data.coupons[i].code.toLowerCase() == Order.data.coupons[j].code.toLowerCase())
					{
						// Remove dupplicate coupon
						Order.LoadCouponHandlers();
						EcomUI.RevokeCoupon(j, EcomUI.Settings.cartTemplate, true);
					}
				}
			}
		}
		
		if (!couponGlobal && !couponMaster)
		{
			/* Load from server */
			var pl = new SOAPClientParameters();
			pl.add("CultureCode", board_culture);					
			SOAPClient.invoke(URL_SOAP_CART, "GetCouponGlobal", pl, true, function(data) {
				var coupon = eval("(" + data + ")");							
				if (!coupon.invalid)
				{					
					EcomUI.ApplyCoupon(coupon.code , EcomUI.Settings.cartTemplate, true);
				}
			});
		}
	}
	
	this.ShowPromoInfo = function()
	{
		$("#divPromoInfo").dialog({width: 750, height: 250});
	}

/*
	this.ShowGiftCard = function() {
		var pl = new SOAPClientParameters();		
		SOAPClient.invoke(URL_SOAP_CART, "ShowGiftCard", pl, true, function(data) {
			Order.data.showGiftCard = data;
		});
	}
	*/
	this.RevokeGiftCard = function(Index)
	{
		var remove = false;
		var revokingCode = Order.data.giftCards[Index].Code;
		if (Order.data.giftCards[Index])
		{	
			if (confirm(SBPhrases["CART_GIFT_CARD_REVOKE"] + " [" + revokingCode + "]?"))
			{
				remove = true;				
			}
			
			if (remove)
			{	
				EcomUI.SaveGiftCard(Order.data.giftCards[Index], "DELETE");			
				Order.data.giftCards.splice(Index, 1);
				//Order.SaveCartContents(true);
				//EcomUI.ApplyTax();	
				
				
				
				//EcomUI.GetPaymentMethods();
				//Order.LoadCouponHandlers();
				//Order.SaveCartContents(true);
				//if (Template)
				//	EcomUI.LoadTemplate(Template, 'divEcommerce', Order.data);
			}
		}
	}

	this.ApplyGiftCard = function(GiftCode, GiftPin)
	{							
		var giftCardApplied = false;
						
		var giftCardCount = 0;
		if (GiftCode && GiftPin)
		{
			for (var i = 0; i < Order.data.giftCards.length; i++)
			{			
				giftCardApplied = giftCardApplied || (Order.data.giftCards[i].Code.toLowerCase() == GiftCode.toLowerCase());
				giftCardCount++;
			}
			if (!giftCardApplied)
			{	
				/* Load from server */
				var pl = new SOAPClientParameters();
				pl.add("GiftCode", GiftCode);
				pl.add("GiftPin", GiftPin);
				pl.add("CultureCode", board_culture);				
				SOAPClient.invoke(URL_SOAP_CART, "GetGiftCard", pl, true, function(data) {
					var giftCard = eval("(" + data + ")");						
					if (giftCard.invalid)
					{						
						alert(SBPhrases["CART_GIFT_CARD_INVALID"]);
					}	
					else if (giftCard.freeze)	
					{				
						alert(SBPhrases["CART_GIFT_CARD_FREEZE"]);
					}		
					else
					{							
						var index = Order.data.giftCards.length;
						Order.data.giftCards[Order.data.giftCards.length] = giftCard;
						//Order.LoadCouponHandlers();
						
						EcomUI.SaveGiftCard(giftCard, "UPDATE");
						//EcomUI.LoadTemplate(EcomUI.Settings.checkoutTemplate, 'divEcommerce', Order.data);
						
						//EcomUI.GetPaymentMethods();
						//EcomUI.ShowCheckout();
						
						document.getElementById(EcomUI.Settings.inputNames.giftCode).value = "";
						document.getElementById(EcomUI.Settings.inputNames.giftPin).value = "";
						
						//alert(getCookie("Cart_Token"));
					}
				});				
			}
			else
			{									
				alert(SBPhrases["CART_GIFT_CARD_ALREADY"]);
			}
		}
		else
		{		
			alert(SBPhrases["CART_GIFT_CARD_REQUIRED"]);
		}
	}
	
	
	this.UpdateGiftCard = function()
	{	
		var giftCardPanel = document.getElementById(EcomUI.Settings.containerNames.giftCardPanel);
		
		if (giftCardPanel)
		{
			var giftcard = "";
			for (var i = 0; i < Order.data.giftCards.length; i++)
			{			
				giftcard += "<li>" +  Order.data.giftCards[i].Code.substring(0,4)  + "****** (" + SBPhrases["CART_GIFT_CARD_BALANCE"] + ": " + EcomUI.FormatCurrency(Order.data.giftCards[i].Amount - Order.data.giftCards[i].Use) + ") ";
				giftcard += "<a href='javascript:void(0)' onclick='EcomUI.RevokeGiftCard(" + i + ")' class='aDeleteItem'><img src='/modules/Adeo.SpringBoard.Ecommerce/view/imgs/X2.png' alt='revoke' width='22' height='29' /></a>";
				giftcard += "</li>";
			}
			
			giftCardPanel.innerHTML = giftcard;
		}					
	}
	
			
	this.FindGiftCard = function(Code)
	{
		var cardIndex = this.FindGiftCardIndex(Code);
		var returnValue = null;
		if (cardIndex)
			returnValue = Order.data.giftCards[cardIndex];
		return returnValue;	
	}
	
	this.FindGiftCardIndex = function(Code)
	{
		var index = -1;
		for (var i = 0; i < Order.data.giftCards.length; i++)
		{
			index = i;
		}
		return index;
	}
		
	this.SaveGiftCard = function(giftCard, action, Callback)
	{
		var pl = new SOAPClientParameters();
		pl.add("Token", getCookie("Cart_Token"));
		pl.add("GiftCards", JSON.stringify(giftCard));
		pl.add("Action", action);
		SOAPClient.invoke(URL_SOAP_CART, "SaveGiftCard", pl, true, function(data) {
		
			Order.SaveCartContents(true);
			EcomUI.ApplyTax();
		
			if (Callback)
				Callback();
		});
	}

	this.GetGiftCardBalance = function(giftCard, Callback)
	{
		var pl = new SOAPClientParameters();
		pl.add("GiftCode", giftCard);
		SOAPClient.invoke(URL_SOAP_CART, "GetGiftCardBalance", pl, true, function(data) {
			var response = $.parseJSON(data);
			Callback(response);
		});
	}

	this.initDonation = function() {
        var amounts = SBPhrases["CART_DONATION_AMOUNTS"];
        var amounts_ar = amounts.split(';');
        $('#divCartDonation select').html("");
        for(var a=0; a<amounts_ar.length; a++) {
            $('#divCartDonation select').append('<option value="' + amounts_ar[a] + '">' + amounts_ar[a] + '$</option>');
        }
        var price = null;
        for(var i=0; i<Order.data.items.length; i++) {
            if(Order.data.items[i].sku == SBPhrases["CART_DONATION_SKU"]) {
            	price = Order.data.items[i].price;
        	}
        }
        if(price) {
            $('#divCartDonation input').prop('checked', true);
            $('#divCartDonation select').val(price);
        } else {
            $('#divCartDonation input').prop('checked', false);            
        }
    }

    this.updateDonation = function() {
        if($('#divCartDonation input').prop('checked')) {
            this.removeDonation();
            var item = {
                sku: SBPhrases["CART_DONATION_SKU"],
                description: SBPhrases["CART_DONATION_DESC"],
                quantity: 1,
                price: $('#divCartDonation select').val(),
                kitsize: 1,
                tax: 2, /* No Taxable */
                weight: 0,
				sortOrder: (Order.data.items.length + 1),
				'photo': null,				
				'campaignSourceCode': "", 
				"coupon": "",
				"couponShipping": "0"	
            };
            Order.data.items[Order.data.items.length] = item;
        } else {
            this.removeDonation();
        }
        
        Order.SaveCartContents(true);
        Order.SaveFormContents(function() {
			EcomUI.ShowCheckout();
		});

		if (EcomUI.Settings.onAfterUpdateDonation)
		{
			EcomUI.Settings.onAfterUpdateDonation();
		}
    }

    this.removeDonation = function() {
        var id = null;
        for(var i=0; i<Order.data.items.length; i++) {
            if(Order.data.items[i].sku == SBPhrases["CART_DONATION_SKU"]) {
             	id = i;
            }
        }
        if(id) {
        	Order.data.items.splice(id, 1);
        }
    }
    	
	this.LoadOptions = function(productKey, controlName)
	{
		/* This is a products page. Remember it */
		this.Session.lastProductPage = document.location.toString();
		this.SaveSession();

		/* Load from server */
		var pl = new SOAPClientParameters();
		pl.add("ProductKey", productKey);
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "GetOptions", pl, true, function(data) {
			var options = {options: eval(data) }; //Don't like this.... but whatever for now.
			EcomUI.LoadTemplate(EcomUI.Settings.optionsTemplate, controlName, options);
		});
		this.AttachEvents(productKey);
	}

	this.LoadCurrencies = function()
	{
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "GetCurrencies", pl, true, function(data) {
			var currencies = eval("(" + data + ")").currencies;
			EcomUI.currencies = currencies;
			var list = document.getElementById(EcomUI.Settings.inputNames.currency);
			if (list)
			{
				$(list).change(function() {
					Order.data.currency = list.options[list.selectedIndex].value;
					Order.SaveCartContents(true);
					if (EcomUI.Settings.onChangeCurrency)
					{
						EcomUI.Settings.onChangeCurrency();
					}
				});
				list.options.length = 0;
				
				//if (window.orderUserSettings.currency && Order.data.currency == null)
				//	Order.data.currency = window.orderUserSettings.currency
				
				//alert("Currency:" + Order.data.currency + " Setting:" + window.orderUserSettings.currency);
				
				for (var i = 0; i < currencies.length; i++)
				{
					if (!Order.data.currency)
					{
						if (window.currencyCode)
							Order.data.currency = window.currencyCode;
						else
							Order.data.currency = currencies[i].code;
						Order.SaveCartContents(true);
					}
					var option = new Option(currencies[i].code, currencies[i].code);
					list.options[list.options.length] = option;
					if (currencies[i].code == Order.data.currency)
						list.selectedIndex = i;
				}
				if (EcomUI.Settings.onAfterLoadCurrencies)
				{
					EcomUI.Settings.onAfterLoadCurrencies();
				}
			}
			else
			{
				throw new Error("Control named [" + listId + "] does not exist");
			}
		});
	}

	this.CartUpdateHandler = function(Refresh)
	{
		if (Order.Loaded)
		{
			/* Promos */
			for (var p = 0; p < Order.PromoHandlers.length; p++)
				Order.PromoHandlers[p].OnCartUpdate();

			/* Item count indicator */
			var spanCartCount = document.getElementById(EcomUI.Settings.containerNames.cartCountLabel);
			var spanCartSubTotal = document.getElementById(EcomUI.Settings.containerNames.subTotalLabel);
			//var spanRecurringSubTotalAmount = document.getElementById(EcomUI.Settings.containerNames.recurringSubTotalLabel);

			var text = " 0 " + SBPhrases["CART_ITEMS"];
			var totalAmount = 0;
			var recurringTotalAmount = 0;
			if (Order.data.items.length > 0)
			{
				text = " " + Order.data.items.length + " " + SBPhrases["CART_ITEMS"];
				
				for (var i = 0; i < Order.data.items.length; i++) { 
					totalAmount += Order.data.items[i].price * Order.data.items[i].quantity;
				}

				$("#" + EcomUI.Settings.containerNames.cartCountPanel).show();
			}
			else
			{
				$("#" + EcomUI.Settings.containerNames.cartCountPanel).hide();
			}
			//not so sure about this line:
			//Order.data.totalAmount = totalAmount ;
			
			if (spanCartSubTotal)
				spanCartSubTotal.innerHTML = EcomUI.FormatCurrency(totalAmount);

			/*	alert(EcomUI.Settings.containerNames.recurringSubTotalLabel + " " + recurringTotalAmount);
			if (spanRecurringSubTotalAmount) {
				spanRecurringSubTotalAmount.innerHTML = EcomUI.FormatCurrency(recurringTotalAmount);										
			}*/

			if (spanCartCount)
				spanCartCount.innerHTML = text;
				
			if ($('.spancartnumber').length > 0) {
				$('.spancartnumber').html(Order.data.items.length);
				if(Order.data.items.length > 0) {
					$('.spancartnumber').show();
				} else {
					$('.spancartnumber').hide();
				}
			}
				
			if (Refresh && EcomUI.Settings.iFrameItem != null) {						
				var iframe = document.getElementById(EcomUI.Settings.iFrameItem);
				var iframeLocation = iframe.getAttribute('src');
				iframe.src = iframeLocation + '&when=' + Date.now();					
			}
		}
		else
			setTimeout("EcomUI.CartUpdateHandler(" + Refresh + ")", 500);
	}

	this.AttachEvents = function(productKey)
	{
		/* Add to cart */
		$('.btnAddCart').click(function() {
			qty = 1;
			var txtQuantity = document.getElementById("txtQuantity");
			if (txtQuantity)
			{
				qty = parseInt(txtQuantity.value);
			}
			//var options = EcomServer.GetOptions(productKey);
			Order.AddItem(productKey, qty);
		});
	}

	
	/* clear basket contents */
	this.EmptyBasket = function()
	{
		if (confirm(SBPhrases["CART_EMPTY_BASKET_WARN"]))
		{
		    Order.LoadDefaults();
			Order.data.items.length = 0;
			Order.SaveCartContents();
		}
	}

	this.UpdatePrice = function(newPrice)
	{
		if (newPrice)
		{
			var prices = $(".price").html(EcomUI.FormatCurrency(newPrice));
		}
	}

	this.GoToCart = function() 
	{
		/* Redirect to cart page */
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);		
		SOAPClient.invoke(URL_SOAP_CART, "GetCartUrl", pl, true, function(data) {
			if (window.ecomUserSettings && window.ecomUserSettings.onGoToHttps)
				httpsUrl = "https://" + window.location.host;		
			document.location = httpsUrl + data;
		});
	}

	this.GoToCheckout = function(NoEvent) 
	{
		var okToContinue = true;
		if (EcomUI.Settings.OnGotoCheckout)
			okToContinue = NoEvent || EcomUI.Settings.OnGotoCheckout();
		if (okToContinue)
		{
			/* Redirect to cart page */
			var pl = new SOAPClientParameters();
			pl.add("CultureCode", board_culture);
			SOAPClient.invoke(URL_SOAP_CART, "GetCheckoutUrl", pl, true, function(data) {
				if (window.ecomUserSettings && window.ecomUserSettings.onGoToHttps)
					httpsUrl = "https://" + window.location.host;
				document.location = httpsUrl + data;
			});
		}
	}
	
	this.GoToResetPassword = function() {
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "GetResetPasswordUrl", pl, true, function(data) {
			document.location = data;
		});
	}
	
	this.SendNewPassword = function() {
		var security = new SpringBoard.Security();
		security.SendPasswordReminder();
	}
	
	this.SaveNewPassword = function() {
		var newPassword = document.getElementById("txtPassword").value;
		if (newPassword == "") {
			alert(String.format(SBPhrases["REQUIRED_FIELD"], "New password"));
		} else {
			var security = new SpringBoard.Security();
			security.ResetPassword();
		}	
	}

	this.GoBackLastProduct = function()
	{
		if (this.Session.lastProductPage)
			document.location = this.Session.lastProductPage;
		else
			history.go(-1);
	}
	
	this.AccountEnter = function(myfield,e) 
	{		
		var keycode;
		if (window.event)
			keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		
		if (keycode == 13) {
			Security.UserLogin(document.getElementById('txtEcomLogin').value, document.getElementById('txtEcomPass').value, EcomUI.AfterLoginAccount);
			return false;
		}
		else		
			return true;		 
	}
	
	this.CouponEnter = function(myfield,e) 
	{		
		var keycode;
		if (window.event)
			keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		
		if (keycode == 13) {
			EcomUI.ApplyCoupon(document.getElementById('txtCouponCode').value, EcomUI.Settings.cartTemplate)
			return false;
		}
		else		
			return true;		 
	}
	
	this.CheckoutEnter = function(myfield,e) 
	{		
		var keycode;
		if (window.event)
			keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		
		if (keycode == 13) {
			Security.UserLogin(document.getElementById('txtEcomLogin').value, document.getElementById('txtEcomPass').value, EcomUI.AfterLogin)
			return false;
		}
		else		
			return true;		 
	}
	
	/* Loads the cart from a remote template file */
	this.ShowCart = function(IsMiniCart) {
		if (Order.Loaded)
		{
			if (EcomUI.Settings.onBeforeShowCart)
				EcomUI.Settings.onBeforeShowCart();
			if(IsMiniCart)
				EcomUI.LoadTemplate(EcomUI.Settings.miniCartTemplate, Settings.containerNames.miniCartDialog, Order.data);
			else
				EcomUI.LoadTemplate(EcomUI.Settings.cartTemplate, Settings.containerNames.cartContainer, Order.data);
		}
		else
			setTimeout('EcomUI.ShowCart(' + IsMiniCart + ')');
	}

	this.SimulateUpdateCart = function(IsMiniCart) {
		var divEcommerce = null;
		if(IsMiniCart) {
			divEcommerce = document.getElementById(Settings.containerNames.miniCartDialog);
			setTimeout("EcomUI.ShowCart(true)", 1000);
		} else {
			divEcommerce = document.getElementById(Settings.containerNames.cartContainer);
			setTimeout("EcomUI.ShowCart()", 1000);
		}
		divEcommerce.innerHTML = "<img src='/modules/Adeo.SpringBoard.Ecommerce/view/imgs/ajax-loader.gif' />";		
	}

	this.HasData = function(JsonObj) {
		var hasData = false;
		for (var key in JsonObj) {
			if (JsonObj[key])
				hasData = true;
		}
		return hasData;
	}

	/* Loads the checkout page from a remote template file */
	this.ShowCheckout = function() {
		if (Order.Loaded)
		{
			/* Get client info if logged in. */
			var pl = new SOAPClientParameters();
			pl.add("CultureCode", board_culture);
			SOAPClient.invoke(URL_SOAP_CART, "GetCustomerData", pl, true, function(Data) {
				var data = {};
				try
				{
					data = eval("(" + Data + ")");
					if (data.customerInfo) {
						//if (!EcomUI.HasData(Order.data.billingAddress))
							Order.data.billingAddress = data.customerInfo.billingAddress;
						//if (!EcomUI.HasData(Order.data.shippingAddress))
							Order.data.shippingAddress = data.customerInfo.shippingAddress;
						Order.data.email = data.customerInfo.mail;
						Order.data.confirmEmail = data.customerInfo.mail;
						Order.data.phone = data.customerInfo.phone;
						Order.data.extension = data.customerInfo.extension;
					}
					EcomUI.countries = data.countries;
					data.order = Order.data;
					Order.Loaded = false;
					// alert("Data: " + Data); // DEBUG!!
					EcomUI.LoadTemplate(EcomUI.Settings.checkoutTemplate, 'divEcommerce', data, function() {
						// alert(data.toSource()); // DEBUG!!
						// Verify if a new account needs to be created
						if(document.getElementById("chkNewLogin") != null) {
							if(document.getElementById("chkNewLogin").value == "ON" && ! data.isLoggedIn) {
								Order.data.createAccount = "ON";
							} else {
								Order.data.createAccount = "OFF";
								document.getElementById("chkNewLogin").value = "OFF";
							}
						}
						Order.SaveCartContents(true);
						// alert(Order.data.createAccount); // DEBUG!!
						if (EcomUI.Settings.onAfterShowCheckout)
						{
							EcomUI.Settings.onAfterShowCheckout();
						}
					});
				}
				catch (ex)
				{
					alert(data);
				}
			});
		}
		else
			setTimeout("EcomUI.ShowCheckout()", 500);
	}
	
	this.ClearMessages = function()
	{
		$.noty.closeAll();
	}
	
	this.showMessage = function(Message, Type, Icon) {
		//if(Icon)
		//	Message = '<span style="float: left; margin-right: .3em; width: 18px; text-align: left;" class="ui-icon '+ Icon +'"></span> '+ Message;
		var notyContainer = $("#notyContainer");
		if (notyContainer.length > 0)
		{
			notyContainer.noty({
				type: Type,
				text: Message,
				layout: 'top',
				dismissQueue: true
			});
		}
		else
		{	
			noty({
				type: Type,
				text: Message,
				layout: 'topRight',
				dismissQueue: true
			});
		}
	}
	
	this.showMessage = function(Message, Type, Icon, Position) {
		//if(Icon)
		//	Message = '<span style="float: left; margin-right: .3em; width: 18px; text-align: left;" class="ui-icon '+ Icon +'"></span> '+ Message;
		var notyContainer = $("#notyContainer");
		if (notyContainer.length > 0)
		{
			notyContainer.noty({
				type: Type,
				text: Message,
				layout: Position,
				dismissQueue: true
			});
		}
		else
		{	
			noty({
				type: Type,
				text: Message,
				layout: 'center',
				dismissQueue: true
			});
		}
	}

	this.ShippingCheck = function(controlName, description) {
		var result = true;		
		if (Order.data.ShippingCode == "-1" || Order.data.ShippingCode == "UPS|-1" || Order.data.ShippingCode == "FEDEX|-1" || Order.data.ShippingCode == "CANADAPOST|-1") {
			result = false;
			EcomUI.showMessage("Shipping method not valid", 'error');
		}		
		return result;
	}

	this.ConfirmCheck = function(controlName, description, confirmControlName) {
		var control = document.getElementById(controlName);
		var confirmControl = document.getElementById(confirmControlName);
		var result = true;
		if (control && confirmControl) {
			if (control.value != confirmControl.value) {
				result = false;
				EcomUI.showMessage(String.format(SBPhrases["NOTMATCH_FIELD"], description), 'error');
				//alert(String.format(SBPhrases["NOTMATCH_FIELD"], description));
				control.className += " validationFailed";
			}
		}
		return result;
	}
	
	this.RegexCheck = function(controlName, description, regex)
	{
		var control = document.getElementById(controlName);
		var result = true;
		if (control)
		{
			if (!regex.test(control.value))
			{
				result = false;
				EcomUI.showMessage(String.format(SBPhrases["INVALID_FIELD"], description), 'error');		
				//alert(String.format(SBPhrases["INVALID_FIELD"], description));
				control.className += " validationFailed";				
			}
		}
		return result;
	}

	this.NullCheck = function(controlName, description)
	{
		var INVALID_CLASS = " validationFailed";
		var control = document.getElementById(controlName);
		var result = true;
		if (control)
		{
			var val = control.value;
			if (control.options && (control.selectedIndex >= 0))
				val = control.options[control.selectedIndex].value;
			if (control.tagName.toUpperCase() == "SELECT" && control.options.length <= 1)
			{
				val = "ok"; //probably just the state
			}
				
			if (!val)
			{
				result = false;
				EcomUI.showMessage(String.format(SBPhrases["REQUIRED_FIELD"], description), 'error');		
				//alert(String.format(SBPhrases["REQUIRED_FIELD"], description));				
				control.className += INVALID_CLASS;
			}
			else
			{
				control.className = control.className.replace(INVALID_CLASS, "");
			}
		}
		return result;
	}

	this.ValidateConfirm = function()
	{
		var valid = 
				this.ConfirmCheck(Settings.inputNames.email, SBPhrases["CART_EMAIL"], Settings.inputNames.confirmEmail) &&
				this.ConfirmCheck(Settings.inputNames.password, SBPhrases["CART_PASSWORD"], Settings.inputNames.confirmPassword);
		return valid
	}

	this.ValidateShipping = function()
	{
		var valid = this.ShippingCheck();
		return valid
	}
	
	this.ValidateCustomer = function()
	{
		return this.RegexCheck(Settings.inputNames.email, SBPhrases["CART_EMAIL"], /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);
	}

	this.ValidateAddress = function()
	{
		var valid = 
				this.NullCheck(Settings.inputNames.billingAddress.customerName, SBPhrases["CART_NAME"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.address1, SBPhrases["CART_ADDRESS"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.city, SBPhrases["CART_CITY"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.country, SBPhrases["CART_COUNTRY"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.state, SBPhrases["CART_STATE"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.postalCode, SBPhrases["CART_POSTAL"]) &&
				this.NullCheck(Settings.inputNames.billingAddress.phone, SBPhrases["CART_PHONE"]);
		
		var useBilling = true;
		var chkBilling = document.getElementById(Settings.inputNames.shippingAddress.useBilling);
		if (valid && chkBilling && !chkBilling.checked)
		{
			valid = 
				this.NullCheck(Settings.inputNames.shippingAddress.customerName, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_NAME"])) &&
				this.NullCheck(Settings.inputNames.shippingAddress.address1, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_ADDRESS"])) &&
				this.NullCheck(Settings.inputNames.shippingAddress.city, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_CITY"])) &&
				this.NullCheck(Settings.inputNames.shippingAddress.country, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_COUNTRY"])) &&
				this.NullCheck(Settings.inputNames.shippingAddress.state, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_STATE"])) &&
				this.NullCheck(Settings.inputNames.shippingAddress.postalCode, String.format(SBPhrases["CART_SHIPPING_TO"], SBPhrases["CART_POSTAL"]));
		}

		return	valid;
	}

	this.EnableBilling = function(disable)
	{
		var index = 0;
		
		var ctlBilling = document.getElementById(this.Settings.inputNames.shippingAddress.useBilling);		
		if (disable)
		{
			ctlBilling.value = "ON";
		}
		else
		{
			ctlBilling.value = "OFF";
		}
			
		for (var key in this.Settings.inputNames.shippingAddress)
		{
			var control = document.getElementById(this.Settings.inputNames.shippingAddress[key]);			
			if (index && control) {
				control.disabled = disable;
				/*
				Not worth the trouble... Needs to be called on load & there is the issue of dropdowns not matching etc.
				var controlBilling = document.getElementById(controls[i]);
				if (disable && controlBilling)
				{
					control.value = controlBilling.value;
				}
				*/
			}
			index++;
		}
	}

	this.CreateAccountValue = function(strValue)
	{	
		var control = document.getElementById(this.Settings.inputNames.createAccount);
		
		if (strValue != "")
		{
			control.value = "ON";
		}
		else
		{
			control.value = "OFF";		
		}	
	}

	this.RebindCountryList = function(Callback)
	{
		var list = document.getElementById(this.Settings.inputNames.billingAddress.country);
		var list1 = document.getElementById(this.Settings.inputNames.shippingAddress.country);
		if (list && list1)
		{
			list.options.length = 0;
			list1.options.length = 0;
			list.options[0] = new Option("", "");
			list1.options[0] = new Option("", "");
			for (var i = 0; i < this.countries.length; i++)
			{
				var newOption = new Option(this.countries[i].name, this.countries[i].code);
				list.options[list.options.length] = newOption;
				if (this.countries[i].code == Order.data.billingAddress.country)
					list.selectedIndex = i + 1;
				list1.options[list1.options.length] = new Option(this.countries[i].name, this.countries[i].code);
				if (this.countries[i].code == Order.data.shippingAddress.country)
					list1.selectedIndex = i + 1;
			}
			this.RebindStateList(list);
			this.RebindStateList(list1);
			if(Callback)
				Callback();
		}
		else
		{
			//throw new Error("Controls named [" + this.Settings.inputNames.billingAddress.country + "] & [" + this.Settings.inputNames.shippingAddress.country + "] do not exist");
		}
	}
	
	this.EmptyPostalCode = function() {
		$("#txtPostal").val("");
	}

	this.RebindStateList = function(countryControl)
	{
		/* Get the country code */
		var countryCode = countryControl.options[countryControl.selectedIndex].value;
		var countryIndex = 0;
		var country;
		do
		{
			country = this.countries[countryIndex];
			countryIndex++;
		}
		while ((country.code != countryCode) && (countryIndex < this.countries.length));

		/* Reload options */
		var listId = this.Settings.inputNames.billingAddress.state;
		var address = Order.data.billingAddress;
		if (countryControl.id == this.Settings.inputNames.shippingAddress.country)
		{
			var address = Order.data.shippingAddress;
			listId = this.Settings.inputNames.shippingAddress.state;
		}
		var stateControl = document.getElementById(listId);
		if (stateControl)
		{
			stateControl.options.length = 0;
			stateControl.options[0] = new Option("", "");
			for (var i = 0; i < country.states.length; i++)
			{
				stateControl.options[stateControl.options.length] = new Option(country.states[i].name, country.states[i].code, country.states[i].code == Order.data.billingAddress.state);
				if (country.states[i].code == address.state)
					stateControl.selectedIndex = i + 1;
			}			
		}
		else
		{
			throw new Error("Control named [" + listId + "] does not exist");
		}

		/* Payment, shipping and tax might also be affected */
		if (countryControl == document.getElementById(this.Settings.inputNames.billingAddress.country)) //Don't call twice
		{			
			//this.GetPaymentMethods();			
		}
		else
		{			
			//this.GetShippingMethods();			
		}
	}

	this.CountryShippingMethods = function(countryControl)
	{
		/* Get the country code */
		var countryCode = countryControl.options[countryControl.selectedIndex].value;
		var countryIndex = 0;
		var country;
		do
		{
			country = this.countries[countryIndex];
			countryIndex++;
		}
		while ((country.code != countryCode) && (countryIndex < this.countries.length));

		if (country.states.length == 0)
		{
			var me = this;
			Order.SaveFormContents(function() { me.GetShippingMethods(); });					
		}		
	}
	
	this.GetTotalQuantity = function()
	{
		var total = 0;
		if (Order.data.items.length > 0)
		{	
			for (var i = 0; i < Order.data.items.length; i++)
				total += parseInt(Order.data.items[i].quantity);		
		}
		return total;
	}

	this.GetPaymentMethods = function()
	{
		var stateControl = document.getElementById(this.Settings.inputNames.billingAddress.state);
		var countryControl = document.getElementById(this.Settings.inputNames.billingAddress.country);
		var postalCodeControl = document.getElementById(this.Settings.inputNames.billingAddress.postalCode);

		if (postalCodeControl && countryControl && stateControl)
		{
		
			var pl = new SOAPClientParameters();
			pl.add("Country", Order.data.currency);
			pl.add("CultureCode", board_culture);
			
			if (!Order.data.currency)
			    alert("GetPaymentMethods: Currency is empty");
			
			SOAPClient.invoke(URL_SOAP_CART, "GetPaymentMethods", pl, true, function(data) {
				var paymentOptions = eval("(" + data + ")").payment;				
				EcomUI.paymentOptions = paymentOptions;				
				var paymentPanel = document.getElementById(EcomUI.Settings.containerNames.paymentPanel);
				var totalLabel = document.getElementById(EcomUI.Settings.containerNames.totalLabel);
					
				if (paymentPanel)
				{	
					paymentPanel.innerHTML = "";
					if(typeof permanentPO !== 'undefined' && permanentPO)
					{
						paymentPanel.innerHTML = SBPhrases["CART_PO_NUMBER"] + ": <input type='text' id='txtPermanentPoNumber'/><br/><br/>";
					}
					var PaymentCode = Order.data.PaymentCode;				

					//Order.data.PaymentCode = null;
					var noPaymentEnabled = false;
					var PaymentRecurring = parseFloat(Order.data.recurringAmount) > 0;

					for (var i = 0; i < paymentOptions.length; i++)
						noPaymentEnabled = noPaymentEnabled || (paymentOptions[i].code == "NOPAYMENT");					
					for (var i = 0; i < paymentOptions.length; i++)
					{											
						if (totalLabel && noPaymentEnabled && !PaymentRecurring)
						{				
							if (totalLabel.innerHTML == EcomUI.FormatCurrency("0.00"))
							{								
								if (paymentOptions[i].code == "NOPAYMENT")
								{
									//if (PaymentCode == paymentOptions[i].code || !Order.data.PaymentCode)
										Order.data.PaymentCode = paymentOptions[i].code;
									EcomUI.AppendRadioOption(paymentPanel, "payment", paymentOptions[i].name, paymentOptions[i].code, i, Order.data.PaymentCode);
								}								
							}
							else 
							{					
								if (paymentOptions[i].code != "NOPAYMENT")
								{															
									if (PaymentCode == paymentOptions[i].code || !Order.data.PaymentCode || Order.data.PaymentCode == "NOPAYMENT")
										Order.data.PaymentCode = paymentOptions[i].code;
									EcomUI.AppendRadioOption(paymentPanel, "payment", paymentOptions[i].name, paymentOptions[i].code, i, Order.data.PaymentCode);
								}
							}
						}
						else
						{	
							if (PaymentCode == paymentOptions[i].code || !Order.data.PaymentCode || Order.data.PaymentCode == "NOPAYMENT")
								Order.data.PaymentCode = paymentOptions[i].code;
							EcomUI.AppendRadioOption(paymentPanel, "payment", paymentOptions[i].name, paymentOptions[i].code, i, Order.data.PaymentCode);
						}
					}
					if (paymentOptions.length > 0)
					{
						EcomUI.LoadPrePayment(Order.data.PaymentCode);
						$("#" + EcomUI.Settings.containerNames.paymentPanel + " input[value=" + Order.data.PaymentCode + "]").attr("checked", true); //more MSIE crazyness
					}
					var totalCount = paymentOptions.length;		
					if (noPaymentEnabled)
						totalCount--; //don't count this
					if (totalCount <= 1)
						$("#divPayment").hide();
					$("#" + EcomUI.Settings.containerNames.paymentPanel + " input[type='radio']").click(function() {
						/*  start MSIE 7 nonsense */
						$("#" + EcomUI.Settings.containerNames.paymentPanel + " input").attr("checked", null);
						this.checked = true;
						/* stop... the madness*/

						if (EcomUI.Settings.Payment.save)
							EcomUI.Settings.Payment.save();
						Order.data.PaymentCode = this.value;
						Order.SaveCartContents(true);						
						EcomUI.LoadPrePayment(this.value);
					});
					if (EcomUI.Settings.onAfterGetPaymentMethods)
					{
						EcomUI.Settings.onAfterGetPaymentMethods();
					}
				}
			});
		}
		else
		{
			//throw new Error("Could not find one of the following controls: country, state, or postal code. Check your .Settings");
			if (window.console && console.log)
				console.log("Could not find one of the following controls: country, state, or postal code. Check your .Settings");
		}
	}

	this.LoadPrePayment = function(code, callback)
	{
		var pl = new SOAPClientParameters();
		pl.add("Code", code);
		pl.add("Order", JSON.stringify(Order.data));
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "PreProcessPayment", pl, true, function(data) {
			try {
				var payment = eval("(" + data + ")");
				EcomUI.Settings.Payment = payment;
			} catch (ex) {
				alert(ex.toSource() + "\nData:" + data);
			}
			var paymentPanel = document.getElementById(EcomUI.Settings.containerNames.paymentPrePanel);
			if (paymentPanel)
			{
				paymentPanel.innerHTML = payment.html;				
				if (EcomUI.Settings.Payment.load)
					EcomUI.Settings.Payment.load();
				if (callback)
					callback();
			}
		});
	}

	/* Can be overriden if necessary */
	this.AppendRadioOption = function(panel, group, caption, value, index, checkedValue)
	{
		var input = document.createElement("input");
		element = input;
		element.type = "radio";
		element.id= group + index;
		element.checked = (value == checkedValue) || (checkedValue == null && index == 0);
		element.name = group;
		element.value = value;
		element.disabled = (value == "-1");
		var okToAppend = true;		
		if (Settings.OnAppendRadioOption)
			okToAppend = Settings.OnAppendRadioOption(panel, group, caption, value, index, checkedValue);
		if (okToAppend)
		{
			panel.appendChild(element);
			element = document.createElement("span");
			element.innerHTML = caption;
			panel.appendChild(element);
			element = document.createElement("br");
			panel.appendChild(element);
		}
		return input;
	}

	this.AppendRadioGroup = function(panel, title)
	{
		element = document.createElement("span");
		element.innerHTML = title;
		element.className = "groupTitle";
		panel.appendChild(element);
		element = document.createElement("br");
		panel.appendChild(element);
	}

	this.GetShippingMethods = function(Callback)
	{
		$("body").append("<div id='ajaxLoader'><img src='/modules/Adeo.SpringBoard.Ecommerce/view/imgs/ajax-loader.gif' /><p>"+ SBPhrases["LOADING"] +"</p></div>");
		var stateControl = document.getElementById(this.Settings.inputNames.billingAddress.state);
		var countryControl = document.getElementById(this.Settings.inputNames.billingAddress.country);
		var postalCodeControl = document.getElementById(this.Settings.inputNames.billingAddress.postalCode);

		if (postalCodeControl && countryControl && stateControl)
		{
			Order.LoadFormContents();
			var pl = new SOAPClientParameters();
			pl.add("Country", countryControl.options[countryControl.selectedIndex].value);
			pl.add("State", stateControl.options[stateControl.selectedIndex].value);
			pl.add("PostalCode", postalCodeControl.value);
			pl.add("Items", JSON.stringify(Order.data.items));
			pl.add("CultureCode", board_culture);
			var Me = this;
			AdeoUI.waitingForShipping = true;
			SOAPClient.invoke(URL_SOAP_CART, "GetShippingRates", pl, true, function (data) {
			    AdeoUI.waitingForShipping = false;
				var rates = eval("(" + data + ")");
				var otherShippingCompany = rates.otherShippingCompany;
				var displayIfAlone = rates.displayIfAlone;
				var shippingMethods = rates.shipping;
				EcomUI.shippingMethods = shippingMethods;
				var shippingPanel = document.getElementById(EcomUI.Settings.containerNames.shippingPanel);
				if (shippingPanel)
				{
					shippingPanel.innerHTML = "";
					// Need to add a configuration in the admin
					if(displayIfAlone == "0" && shippingMethods.length == 1)
						$("#shippingContainer").css('display', 'none');
					var defaultInput, selectedInput;
					var findCode = false;
					var inputs = "#" + EcomUI.Settings.containerNames.shippingPanel + " input[name='shipping']";
					$(inputs).unbind('click');
					for (var i = 0; i < shippingMethods.length; i++)
					{
						EcomUI.AppendRadioGroup(shippingPanel, shippingMethods[i].name);
						var rates = shippingMethods[i].options;
						for (var j = 0; j < rates.length; j++)
						{
							if (!Order.data.ShippingCode || Order.data.ShippingCode == "-1")
								Order.data.ShippingCode = rates[j].code;
								
							var description = rates[j].name;
							if (rates[j].code != "-1" && rates[j].code != "OTHER")
							{
								var rateAmount = (rates[j].amount).toFixed(2);
								if (window.ecomUserSettings && window.ecomUserSettings.onProcessShipping)
								{
									rateAmount = window.ecomUserSettings.onProcessShipping(Order, rates[j].amount);
									rateAmount = (rateAmount).toFixed(2);
								}
								if (description.indexOf("{0}") > 0)
								{
									description = description.replace("{0}", "($" + rateAmount + ")");
								}
								else
								{							
									description += " ($" + rateAmount + ")";
								}
							}
							var code = EcomUI.GetCombinedCode(shippingMethods[i].code, rates[j].code);
							var option = EcomUI.AppendRadioOption(shippingPanel, "shipping", description, code, i, Order.data.ShippingCode);
							
							// other shipping account
							if (shippingMethods[i].code == "OTHER") {
								EcomUI.AppendOtherAccount(shippingPanel, otherShippingCompany);
							}
								
							if (code == Order.data.ShippingCode)
							{
								findCode = true;
								selectedInput = option;
							}
							
							if (!defaultInput)
								defaultInput = option;						
						}
					}
					if (!findCode)
					{
						defaultInput.checked = true;
						selectedInput = defaultInput;
					}
					
					// other shipping account
					if(selectedInput.value == "OTHER") {
						$('#divothershippingaccount').show();
					} else {
						$('#divothershippingaccount').hide();
					}
						
					/* Check promos handler */
					EcomUI.UpdateShippingPromo(selectedInput);
					Order.data.ShippingCode = selectedInput.value;
					
					//if (discountAffected)
					//	EcomUI.ShowCheckout(); // Possibility of endless loop
					//else
					
					$(inputs).click(function() {
						/*  start MSIE 7 nonsense */
						$("#" + EcomUI.Settings.containerNames.shippingPanel + " input").attr("checked", null);
						this.checked = true;
						/* stop... the madness*/
						
						EcomUI.UpdateShippingPromo(this);
						Order.data.ShippingCode = this.value;
						//EcomUI.GetPaymentMethods();
					});
					//if($("#" + EcomUI.Settings.containerNames.shippingPanel + " > input[value=\"" + Order.data.ShippingCode + "\"]").length > 0)
					//	$("#" + EcomUI.Settings.containerNames.shippingPanel + " > input[value=\"" + Order.data.ShippingCode + "\"]").trigger('click');
/*					if (Order.Loaded)
					{
						Order.SaveFormContents();
					}
					else
					{
						Order.LoadFormContents();
					}*/
				}
				if(Callback)
					Callback();
				$("body").find("#ajaxLoader").remove();
			});
		}
		else
		{
			throw new Error("Could not find one of the following controls: country, state, or postal code. Check your .Settings");
		}
	}
	
	/* for other shipping account */
	this.AppendOtherAccount = function(panel, shippingcompany)
	{
		shippingcompanyar = shippingcompany.split(";");
		div = document.createElement("div");
		div.id = "divothershippingaccount";
		element = document.createElement("label");
		element.innerHTML = SBPhrases["SHIPPING_COMPANY"];
		div.appendChild(element);
		element = document.createElement("select");
		element.id = "drpothershippingcompany";
		for(var i=0; i<shippingcompanyar.length; i++) {
			option = document.createElement("option");
			option.value = shippingcompanyar[i];
			option.innerHTML = shippingcompanyar[i];
			element.appendChild(option);
		}
		div.appendChild(element);
		element = document.createElement("br");
		div.appendChild(element);
		element = document.createElement("label");
		element.innerHTML = SBPhrases["ACCOUNT_NUMBER"];
		div.appendChild(element);
		element = document.createElement("input");
		element.id = "dothershippingaccountno";
		div.appendChild(element);
		panel.appendChild(div);
	}
	
	this.UpdateShippingPromo = function(selectedInput)
	{
		var previousShipping = Order.data.shipping;
		EcomUI.GetShippingAmount();
		var discountAffected = previousShipping != Order.data.shipping;
		for (var p = 0; p < Order.PromoHandlers.length; p++)
			discountAffected = discountAffected || Order.PromoHandlers[p].OnShipping(selectedInput.value); //really not sure this is needed anymore!
			
		if (discountAffected)
		{
			Order.SaveFormContents(function() {
				EcomUI.ShowCheckout();
			});
		}
		else
			EcomUI.ApplyTax();
	}
	
	this.GetCombinedCode = function(groupCode, itemCode)
	{
		if (groupCode != itemCode)
			return groupCode + "|" + itemCode;
		else
			return itemCode;
	}

	this.GetShippingAmount = function()
	{
		var returnValue = -1;
		var shippingOptions = $("#" + EcomUI.Settings.containerNames.shippingPanel + " input");
		for (var i = 0; i < shippingOptions.length; i++)
		{
			if (shippingOptions[i].checked)
			{
				for (var g = 0; g < EcomUI.shippingMethods.length; g++)
				{
					var group = EcomUI.shippingMethods[g].options;
					for (var r = 0; r < group.length; r++)
					{
						if (shippingOptions[i].value == this.GetCombinedCode(EcomUI.shippingMethods[g].code, group[r].code))
						{
							if (group[r].code == "-1")
							{
								$("#" + EcomUI.Settings.containerNames.shippingLabel).hide();
								$("#" + EcomUI.Settings.containerNames.discountLabel).hide();
								$("#" + EcomUI.Settings.containerNames.giftCardLabel).hide();
								$("#" + EcomUI.Settings.containerNames.taxLabel).hide();
								$("#" + EcomUI.Settings.containerNames.totalLabel).hide();
							}
							else
							{
								$("#" + EcomUI.Settings.containerNames.shippingLabel).show();
								$("#" + EcomUI.Settings.containerNames.discountLabel).show();
								$("#" + EcomUI.Settings.containerNames.giftCardLabel).show();
								$("#" + EcomUI.Settings.containerNames.taxLabel).show();
								$("#" + EcomUI.Settings.containerNames.totalLabel).show();
							}
							returnValue = group[r].amount;
							if (window.ecomUserSettings && window.ecomUserSettings.onProcessShipping)
								returnValue = window.ecomUserSettings.onProcessShipping(Order, group[r].amount);
							Order.data.shipping = returnValue;
						}
					}
				}
			}
		}
		return returnValue;
	}
		
	this.ApplyTax = function(BackgroundDataOnly, Callback)
	{
		var subTotalLabel = document.getElementById(EcomUI.Settings.containerNames.subTotalLabel);
		var shippingLabel = document.getElementById(EcomUI.Settings.containerNames.shippingLabel);
		var discountLabel = document.getElementById(EcomUI.Settings.containerNames.discountLabel);
		var giftCardLabel = document.getElementById(EcomUI.Settings.containerNames.giftCardLabel);
		var taxLabel = document.getElementById(EcomUI.Settings.containerNames.taxLabel);
		var totalLabel = document.getElementById(EcomUI.Settings.containerNames.totalLabel);
		var stateControl = document.getElementById(EcomUI.Settings.inputNames.billingAddress.state);
		var countryControl = document.getElementById(EcomUI.Settings.inputNames.billingAddress.country);
		var postalCodeControl = document.getElementById(EcomUI.Settings.inputNames.billingAddress.postalCode);

		var recurringTaxLabel = document.getElementById(EcomUI.Settings.containerNames.recurringTaxLabel);
		var recurringSubTotalLabel = document.getElementById(EcomUI.Settings.containerNames.recurringSubTotalLabel);
		var recurringTotalLabel = document.getElementById(EcomUI.Settings.containerNames.recurringTotalLabel);
		var recurringDescription = document.getElementById(EcomUI.Settings.containerNames.recurringDescription);

		if (BackgroundDataOnly || (subTotalLabel && shippingLabel && taxLabel && totalLabel && stateControl && countryControl && postalCodeControl))
		{
			var pl = new SOAPClientParameters();
			
			var country = Order.data.billingAddress.country;
			var state = Order.data.billingAddress.state;
			var postalCode = Order.data.billingAddress.postalCode;
			if (!BackgroundDataOnly)
			{
				country = countryControl.options[countryControl.selectedIndex].value;
				state = stateControl.options[stateControl.selectedIndex].value;
				postalCode = postalCodeControl.value;
			}
			
			pl.add("Country", country);
			pl.add("State", state);
			pl.add("PostalCode", postalCode);
			pl.add("CultureCode", board_culture);
			SOAPClient.invoke(URL_SOAP_CART, "GetTaxRates", pl, true, function(data) {
				var taxes = eval("(" + data + ")").tax;
				/* Sub total */
				var subtotal = Order.data.totalAmount;
				var discount = Order.data.discount;				
				if (!BackgroundDataOnly)
				{
					subtotal = 0;
					discount = 0;
					
					subtotal = EcomUI.ParseCurrency(subTotalLabel.innerHTML);

					Order.data.totalAmount = subtotal;
				
					/* Shipping */			
					shippingLabel.innerHTML = EcomUI.FormatCurrency(parseFloat(Order.data.shipping));
					
					/* Discount */
					if (discountLabel)
						discount = EcomUI.ParseCurrency(discountLabel.innerHTML);				
									
					Order.data.discount = discount;								
					if (discount > (subtotal + Order.data.discount.recurringAmount)) {
						discount = subtotal + Order.data.discount.recurringAmount;				
					}
					
					Order.data.discount = discount;
					
					if (discountLabel)
					{
						discountLabel.innerHTML = EcomUI.FormatCurrency(Order.data.discount);
					}
				}
				subtotal += parseFloat(Order.data.shipping);
				subtotal = subtotal - discount;

				/* Taxes */
				var labelValue = "";
				var recurringlabelValue = "";
				Order.data.tax.length = 0;
				var totalTax = 0;
				var totalRecurringTax = 0;
				for (var i = 0; i < taxes.length; i++)
				{
					var subtotaltax = 0;					
					var subtotalrecurringtax = 0;					
					var taxGroup = taxes[i].group.split('|');
					var shippingTaxable = false;
										
					for (var t = 0; t < Order.data.items.length; t++)
					{
						for (var c = 0; c < taxGroup.length; c++)
						{							
							var kitsize = Order.data.items[t].kitsize;
							
							if (Order.data.items[t].tax == taxGroup[c])
							{
								var ajustedQty = Order.data.items[t].quantity;
								if (kitsize > 1)								
									ajustedQty = ajustedQty / kitsize;									
									
								subtotaltax += ajustedQty * Order.data.items[t].price;	

 								if (Order.data.items[t].pricerecurring)
 									subtotalrecurringtax += ajustedQty * Order.data.items[t].pricerecurring;	
							}
						}		
					}
					
					for (var c = 0; c < taxGroup.length; c++)
					{							
						if ("1" == taxGroup[c])
							shippingTaxable = true;
					}
					
					if (subtotaltax > (subtotal - parseFloat(Order.data.shipping)))
					{							
						subtotaltax = subtotal - parseFloat(Order.data.shipping);
					}
					
					// Shipping amount always taxable
					if (shippingTaxable)
						subtotaltax += parseFloat(Order.data.shipping);	
									
					if (subtotaltax > 0) {				
						var taxAmount = (subtotaltax * (taxes[i].percentage / 100));
						taxAmount = Math.round(taxAmount * 100) / 100;
						totalTax += taxAmount;
						labelValue += "(" + taxes[i].code + ") " + EcomUI.FormatCurrency(taxAmount) + "\n<br />";					
											
						Order.data.tax[Order.data.tax.length] = {code: taxes[i].code, percentage: taxes[i].percentage, amount: taxAmount};
					}

					if (subtotalrecurringtax > 0) {				
						var recurringtaxAmount = (subtotalrecurringtax * (taxes[i].percentage / 100));
						recurringtaxAmount = Math.round(recurringtaxAmount * 100) / 100;
						totalRecurringTax += recurringtaxAmount;
						recurringlabelValue += "(" + taxes[i].code + ") " + EcomUI.FormatCurrency(recurringtaxAmount) + "\n<br />";				
																																				
						//Order.data.recurringTax[Order.data.tax.length] = {code: taxes[i].code, percentage: taxes[i].percentage, amount: taxAmount};
					}
				}
				
				// Add taxes amount only at the end
				subtotal += totalTax;

				// Add recurring taxes amount
				if (recurringSubTotalLabel) {
					var recurringsubtotal = EcomUI.ParseCurrency(recurringSubTotalLabel.innerHTML);
					recurringsubtotal += totalRecurringTax;				
					Order.data.recurringAmount  = recurringsubtotal;
				}
				else
					Order.data.recurringAmount = 0;


				if (!labelValue)
					Order.data.taxlabel = EcomUI.FormatCurrency(0);
				else
					Order.data.taxlabel = labelValue.replace("\n","").replace("\n","");


				if (!recurringlabelValue)
					Order.data.recurringTaxLabel = EcomUI.FormatCurrency(0);
				else
					Order.data.recurringTaxLabel = recurringlabelValue.replace("\n","").replace("\n","");
									
				// Gift card		
				var giftcard = Order.data.giftcard;							
											
				if (!BackgroundDataOnly)
				{					
					giftcard = 0;
										
					for (var i = 0; i < Order.data.giftCards.length; i++)
					{							
						if (Order.data.giftCards[i].Amount > subtotal) {
											
							Order.data.giftCards[i].Use = subtotal;
						}
						else {
							Order.data.giftCards[i].Use = Order.data.giftCards[i].Amount;
						}		
						subtotal -= parseFloat(Order.data.giftCards[i].Use);					
						giftcard += parseFloat(Order.data.giftCards[i].Use);
					}
														
					Order.data.giftcard = giftcard;	
										
					if (giftCardLabel)
					{
						giftCardLabel.innerHTML = EcomUI.FormatCurrency(Order.data.giftcard);
						EcomUI.GetPaymentMethods();
						Order.SaveCartContents(true);
					}	
					
				}
				EcomUI.UpdateGiftCard();
					
				if (!BackgroundDataOnly)
				{
					if (!labelValue)
						labelValue = EcomUI.FormatCurrency(0);								
					taxLabel.innerHTML = labelValue;

					if (recurringTaxLabel && recurringTotalLabel)
					{
						if (!recurringlabelValue)
							recurringlabelValue = EcomUI.FormatCurrency(0);
						recurringTaxLabel.innerHTML = recurringlabelValue;
						recurringTotalLabel.innerHTML = EcomUI.FormatCurrency(Math.round((recurringsubtotal) * 100) / 100);
					}

					totalLabel.innerHTML = EcomUI.FormatCurrency(Math.round((subtotal) * 100) / 100);
					if (Order.data.PaymentCode == "PAYPAL")
						EcomUI.LoadPrePayment(Order.data.PaymentCode);
					
				}
				else if (Callback)
					Callback();
			});
		}
		else
		{
			throw new Error("Could not find one of the following controls: sub total, shipping, tax or grand total. Check your .Settings");
		}
	}

	/* Loads the checkout screen from a remote template */
	this.ShowAccount = function()
	{
		/* Get client info if logged in. */
		var pl = new SOAPClientParameters();
		pl.add("CultureCode", board_culture);
		SOAPClient.invoke(URL_SOAP_CART, "GetOrderHistory", pl, true, function(data) {
			var history = eval("(" + data + ")");			
			EcomUI.LoadTemplate(EcomUI.Settings.accountTemplate, 'divEcommerce', history);
		});
	}

	/* Loads the checkout screen from a remote template */
	this.ShowConfirmation = function()
	{
		EcomUI.LoadTemplate(EcomUI.Settings.confirmationTemplate, 'divEcommerce', Order.data);
	}

	/* I only want the 2 decimals i gave you, thx.
	http://www.mredkj.com/javascript/nfbasic2.html
	*/
	this.FixFloat = function(Amount)
	{
		Amount *= 100;
		Amount = Math.round(Amount);
		return Amount / 100;
	}

	/* Prints the links container in a "clean" window */
	this.PrintReceipt = function(sender)
	{
		/*
		var html = "<html><head><link rel='stylesheet' type='text/css' href='/modules/Adeo.SpringBoard.Ecommerce/view/ecommerce.css' /></head><body>" + sender.parentNode.innerHTML + "</body></html>";
		var win = window.open();
		win.document.write(html);
		win.document.close(); 
		win.print();
		*/
		window.print();
	}

	/* Prints the links container in a "clean" window */
	this.ExportReceipt = function(sender)
	{
		document.location = "/Modules/Adeo.SpringBoard.Ecommerce/view/ExportAdminContentsPDF.aspx?url=" + encodeURIComponent(sender.href) + "&orderKey=" + $(sender).data("orderkey");
		return false;
	}

	this.OpenLogin = function()
	{
		this.divLoginFormName = "divLoginForm";
		if (!document.getElementById(divLoginForm))
		{
			var divLoginForm = document.createElement("div");
			divLoginForm.id = this.divLoginFormName;
			divLoginForm.title = SBPhrases["CART_LOGIN"];
			document.body.appendChild(divLoginForm);
		}
		EcomUI.LoadTemplate(EcomUI.Settings.loginTemplate, this.divLoginFormName, {});
	}

	this.AfterLogin = function(response) {
		//alert(response.toString() + " : " + true.toString());
		if (response)
		{
			var chkNewLogin = document.getElementById("chkNewLogin");
			if (chkNewLogin)
				chkNewLogin.value = "OFF";
			Order.data.createAccount = "OFF";
			Order.SaveCartContents(true);
			EcomUI.ShowCheckout();
		} 
		else 
		{
			$("#divEcomLoginFailed").show();
		}
	}

	this.AfterLoginAccount = function(response) {
		if (response) {
			//$("#" + EcomUI.divLoginFormName).dialog("close");
			EcomUI.ShowAccount();
			if (EcomUI.Settings.onAfterLoginAccount)
			{
				EcomUI.Settings.onAfterLoginAccount();
			}
		} else {
			document.getElementById("divEcomLoginFailed").style.display = "block";
		}
	}
	
	this.Logout = function()
	{
		Security.UserLogout(function() {
			var chkNewLogin = document.getElementById("chkNewLogin");
			if (chkNewLogin)
				chkNewLogin.value = "ON";
			Order.data.createAccount = "ON";
			Order.SaveCartContents(true);
			EcomUI.ShowCheckout();
		});
	}
	
	this.LogoutAccount = function(Url)
	{
		var Me = this;
		Security.UserLogout(function() {
			if (!Url)
				Url = Me.Settings.homePage;
			document.location = Url;
			
			//EcomUI.ShowAccount();
		});
	}

	this.OpenChangeAccount = function(Sender)
	{
		$(".divEditAccount").dialog({
			modal: true,
			width: 430,
			title: Sender.innerHTML
		});
	}

	this.OpenCheckGiftCardBalance = function(Sender)
	{
		$(".divGiftCardBalance").dialog({
			modal: true,
			width: 400,
			title: Sender.innerHTML
		});
	}

	this.CheckGiftCardBalance = function(Sender)
	{
		var container = Sender.parentNode;
		var cardNumber = $(container).find(".txtGiftCardBalance").val();
		this.GetGiftCardBalance(cardNumber, function(data) {
			$(container).find(".spanGiftCardBalance").text(data.total ? "$" + data.total.toFixed(2) : data.message);
		});
	}

	this.ChangeAccount = function(Sender)
	{
		var container = $(Sender.parentNode);
		
		var email = container.find(".txtEmail").val();
		var password = container.find(".txtPassword").val();
		var passwordConfirm = container.find(".txtPasswordConfirm").val();
		
		this.ClearMessages();				
		if (email && password && passwordConfirm)
		{
			if (password == passwordConfirm)
			{
				/* Get client info if logged in. */
				var Me = this;
				var pl = new SOAPClientParameters();
				pl.add("CultureCode", board_culture);
				pl.add("Username", email);
				pl.add("Password", password);
				SOAPClient.invoke(URL_SOAP_CART, "ModifyAccount", pl, true, function(data) {
					Me.showMessage(data);
					container.dialog('close');
				});
			}
			else
			{
				this.showMessage("Password must match");
			}
		}
		else
		{
			this.showMessage("All fields marked with a star (*) are required");
		}
	}
}

AdeoEcom = {};

///////// PROMO FACTORY  ///////////

AdeoEcom.PromoMaker = function() {};

AdeoEcom.PromoMaker.prototype.CreatePromoHandler = function(Code, Promo)
{
	switch (Code) //sucks!
	{
		case "9": 
		case "1": 
			return new AdeoEcom.PercentOffPromo(Promo);
			break;
		case "11": 
		case "3": 
			return new AdeoEcom.FreeShippingPromo(Promo);
			break;
		case "10": 
		case "2":
			return new AdeoEcom.DollarsOffPromo(Promo);
			break;
		case "12": 
		case "4":
			return new AdeoEcom.FreeWithPurchasePromo(Promo);
			break;
		case "13": 
		case "5":
			return new AdeoEcom.FixedPricingPromo(Promo);
			break;
		default:
			return new AdeoEcom.Promo(Promo);
			break;
	}
}

///////// PROMO HANDLERS  ///////////

AdeoEcom.Promo = function(Promo) { 
	this.Promo = Promo;
};

AdeoEcom.Promo.prototype.IsEligible = function() {
	var isEligible = true;
	
	switch (this.Promo.condition)
	{
		case "6069": //legacy sku
		case "1": // SKU
			var hasItem = false;
			var hasItemAnd;
			var hasItemTest;
			var promosOR = this.Promo.value.split(",");			
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;			
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var sku;		
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						sku = parts[1];
					}
					else
					{
						sku = promosAND[and];
					}
					
					var re = new RegExp(sku);					
					hasItemTest = false;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || ((Order.data.items[i].sku.match(re)) && (Order.data.items[i].quantity >= itemCount));						
					}
					
					hasItemAnd = hasItemAnd && hasItemTest;
				}
				hasItem = hasItem || hasItemAnd;
			}			
			isEligible = hasItem;
			break;
		case "2": // TOTAL
		case "6057": //legacy sku
			var totalAmount = 0;
			for (var i = 0; i < Order.data.items.length; i++) {
				totalAmount += Order.data.items[i].price * Order.data.items[i].quantity;
			}
			isEligible = totalAmount >= parseFloat(this.Promo.value);			
			break;
		case "3": // CATEGORY
			var hasItem = false;
			var hasItemAnd;
			var hasItemTest;
			var promosOR = this.Promo.value.split(",");			
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;			
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var category;
										
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						category = parts[1];
					}
					else
					{
						category = promosAND[and];
					}
					
					hasItemTest = false;
					var itemTotal = 0;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || (Order.data.items[i].category == category && (Order.data.items[i].quantity >= 1));						
						if (Order.data.items[i].category == category)
							itemTotal += parseInt(Order.data.items[i].quantity);
					}					
					hasItemAnd = hasItemAnd && (hasItemTest && (itemTotal >= itemCount)); 					
				}
				hasItem = hasItem || hasItemAnd;
			}
			isEligible = hasItem;
			break;			
		case "4": // PRODUCT
			var hasItem = false;
			var hasItemAnd;
			var hasItemTest;
			var promosOR = this.Promo.value.split(",");			
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;			
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var productKey;
										
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						productKey = parts[1];
					}
					else
					{
						productKey = promosAND[and];
					}					
					hasItemTest = false;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || ((Order.data.items[i].productKey == productKey) && (Order.data.items[i].quantity >= itemCount));						
					}					
					hasItemAnd = hasItemAnd && hasItemTest;
				}
				hasItem = hasItem || hasItemAnd;
			}
			isEligible = hasItem;
			break;
	}
	return isEligible;
};

AdeoEcom.Promo.prototype.IndexOfSku = function(Sku) {
	var itemIndex = -1;
	for (var i = 0; i < Order.data.items.length; i++)
	{
		if (Order.data.items[i].sku == Sku)
			itemIndex = i;
	}
	return itemIndex;
}

AdeoEcom.Promo.prototype.CheckDiscount = function(Discount) {
	if (this.IsEligible())
		return parseFloat(Discount);
	else
		return 0;
}

AdeoEcom.Promo.prototype.OnCartUpdate = function() {};

//Returns true if discount affected
AdeoEcom.Promo.prototype.OnShipping = function(NewCode) {
	return false;
};

AdeoEcom.Promo.prototype.GetDiscountAmount = function(OrderTotal) {
	return 0;
};

AdeoEcom.Promo.prototype.OnRevoke = function() {};


//     /////// PERCENT OFF  ///////////
AdeoEcom.PercentOffPromo = function(Promo) {
	this.constructor(Promo);
};

AdeoEcom.PercentOffPromo.prototype = new AdeoEcom.Promo();

AdeoEcom.PercentOffPromo.prototype.GetDiscountAmount = function(OrderTotal) {
	var totalAmount = OrderTotal;
	
	switch (this.Promo.condition)
	{
		case "6069": //legacy sku
		case "1": // SKU
			var hasItemAnd;
			var hasItemTest;
			var promosOR = this.Promo.value.split(",");	
			totalAmount = 0;		
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;			
				var total = 0;
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var sku;														
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						sku = parts[1];
					}
					else
					{
						sku = promosAND[and];
					}	
					var re = new RegExp(sku);						
					hasItemTest = false;
					var subTotal = 0;
					var matchQty = 0;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || (Order.data.items[i].sku.match(re) && (Order.data.items[i].quantity >= itemCount));						
						if (Order.data.items[i].sku.match(re))
						{
							matchQty += Order.data.items[i].quantity;
							if (!this.Promo.kitSize || (matchQty / this.Promo.kitSize) >= 1)
							{
								var applicableMatchedQty = Math.floor(matchQty / this.Promo.kitSize) * this.Promo.kitSize;
								total += EcomUI.FixFloat(applicableMatchedQty * Order.data.items[i].price);							
								matchQty -= applicableMatchedQty;
							}
						}
					}												
					hasItemAnd = hasItemAnd && hasItemTest;
				}							
				if (hasItemAnd)
					totalAmount += total;
			}
			break;						
		case "3": // CATEGORY		
			var hasItem = false;
			var hasItemAnd;
			var hasItemTest;
			totalAmount = 0;
			var promosOR = this.Promo.value.split(",");			
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;	
				var total = 0;		
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var category;										
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						category = parts[1];
					}
					else
					{
						category = promosAND[and];
					}					
					hasItemTest = false;
					var itemTotal = 0;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || (Order.data.items[i].category == category  && (Order.data.items[i].quantity >= itemCount));						
						if (Order.data.items[i].category == category)
						{
							itemTotal += parseInt(Order.data.items[i].quantity);
							total += Order.data.items[i].quantity * Order.data.items[i].price;
						}
					}					
					hasItemAnd = hasItemAnd && (hasItemTest && (itemTotal >= itemCount)); 					
				}
				if (hasItemAnd)
					totalAmount += total;
			}			
			break;
		case "4": // PRODUCT
		var hasItem = false;
			var hasItemAnd;
			var hasItemTest;
			var promosOR = this.Promo.value.split(",");	
			totalAmount = 0;		
			for (var or = 0; or < promosOR.length; or++)
			{
				var promosAND = promosOR[or].split("&");					
				hasItemAnd = promosAND.length > 0;			
				var total = 0;
				for (var and = 0; and < promosAND.length; and++)
				{
					var parts = promosAND[and].split("*");
					var productKey;														
					var itemCount = 1;
					if (parts.length > 1)
					{
						itemCount = parseInt(parts[0]);
						productKey = parts[1];
					}
					else
					{
						productKey = promosAND[and];
					}										
					hasItemTest = false;
					for (var i = 0; i < Order.data.items.length; i++)
					{
						hasItemTest = hasItemTest || ((Order.data.items[i].productKey == productKey) && (Order.data.items[i].quantity >= itemCount));						
						if (Order.data.items[i].productKey == productKey) {
							total += Order.data.items[i].quantity * Order.data.items[i].price;
						}
					}												
					hasItemAnd = hasItemAnd && hasItemTest;
				}							
				if (hasItemAnd)
					totalAmount += total;
			}
			break;
	}
	return this.CheckDiscount(EcomUI.FixFloat(totalAmount * (parseFloat(this.Promo.amount) / 100)));
};


//     /////// DOLLARS OFF  ///////////
AdeoEcom.DollarsOffPromo = function(Promo) {
	this.constructor(Promo);
};

AdeoEcom.DollarsOffPromo.prototype = new AdeoEcom.Promo();

AdeoEcom.DollarsOffPromo.prototype.GetMatchItems = function() {
	var re = new RegExp(this.Promo.value);						
	hasItemTest = false;
	var matchQty = 0;
	var returnValue = new Array();
	for (var i = 0; i < Order.data.items.length; i++)
	{
		if (Order.data.items[i].sku.match(re))
		{
			matchQty += Order.data.items[i].quantity;
			if (!this.Promo.kitSize || (matchQty / this.Promo.kitSize) >= 1)
			{
				var applicableMatchedQty = Math.floor(matchQty / this.Promo.kitSize);
				matchQty -= applicableMatchedQty * this.Promo.kitSize;
				Order.data.items[i].couponShipping = this.Promo.shipping;
				Order.data.items[i].couponShippingCode = this.Promo.code;
				returnValue[returnValue.length] = {"item": Order.data.items[i], "qty": applicableMatchedQty, "matchQty": applicableMatchedQty * this.Promo.kitSize};
			}
		}
	}
	return returnValue;
}	

AdeoEcom.DollarsOffPromo.prototype.GetMatchCount = function() {
	var returnCount = 0;
	var items = this.GetMatchItems();
	for (var i = 0; i < items.length; i++)
	{
		returnCount += items[i].qty;
	}
	return returnCount;
}

AdeoEcom.DollarsOffPromo.prototype.GetDiscountAmount = function(OrderTotal) {
	var discountAmount = this.CheckDiscount(parseFloat(this.Promo.amount));
	if (this.Promo.condition == "1" || this.Promo.condition == "6069") //sku based (+ legacy).
		discountAmount = discountAmount * this.GetMatchCount();	
	return discountAmount;
};


//     /////// FREE SHIPPING  ///////////
AdeoEcom.FreeShippingPromo = function(Promo) {
	this.constructor(Promo);
};

AdeoEcom.FreeShippingPromo.prototype = new AdeoEcom.Promo();

AdeoEcom.FreeShippingPromo.prototype.GetDiscountAmount = function(OrderTotal) {

	return this.CheckDiscount(Order.data.shipping);
};


//     /////// FREE SHIPPING  ///////////
AdeoEcom.FreeWithPurchasePromo = function(Promo) {
	this.constructor(Promo);
};

AdeoEcom.FreeWithPurchasePromo.prototype = new AdeoEcom.Promo();

AdeoEcom.FreeWithPurchasePromo.prototype.OnCartUpdate = function() {
	var freebieIndex = this.IndexOfSku(this.Promo.code);
	var needsSaving = false;
	if (this.IsEligible() && (freebieIndex < 0)) //add freebie
	{
		Order.data.items[Order.data.items.length] = {"productKey":-1,"sku":this.Promo.code,"description":this.Promo.description,"quantity":"1","price":this.Promo.amount,kitsize: 1,tax: 1,sortOrder: (Order.data.items.length + 1)};
		needsSaving = true;
	}
	else if (!this.IsEligible() && (freebieIndex >= 0)) //remove freebit
	{
		Order.data.items.splice(freebieIndex, 1);
		needsSaving = true;
	}
	else if ((freebieIndex >= 0) && (Order.data.items[freebieIndex].quantity != 1)) //nice try, but don't get greedy.
	{
		Order.data.items[freebieIndex].quantity = 1;
	}
	if (needsSaving)
		Order.SaveCartContents(true);
};

AdeoEcom.FreeWithPurchasePromo.prototype.GetDiscountAmount = function(OrderTotal) {
	return this.CheckDiscount(0);
};

AdeoEcom.FreeWithPurchasePromo.prototype.OnRevoke = function() {
	var freebieIndex = this.IndexOfSku(this.Promo.code);
	if (freebieIndex >= 0) //zoink!
		Order.data.items.splice(freebieIndex, 1);
};



//     /////// FIXED PRICING  ///////////
AdeoEcom.FixedPricingPromo = function(Promo) {
	this.constructor(Promo);
};

AdeoEcom.FixedPricingPromo.prototype = new AdeoEcom.DollarsOffPromo();

AdeoEcom.FixedPricingPromo.prototype.GetDiscountAmount = function(OrderTotal) {
	var items = this.GetMatchItems();
	var totalDiscountAmount = 0;
	for (var i = 0; i < items.length; i++)
	{

		/*
		whatever this is suposed to fix... don't do it! It breaks in at least the following scenario:
		promo with kit size 2. fixed priced promo with kit size 1...
		order a promo and apply discount... discount way too big
		var promoKitSize = parseInt(this.Promo.kitSize);
		var realAmount = items[i].qty * promoKitSize * items[i].item.price;
		discountAmount = items[i].qty * this.Promo.amount;
		totalDiscountAmount += Math.max(realAmount - discountAmount, 0);
		*/
		
		/*
		var promoKitSize = parseInt(this.Promo.kitSize);
		var itemKitSize = parseInt(items[i].item.kitsize);
		var realAmount = (items[i].qty / itemKitSize) * items[i].item.price;
		var discountAmount = (items[i].qty / promoKitSize) * this.Promo.amount;
		totalDiscountAmount += Math.max(realAmount - discountAmount, 0);
		*/

		var promoKitSize = parseInt(this.Promo.kitSize);
		var itemKitSize = parseInt(items[i].item.kitsize);
		var realAmount = (items[i].matchQty / itemKitSize) * items[i].item.price;			
		var discountAmount = (items[i].matchQty / promoKitSize) * this.Promo.amount;
		totalDiscountAmount += Math.max(realAmount - discountAmount, 0);
		
	}
	return totalDiscountAmount;
};



AdeoEcom.FreeWithPurchasePromo.prototype.OnRevoke = function() {
	var freebieIndex = this.IndexOfSku(this.Promo.code);
	if (freebieIndex >= 0) //zoink!
		Order.data.items.splice(freebieIndex, 1);
};






//var EcomServer = new AdeoServer();
var URL_SOAP_CART = "/modules/Adeo.SpringBoard.Ecommerce/model/Ecommerce.asmx";
var PromoFactory = new AdeoEcom.PromoMaker();
var EcomUI = new AdeoUI(window.ecomUserSettings);
var Order = new AdeoOrder(window.orderUserSettings);
/*
$(document).ready(function() {
	EcomUI.CartUpdateHandler();
 });
 */;
