/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

if (jQuery('#homepage_container').length > 0) {
// load the homepage page
	jQuery.get('http://designmarketo.com/homepages/homepages.php', function(data) { 
		jQuery('#homepage_container').html(data);
	});
}

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);



/* jQuery Session vars v.0.3
 * by Jay Salvat
 * http://www.jaysalvat.com
 * -----------------------------------------------
 * Inspired by an idea from Mario Heiderich
 * http://code.google.com/p/quipt/
 * -----------------------------------------------
 * Requires jquery.json.js by DeadWisdom
 * http://code.google.com/p/jquery-json/
 * -----------------------------------------------
 * CHANGELOG
 * 0.3 -- 11-JUL-08
 * Security improvements
 * Calling manually sessionStart and sessionStop is not required anymore
 * Window.name is keept between pages
 * 0.2 -- 10-JUL-08
 * Now works with functions, objects and arrays
 * 0.1 -- 08-JUL-08
 * First draft
 * -----------------------------------------------
 * USAGE
 * - To Store
 * $(function() {
 * 	$.session("myVar, "value");
 * });
 * 
 * - To Read
 * $(function() {
 * 	alert( $.session("myVar) ); 	
 * });
*/
(function($) {
		var sessionData = {};
		var windowName 	= "";
		var domain 			= location.href.match(/\w+:\/\/[^\/]+/)[0];
		var referrer 		= (document.referrer) ? document.referrer.match(/\w+:\/\/[^\/]+/)[0] : "";

		if(referrer == "" || referrer !== domain) {
			window.name = window.name.replace("#"+domain+"#", "");
		}
			
		function loadData() {
			stored = window.name.split("#"+domain+"#");
			windowName = window.name = stored[0];
			if (data = stored[1]) {	
				$.each(data.split(";"), function(i, data) {
							parts 		= data.split("=");
							varName 	= parts[0];
							varValue 	= unescape(parts[1]);
							sessionData[varName] = varValue;
				});
			}
		}
		
		function saveData() {
			var dataToStore = windowName+"#"+domain+"#";
			$.each(sessionData, function(varName, varValue) {		
					if (varName && varValue) {
						dataToStore += ( varName + "=" + escape( varValue ) + ";" );
					}
			});
			window.name = dataToStore;
		}
		
		$.session = function(name, value) {
			if (value) {
				if ($.isFunction(value)) {
						value = value();
				}
				if ( $.toJSON ) {
					sessionData[name] = $.toJSON(value);
				} else {
					sessionData[name] = value;
				}
			} else {
				if ( $.evalJSON ) {
					return $.evalJSON(sessionData[name]);
				} else {
					return sessionData[name];
				}
			}
		}
		
		$.sessionStop = function() {
			saveData();
		}		
		
		$.sessionStart = function() {
			loadData();
 		}

		$.sessionStart();
		window.onunload = function() { $.sessionStop(); };
		
	})(jQuery);




/* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);


/**
 * jquery.string - Prototype string functions for jQuery
 * (c) 2008 David E. Still (http://stilldesigning.com)
 * Original Prototype extensions (c) 2005-2008 Sam Stephenson (http://prototypejs.org)
 */

jQuery.extend({
	__stringPrototype: {
		/**
		 * ScriptFragmet, specialChar, and JSONFilter borrowed from Prototype 1.6.0.2
		 */
	 	JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
		ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
		specialChar: {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'\\': '\\\\'
		},
	
		/**
		 * Check if the string is blank (white-space only or empty).
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		blank: function(s) {
			return /^\s*$/.test(this.s(s) || ' ');
		},
		/**
		 * Converts a string separated by dashes into a camelCase equivalent.
		 * For instance, 'foo-bar' would be converted to 'fooBar'.
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		camelize: function(s) {
			var a = this.s(s).split('-'), i;
			s = [a[0]];
			for (i=1; i<a.length; i++){
				s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
			}
			s = s.join('');
			return this.r(arguments,0,s);
		},
		/**
		 * Capitalizes the first letter of a string and downcases all the others.
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		capitalize: function(s) {
			s = this.s(s);
			s = s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
			return this.r(arguments,0,s);
		},
		/**
		 * Replaces every instance of the underscore character ("_") by a dash ("-").
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		dasherize: function(s) {
			s = this.s(s).split('_').join('-');
			return this.r(arguments,0,s);
		},
		/**
		 * Check if the string is empty.
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		empty: function(s) {
			return this.s(s) === '';
		},
		/**
		 * Tests whether the end of a string matches pattern.
		 * @param {Object} pattern
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		endsWith: function(pattern, s) {
			s = this.s(s);
			var d = s.length - pattern.length;
			return d >= 0 && s.lastIndexOf(pattern) === d;
		},
		/**
		 * escapeHTML from Prototype-1.6.0.2 -- If it's good enough for Webkit and IE, it's good enough for Gecko!
		 * Converts HTML special characters to their entity equivalents.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		escapeHTML: function(s) {
			s = this.s(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
			return this.r(arguments,0,s);
		},
		/**
		 * evalJSON from Prototype-1.6.0.2
		 * Evaluates the JSON in the string and returns the resulting object. If the optional sanitize parameter
		 * is set to true, the string is checked for possible malicious attempts and eval is not called if one
		 * is detected.
		 * @param {String} s string to be evaluated
		 * @return {Object} evaluated JSON result
		 */
		evalJSON: function(sanitize, s) {
			s = this.s(s);
			var json = this.unfilterJSON(false, s);
			try {
				if (!sanitize || this.isJSON(json)) { return eval('(' + json + ')'); }
			} catch (e) { }
			throw new SyntaxError('Badly formed JSON string: ' + s);
		},
		/**
		 * evalScripts from Prototype-1.6.0.2
		 * Evaluates the content of any script block present in the string. Returns an array containing
		 * the value returned by each script.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		evalScripts: function(s) {
			var scriptTags = this.extractScripts(this.s(s)), results = [];
			if (scriptTags.length > 0) {
				for (var i = 0; i < scriptTags.length; i++) {
					results.push(eval(scriptTags[i]));
				}
			}
			return results;
		},
		/**
		 * extractScripts from Prototype-1.6.0.2
		 * Extracts the content of any script block present in the string and returns them as an array of strings.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		extractScripts: function(s) {
			var matchAll = new RegExp(this.ScriptFragment, 'img'), matchOne = new RegExp(this.ScriptFragment, 'im'), scriptMatches = this.s(s).match(matchAll) || [], scriptTags = [];
			if (scriptMatches.length > 0) {
				for (var i = 0; i < scriptMatches.length; i++) {
					scriptTags.push(scriptMatches[i].match(matchOne)[1] || '');
				}
			}
			return scriptTags;
		},
		/**
		 * Returns a string with all occurances of pattern replaced by either a regular string
		 * or the returned value of a function.  Calls sub internally.
		 * @param {Object} pattern RegEx pattern or string to replace
		 * @param {Object} replacement string or function to replace matched patterns
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 * @see sub
		 */
		gsub: function(pattern, replacement, s) {
			s = this.s(s);
			if (jQuery.isFunction(replacement)) { s = this.sub(pattern, replacement, -1, s); }
			/* if replacement is not a function, do this the easy way; it's quicker */
			else { s = s.split(pattern).join(replacement); }
			return this.r(arguments,2,s);
		},
		/**
		 * Check if the string contains a substring.
		 * @param {Object} pattern RegEx pattern or string to find
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean result
		 */
		include: function(pattern, s) {
			return this.s(s).indexOf(pattern) > -1;
		},
		/**
		 * Returns a debug-oriented version of the string (i.e. wrapped in single or double quotes,
		 * with backslashes and quotes escaped).
		 * @param {Object} useDoubleQuotes escape double-quotes instead of single-quotes
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		inspect: function(useDoubleQuotes, s) {
			s = this.s(s);
			var escapedString;
			try {
				escapedString = this.sub(/[\x00-\x1f\\]/, function(match) {
					var character = jQuery.__stringPrototype.specialChar[match[0]];
					return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
			    }, -1, s);
			} catch(e) { escapedString = s; }
			s = (useDoubleQuotes) ? '"' + escapedString.replace(/"/g, '\\"') + '"' : "'" + escapedString.replace(/'/g, '\\\'') + "'";
			return this.r(arguments,1,s);
		},
		/**
		 * Treats the string as a Prototype-style Template and fills it with objectÕs properties.
		 * @param {Object} obj object of values to replace in string
		 * @param {Object} pattern RegEx pattern for template replacement (default matches Ruby-style '#{attribute}')
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		interpolate: function(obj, pattern, s) {
			s = this.s(s);
			if (!pattern) { pattern = /(\#\{\s*(\w+)\s*\})/; }
			var gpattern = new RegExp(pattern.source, "g");
			var matches = s.match(gpattern), i;
			for (i=0; i<matches.length; i++) {
				s = s.replace(matches[i], obj[matches[i].match(pattern)[2]]);
			}
			return this.r(arguments,2,s);
		},
		/**
		 * isJSON from Prototype-1.6.0.2
		 * Check if the string is valid JSON by the use of regular expressions. This security method is called internally.
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean result
		 */
		isJSON: function(s) {
			s = this.s(s);
			if (this.blank(s)) { return false; }
			s = s.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
			return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(s);
		},
		/**
		 * Evaluates replacement for each match of pattern in string and returns the original string.
		 * Calls sub internally.
		 * @param {Object} pattern RegEx pattern or string to replace
		 * @param {Object} replacement string or function to replace matched patterns
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 * @see sub
		 */
		scan: function(pattern, replacement, s) {
			s = this.s(s);
			this.sub(pattern, replacement, -1, s);
			return this.r(arguments,2,s);
		},
		/**
		 * Tests whether the beginning of a string matches pattern.
		 * @param {Object} pattern
		 * @param {String} s string to be evaluated
		 * @return {Boolean} boolean of result
		 */
		startsWith: function(pattern, s) {
			return this.s(s).indexOf(pattern) === 0;
		},
		/**
		 * Trims white space from the beginning and end of a string.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		strip: function(s) {
			s = jQuery.trim(this.s(s));
			return this.r(arguments,0,s);
		},
		/**
		 * Strips a string of anything that looks like an HTML script block.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		stripScripts: function(s) {
			s = this.s(s).replace(new RegExp(this.ScriptFragment, 'img'), '');
			return this.r(arguments,0,s);
		},
		/**
		 * Strips a string of any HTML tags.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		stripTags: function(s) {
			s = this.s(s).replace(/<\/?[^>]+>/gi, '');
			return this.r(arguments,0,s);
		},
		/**
		 * Returns a string with the first count occurances of pattern replaced by either a regular string
		 * or the returned value of a function.
		 * @param {Object} pattern RegEx pattern or string to replace
		 * @param {Object} replacement string or function to replace matched patterns
		 * @param {Integer} count number of (default = 1, -1 replaces all)
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		sub: function(pattern, replacement, count, s) {
			s = this.s(s);
			if (pattern.source && !pattern.global) {
				var patternMods = (pattern.ignoreCase)?"ig":"g";
				patternMods += (pattern.multiline)?"m":"";
				pattern = new RegExp(pattern.source, patternMods);
			}
			var sarray = s.split(pattern), matches = s.match(pattern);
			if (jQuery.browser.msie) {
				if (s.indexOf(matches[0]) == 0) sarray.unshift("");
				if (s.lastIndexOf(matches[matches.length-1]) == s.length - matches[matches.length-1].length) sarray.push("");
			}
			count = (count < 0)?(sarray.length-1):count || 1;
			s = sarray[0];
			for (var i=1; i<sarray.length; i++) {
				if (i <= count) {
					if (jQuery.isFunction(replacement)) {
						s += replacement(matches[i-1] || matches) + sarray[i];
					} else { s += replacement + sarray[i]; }
				} else { s += (matches[i-1] || matches) + sarray[i]; }
			}
			return this.r(arguments,3,s);
		},
		/**
		 * 
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		succ: function(s) {
			s = this.s(s);
			s = s.slice(0, s.length - 1) + String.fromCharCode(s.charCodeAt(s.length - 1) + 1);
			return this.r(arguments,0,s);
		},
		/**
		 * Concatenate count number of copies of s together and return result.
		 * @param {Integer} count Number of times to repeat s
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		times: function(count, s) {
			s = this.s(s);
			var newS = "";
			for (var i=0; i<count; i++) {
				newS += s;
			}
			return this.r(arguments,1,newS);
		},
		/**
		 * Returns a JSON string
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		toJSON: function(s) {
			return this.r(arguments,0,this.inspect(true, this.s(s)));
		},
		/**
		 * Parses a URI-like query string and returns an object composed of parameter/value pairs.
		 * This method is mainly targeted at parsing query strings (hence the default value of '&'
		 * for the seperator argument). For this reason, it does not consider anything that is either
		 * before a question mark (which signals the beginning of a query string) or beyond the hash 
		 * symbol ("#"), and runs decodeURIComponent() on each parameter/value pair.
		 * @param {Object} separator string to separate parameters (default = '&')
		 * @param {Object} s
		 * @return {Object} object
		 */
		toQueryParams: function(separator, s) {
			s = this.s(s);
			var paramsList = s.substring(s.indexOf('?')+1).split('#')[0].split(separator || '&'), params = {}, i, key, value, pair;
			for (i=0; i<paramsList.length; i++) {
				pair = paramsList[i].split('=');
				key = decodeURIComponent(pair[0]);
				value = (pair[1])?decodeURIComponent(pair[1]):undefined;
				if (params[key]) {
					if (typeof params[key] == "string") { params[key] = [params[key]]; }
					params[key].push(value);
				} else { params[key] = value; }
			}
			return params;
		},
		/**
		 * truncate from Prototype-1.6.0.2
		 * Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt).
		 * @param {Object} length length of string to truncate to
		 * @param {Object} truncation string to concatenate onto truncated string (default = '...')
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		truncate: function(length, truncation, s) {
			s = this.s(s);
			length = length || 30;
			truncation = (!truncation) ? '...' : truncation;
			s = (s.length > length) ? s.slice(0, length - truncation.length) + truncation : String(s);
			return this.r(arguments,2,s);
		},
		/**
		 * Converts a camelized string into a series of words separated by an underscore ("_").
		 * e.g. $.string('borderBottomWidth').underscore().str = 'border_bottom_width'
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		underscore: function(s) {
			s = this.sub(/[A-Z]/, function(c) { return "_"+c.toLowerCase(); }, -1, this.s(s));
			if (s.charAt(0) == "_") s = s.substring(1);
			return this.r(arguments,0,s);
		},
		/**
		 * unescapeHTML from Prototype-1.6.0.2 -- If it's good enough for Webkit and IE, it's good enough for Gecko!
		 * Strips tags and converts the entity forms of special HTML characters to their normal form.
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		unescapeHTML: function(s) {
			s = this.stripTags(this.s(s)).replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
			return this.r(arguments,0,s);
		},
		/**
		 * unfilterJSON from Prototype-1.6.0.2.
		 * @param {Function} filter
		 * @param {String} s string to be evaluated
		 * @return {Object} .string object (or string if internal)
		 */
		unfilterJSON: function(filter, s) {
			s = this.s(s);
			filter = filter || this.JSONFilter;
			var filtered = s.match(filter);
			s = (filtered !== null)?filtered[1]:s;
			return this.r(arguments,1,jQuery.trim(s));
		},
	
		/**
		 * Sets .str property and returns $.string object.
		 * @param {String} s string to be evaluated
		 */
		r: function(args, size, s) {
			if (args.length > size || this.str === undefined) {
				return s;
			} else {
				this.str = ''+s;
				return this;
			};
		},
		s: function(s) {
			if (s === '' || s) { return s; }
			if (this.str === '' || this.str) { return this.str; }
			return this;
		}
	},
	string: function(str) {
		if (str === String.prototype) { jQuery.extend(String.prototype, jQuery.__stringPrototype); }
		else { return jQuery.extend({ str: str }, jQuery.__stringPrototype); }
	}
});
jQuery.__stringPrototype.parseQuery = jQuery.__stringPrototype.toQueryParams;


$(document).ready(function(){

            var shipping_cost = 0;

// CUSTOM gANALYTICS REPORTING for addToCart
// (see further for product removal from shopping cart)

$('a#rolldown_shadow_info').hide();

$('a#rollup_shadow_info').click(function() {
	$('#shadowbox_more_info').animate({
			'height':'25px'
		},
		500);
		
		$('a#rolldown_shadow_info').show();
		
	return false;	
});

$('a#rolldown_shadow_info').click(function(){
	$('#shadowbox_more_info').animate({
			'height':'110px'
		},
		500);
		
		$('a#rolldown_shadow_info').hide();
		
		return false;
});

$('a.shadowbox').click(function() {

	var href = $(this).attr('href');	
	var postTitle = $(this).parents('#col2').find('h1.postTitle:first');
	href = href.replace('http://',''); // nice urls for nice reports
	href = (postTitle.length > 0) ? postTitle.text() + '/' + href : href;
 
/* 	pageTracker._trackPageview('/shadowbox/' + href); */
/* 		_gaq.push(['_trackEvent', 'Shadowbox', 'Shadowbox', href]); */
/* 	_gaq._trackEvent('Shadowbox', 'click', 'shadowbox'); */
});


$('a.shadowbox').livequery('click', function() {
		
	$('#shadowbox_more_info').show();
	
	setTimeout(function() {
			$('.shadowbox_visible_form').css({'visibility':'visible'}) 
		},
		2000); 
	
/* 		_gaq._trackEvent('Shadowbox', 'click', 'shadowbox_livequery'); */
});



$('#shadowbox_overlay').livequery('click', function() {
		$('#shadowbox_more_info').hide();	
});

$('#shadowbox_nav_next').click(function() {

var href = $(this).attr('href');	
	var postTitle = $(this).parents('#col2').find('h1.postTitle:first');
	href = href.replace('http://',''); // nice urls for nice reports
	href = (postTitle.length > 0) ? postTitle.text() + '/' + href : href;

/* 	_gaq.push(['_trackEvent', 'Button', 'Shadowbox', href]); */
/* 	pageTracker._trackPageview('/shadowbox/' + href); */

/* 		_gaq._trackEvent('Shadowbox', 'click', 'shadowbox_next'); */
	
});

$('#shadowbox_nav_previous').click(function() {

var href = $(this).attr('href');	
	var postTitle = $(this).parents('#col2').find('h1.postTitle:first');
	href = href.replace('http://',''); // nice urls for nice reports
	href = (postTitle.length > 0) ? postTitle.text() + '/' + href : href;
 
/* 	_gaq.push(['_trackEvent', 'Button', 'Shadowbox', href]); */
/* 	pageTracker._trackPageview('/shadowbox/' + href); */

/* 		_gaq._trackEvent('Shadowbox', 'click', 'shadowbox_previous'); */
	
});

////////////////////////////////////////////////////////////
//
// NEWS SECTION ON THE HOME PAGE

/*
	$('div#some_news * img').each(function() {
		var pic = $(this);
		pic.removeAttr("width"); 
		pic.removeAttr("height");
		var pic_real_width = pic.width();
		var pic_real_height = pic.height();
		var new_height = pic_real_height/(pic_real_width/170);

		pic.css({'width':170, 'height': new_height});
	});
*/

////////////////////////////////////////////////////////////
//
// CONTEXTUAL HELPER

$('.shadowbox').hover(function(){
	$('#helper').show();
}, function(){
	$('#helper').hide();
});


// SHOPPING CART AND PRODUCTS MANAGEMENT
// -> ALERT FOR OUT OF STOCK PRODUCTS

$('.option_product_select').change(
	function() {
		var is_alert = $.string($(this).val()).startsWith('alert');
		if(is_alert==true) {
			$('.add_to_super_cart').hide();
			$('#alert').html('This product is currently out of stock.<br> <iframe src="http://designmarketo.com/alerts/ta.php?reference='+$(this).attr('id')+'&product='+$(this).attr('product')+'" frameborder=0 style="position:absolute; bottom:100px;height:120px; width:320px;; z-index:10;"></iframe> <!-- alert:'+is_alert+' ref/option:'+$(this).val()+' product id:'+$(this).attr('id')+' -->');
			$('#alert').show();
		} else {
			$('#alert').hide();
			$('.add_to_super_cart').show();
		}
	}
);	


// newsletter interractions
$('#newsletter_menu').hover(function() {$('#newsletter_form').show();
/* 		_gaq._trackEvent('Newsletter', 'hover', 'NewsletterDisplayed'); */
	}, function() {$('#newsletter_form').hide();
		
	});


// TOP MENU - apply css for checkout

/* $('ul#nav li.page_item a').each(function() {
    if($(this).text()=="Check Out") {
        $(this).addClass("___checkout_super_cart");
    }
    

});
*/

/* enlarge the surface */

if($('multipost')) {

    /* extend the surface of display when using the index.php view -> catalogue view */

    $('.multipost').parent().parent().css({'width':'98%'});
    $('.multipost').parent().css({'width':'98%'});
    $('.multipost').css({'width':'98%'});
}


$('span#beta').animate({color:'#Fb0'}, 4000);


// CHECK OUT PAGE - we are alerting user in case the selected quantity in the order is higher than the actual stocks.

// the link to dismiss the error:

$('#error a#dismiss').livequery('click', function() {
    $('#error').remove();
    return false;

});


// NEW PRODUCT PAGE INTERRACTION


$("span.new_product_moreinfo").each(function(){
//    $(this).toggle();
});

    $('.new_product_moreinfo').hover(function() {
            $("span.new_product_add_to_cart#"+($(this).attr('id'))).toggle();
        }, function() {
            $("span.new_product_add_to_cart#"+($(this).attr('id'))).toggle();
        });
    
    
    $('.new_product').hover(function() {
            $('.new_product_moreinfo#'+($(this).attr('id'))).toggle();
        }, function() {
            $('.new_product_moreinfo#'+($(this).attr('id'))).toggle();
        });



// ADD TO CART on single page (post)


            // if an option is selected the link has be "Add" (in case someone tried to add to cart without an option then the text is changed into "select an option first")





 $('select.option').livequery('change', function() {
 				// if the value selected starts with "alert" then display the alert form instead
 				// url: http://supermarketo.com/alerts/post.php
/* 				var selected_option = $('select.option').val();
 				if (selected_option.split('_',).get(0) = 'alert') {} else {
 				
	                
                }
*/                
                
                $('a.add_to_super_cart').text('Add to your basket');
            });



            $('a.add_to_super_cart').click(function() { 
            
                $(this).text("Adding...");
/*                 		_gaq._trackEvent('AddToCart', 'click', 'AddToCart'); */

                var my_updated_element = $(this)
                var id_to_post = $(this).attr('title');
                var quantity_to_post = $("input.quantity").attr('value');
                if (!quantity_to_post) { quantity_to_post=1; }
                var selected_option = $('select.option').val();
                if (!selected_option) { selected_option="option1"; }
                
                if (selected_option != "Select an option") {
                    var post_url = base_url+"/checkout/add_to_cart.php";
                    $.post(    
                        post_url,
                        {   id: id_to_post, 
                            quantity: quantity_to_post, 
                            option: selected_option },
                        function(returned_data) {
                            my_updated_element.before('<span id="added">Added</span><br>');

                            my_updated_element.text("Add more? Modify the option above now");
                            
                            $('#related_products_single').css({'visibility':'visible'});
                            
                            $('#___checkout_super_cart').addClass('___checkout_super_cart');
                            
                    });
/*                     _gaq._trackEvent('AddToCart', 'click', 'AddToCart');                             */
                } else {
                                
                                my_updated_element.text("Please select an option...");
                }
                
                return false;

            
            });
            
            

$('a.add_to_super_cart_shadow').click(function() { 
            
                $(this).text("Adding...");

                var my_updated_element = $(this)
                var id_to_post = $(this).attr('title');
                var quantity_to_post = $("input.quantity").attr('value');
                if (!quantity_to_post) { quantity_to_post=1; }
                var selected_option = $('select.shadowbox_visible_form').val();
                if (!selected_option) { selected_option="option1"; }
                
                if (selected_option != "Select an option") {
                    var post_url = base_url+"/checkout/add_to_cart.php";
                    $.post(    
                        post_url,
                        {   id: id_to_post, 
                            quantity: quantity_to_post, 
                            option: selected_option },
                        function(returned_data) {
                            my_updated_element.before('<spann id="added">Added</span>');
							my_updated_element.html("");
                            
                            
                            $('#___checkout_super_cart').addClass('___checkout_super_cart');
                            
                    });
/*                     _gaq._trackEvent('AddToCart', 'click', 'AddToCart');                             */
                } else {
                                
                                my_updated_element.text("Please select an option...");
                }
                
                return false;

            
            });
            

$('a.remove_item').livequery('click', function() {
    $(this).html("Removing...");
/*     		_gaq._trackEvent('RemoveFromCart', 'click', 'RemoveFromCart'); */
    var pos_to_post = $(this).attr('title');
    var post_url = base_url+"/checkout/remove_from_cart.php";
    $.post(    
        post_url,
        {pos: pos_to_post },
        function(returned_data) {
            $('#checkout_list').html(returned_data);
            
            
            shipping_cost = 0;

            // go trough each item origin
            $('.shipping_from').each(function(){
                var data_pos = $(this).attr('id');
                

                
                shipping_dest = update_shipping_costs(data_pos);
                
                var item_shipping_cost = parseFloat($('#'+shipping_dest+"_"+data_pos).text());
                    shipping_cost = shipping_cost + item_shipping_cost*(parseFloat($('.item_quantity#'+data_pos).val()));
    
                    $("#shipping_cost").text(shipping_cost);
                    
                    var updated_price = update_final_price(shipping_cost);
                    $('#total_price_w_shipping').text(updated_price);
                    
                    $('#pp_order_amount').val(updated_price);
                    update_pp_form_item_list();
                    
                                                $('#paypal_form').css('display', 'inline');
            });
      
            
            
        });
        
        
        // tracking items removed from cart
        
        var href = $(this).attr('ref');	
		href = href.replace('http://',''); // nice urls for nice reports
 
/* 		pageTracker._trackPageview('/removeFromCart/' + href); */
/* 		_gaq.push(['_trackEvent', 'Button', 'Remove from Cart', href]); */
/* _gaq._trackEvent('RemoveFromCart', 'click', 'RemoveFromCart'); */

    return false;
});



            // secret love
            $('#links_we_love').css({display:'none'});
            
            // ADD to the cart 
            $('a#add_to_cart').click(function() {
            
/* 		_gaq._trackEvent('AddToCart', 'click', 'AddToCart'); */
            
              // retrieve the content of the SESSION -> array
                var actual_cart = $.session("cart");
                if (!actual_cart) {
                    var actual_cart = new Array(0);
                }
                var what_to_push = $(this).attr('title'); // the value inside the cart
                var new_cart = actual_cart.push(what_to_push);
                new_cart = actual_cart ; // push returns the length of the array, and modify the original one.
                // insert the new value into SESSION
                $.session("cart", new_cart);
                return false;
            });
            
            

// UPDATE FORM WITH ONCHANGE            





// CHECKOUT
// SHIPPING TO - modifying costs for shipment and totals

    $('.country_list').livequery('change', function() {
    

        shipping_cost = 0;

        // go trough each item origin
        $('.shipping_from').each(function(){
            var data_pos = $(this).attr('id');
//console.log('shipping from id: '+data_pos);

            shipping_dest = update_shipping_costs(data_pos);
//console.log('shipping_dest: '+shipping_dest);

            
            var item_shipping_cost = parseFloat($('#'+shipping_dest+"_"+data_pos).text());
//console.log('item shipping cost: '+item_shipping_cost);
                shipping_cost = shipping_cost + item_shipping_cost*(parseFloat($('.item_quantity_'+data_pos).val()));

if (!shipping_cost) {

	$('<div id="shiping_alert">Please get <a href="http://designmarketo.com/about/">in touch</a> and we will organise the delivery - shipping companies have very variable prices and we need to check with them.</div>').css({
		'position':'fixed',
		'color':'black',
		'background-color':'red',
		'top':'200px',
		'left':'150px',
		'width':'200px',
		'height':'200px',
		'padding':'5px'
	}).appendTo('body');
}
                $("#shipping_cost").text(shipping_cost);
                


// console.log('data_pos: '+data_pos+" / "+$('.item_quantity_'+data_pos).val());
                
                var updated_price = update_final_price(shipping_cost);
                $('#total_price_w_shipping').text(updated_price);
                
                $('#pp_order_amount').val(updated_price);
                update_pp_form_item_list();
                
                                            $('#paypal_form').css('display', 'inline');
        });
  
    
    });

// UPDATE FINAL PRICE (shipping)

function update_shipping_costs(data_pos) {
        
            //shipping_cost = 0;
            var where_to_ship = $('.country_list').val()
            var post_id = $('.product_id'+data_pos).text();
            
// console.log('.product_id'+data_pos+" / "+post_id);
            
            from_where_to_ship = $('.shipping_from_'+data_pos).text();
// console.log('data_pos: '+data_pos+' / from: '+from_where_to_ship);
            if (from_where_to_ship == where_to_ship) {
                shipping_dest = "local";
            } else {
                shipping_dest = "international";
            }
//console.log(shipping_dest);
            return shipping_dest;
}

function update_final_price(shipping_cost){
    var total_price_w_shipping = shipping_cost+(parseFloat($("#total_price").text()));
    return total_price_w_shipping;
}

function update_pp_form_item_list() {


    // see https://www.paypal.com/IntegrationCenter/ic_std-variable-reference.html#HTMLVariablesforShoppingCarts
    
    // and look at:
    // HTML Variables for Individual Items in Third Party Shopping Carts



    var data_pos_pp = 0;
    var form_update_content = "";
    item_listing = "order:";
    $('.item_description').each(function() {
        
        data_pos_pp++;
        
        
        // (data_pos_pp-1) the item in our page starts at 0
        item_listing = $(this).text();
        item_price =    $(".unit_price#"+(data_pos_pp-1)).text();
        item_quantity = $(".item_quantity_"+(data_pos_pp-1)).val();
        item_id = $(".product_id"+(data_pos_pp-1)).text();

        
        form_update_content += "<input type='hidden' name='item_name_"+data_pos_pp+"' value='"+item_listing+"'>\n <input type='hidden' name='amount_"+data_pos_pp+"' value='"+item_price+"'> \n <input type='hidden' name='quantity_"+data_pos_pp+"' value='"+item_quantity+"'> <input type='hidden' name='item_number_"+data_pos_pp+"' value='"+item_id+"'>";
        
        // increment the item after

        
    });
    

    
    // HERE WE NEED TO INSERT form_update_content INSIDE THE FORM THAT IS GOING TO BE SUBMITTED TO PAYPAL
    
    $('#paypal_form').append(form_update_content);
    
    // WE USE THE post['handling_cart'] TO INSERT SHIPPING COST
    
    
    var shippingcost = $('#shipping_cost').text();
    var shippingcost_input = "<input type='hidden' name='handling_cart' value='"+shippingcost+"'>";
    $('#paypal_form').append(shippingcost_input);
    

    
}


// UPDATE ITEMS QUANTITY AUTO~
            
            $('.item_quantity').livequery('keyup', function() {
            
                shipping_cost = 0;
            
                var what_value_id = $(this).attr('id'); // i get teh ID from the <INPUT>
                var new_total_price = 0;
                var actual_price = parseFloat($('.unit_price#'+what_value_id).text());
                
                var quantity_update = parseFloat($(this).val(),10); // it is very important to convert this value using parseFloat or wrong results will happen  because of presence of string - so we have to make sure this one is really an integer and there's no trace of a string in there. (text entry)
                

                
                // HERE WE NEED TO CHECK THE QUANTITY WHICH ARE AVAILABLE FOR THE ITEM.
                // the stock quantity is stored in an INPUT .item_stock_quantity
                // need to identify  which elements: using var what_value_id we get the data_pos of the updated quantity.

                var actual_stock = parseFloat($('#stock_'+what_value_id).val());
                
                
                if (actual_stock < quantity_update) { 
                
                    $('#error').remove();
                    $('body').append('<span id="error" style="display:block; background-color:red; color:yellow; padding:3px; position:absolute; top:20px; left:473px;"><b>Stocks are limited</b>,<br>please edit your order according to stock availability (max: '+actual_stock+')<br><a href="javascript:void(0);" id="dismiss">OK/dismiss</a></span>');
                    $(this).val(actual_stock);
                } else {
                
                	$('span#error').hide();
                
                }

                
                if (is_int(parseFloat(quantity_update))) {
                
                
                    var new_total = ($(this).val())*(actual_price);

                    $('.item_price#'+what_value_id).text(new_total);
                    $('.item_price').each(function() {
//                        var item_quantity = parseFloat($('input.item_quantity#'+$(this).attr('id')).attr('value'));
                        
/*                        var which_element = 'input.item_quantity#'+$(this).attr('id');
                        var item_quantity = $(which_element).val();
*/
                        var item_quantity = $(this).parent().prev().children('.item_quantity').val();
                        
                        
                        var unit_price = parseFloat($('span.unit_price#'+$(this).attr('id')).text());
                        new_total_price = parseFloat(new_total_price) + (unit_price*item_quantity);
                        var data_pos = $(this).attr('id');
                        

                        
                        
						shipping_dest = update_shipping_costs(data_pos);
            
						var item_shipping_cost = parseFloat($('#'+shipping_dest+"_"+data_pos).text());
                            

                            
						shipping_cost = shipping_cost + item_shipping_cost*(parseFloat(item_quantity));
                        
                        $("#shipping_cost").text(shipping_cost);


                            
                            $('#total_price').text('updating...');
                            
                            var post_url = base_url+"/checkout/update_cart.php";
                            $.post(    
                                    post_url,{  pos: what_value_id,
                                                quantity: quantity_update},
                                    function(returned_data) {
                                        $('#total_price').text(new_total_price);
                                        //update_final_price(shipping_cost);
                                         var updated_price = update_final_price(shipping_cost);
                            
                            $('#total_price_w_shipping').text(updated_price);
                            $('#pp_order_amount').val(updated_price);
                            update_pp_form_item_list();

                                    }
                            );
                    });
                }

            });
    

            
            make_it_prettier();

            
            });



function is_int(variable)
{
	return variable.constructor === Number && Math.round(variable, 0) === variable;
}



function make_it_prettier() {

	$('#events_list').children('.page_item:first').css({'margin':'6px 0 6px 0', 'font-weight':'normal', 'padding':'2px', 'background-color':'grey'}).children('a').css({'color':'white'});
	$('#events_list').children('.page_item:first').children('ul').children('li').children('a').css({'color':'white'});

}
