/*

  __ )  _)               |                 |    
  __ \   |   _` |   __|  __|   _ \    __|  |  / 
  |   |  |  (   | \__ \  |    (   |  (       <  
 ____/  _| \__, | ____/ \__| \___/  \___| _|\_\ 
           |___/                                

*/

var LANG_URL = jsvars.LANG_URL;
$(function(){ $('body').addClass(jsvars.USER_LANGUAGE); });
if (jsvars.LANG_URL == '/'+$('html').attr('default_lang')) { LANG_URL = ''; }
bsp = {};
bsp.photos = {};
bsp.selected = {};
var document_location_host = document.location.host.split(".")
var document_domain = document_location_host[document_location_host.length-2]+'.'+document_location_host[document_location_host.length-1];
document.domain = document_domain;
lang = {};
bsp.hasPostMessage =  (typeof window.postMessage === "undefined") ? false : true;
optimizely = optimizely || [];

if(typeof ABtest == 'undefined') { ABtest = {}; }
ABtest.paygo_bulk_purchase = ABtest.paygo_bulk_purchase || 0;
ABtest.paygo_single_purchase = ABtest.paygo_single_purchase || 0;
ABtest.credits_download = ABtest.credits_download || 0;
ABtest.credit_pack_purchase = ABtest.credit_pack_purchase || 0;
ABtest.credit_bulk_download = ABtest.credit_bulk_download || 0;

bsp.regex = {
	email: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
	hash: /#.*?$/
};

//this will catch debug code that may break all js
if(typeof console != 'object') {
	var console = {};
	console.log = function(i){};
}

bsp.html5 = {
	"localStorage" : function() {
		try {
			return 'localStorage' in window && window['localStorage'] !== null;
		} catch (e) {
			return false;
		}
	},
	"placeholder" : function() {
		var test = document.createElement('input');
		return ('placeholder' in test) ? true :  false;
	}
}

function JSONreplacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

var JSON;if(!JSON){JSON={};}
(function(){"use strict";function f(n){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={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){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){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}
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{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){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);}
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);});}
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,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());

(function($) {
	//This is to load in the translation in to the window.lang namespace
	// filepath =  string || array
	$.load_js_translation = function(filepath) {
		
		if(typeof window.lang != 'object') { window.lang = {}; }
		if(typeof filepath != 'object') filepath = [filepath];
		
		return $(filepath).each(function(){
			var filepath = this.replace('.js',''); //check for common mistakes
			var d = new Date();
			var loaded_saved_transations = 0;
			var async_bool = ($.browser.msie && ($.browser.version < 7)) ? true : false; //keep ie6 working a bit better
			if(bsp.html5.localStorage()) { //if localStorage is supported
				if(localStorage["js_translate_"+$('html').attr('lang')+"_"+filepath]) { //if localStorage has been set
					var lang_data = $.parseJSON(localStorage["js_translate_"+$('html').attr('lang')+"_"+filepath]); //encode localStorage
					if((lang_data.date + (1000*60*60)) >  d.getTime()) { //check that data is less then 1 hour old
						for (i in lang_data.data) { //loop through
						   lang[i] = lang_data.data[i]; //put data in lang array
						};
						loaded_saved_transations = 1; //stop ajax call
					}
				}
			}
			if(!loaded_saved_transations) { 
				$.ajax({
					url: LANG_URL+'/js_translation/?path='+filepath+'.html',
					async: async_bool,
					success: function(data){
						var t = $('<div>').append(data); //force jquery to build dom fragment
						var tmp_lang = {};
						t.find('div').each(function(){

							lang[$(this).attr('id')] = $(this).html();
							tmp_lang[$(this).attr('id')] = $(this).html();
						});
						if(bsp.html5.localStorage()) {
							var tmp = {data: tmp_lang, date: d.getTime() } //build object
							var JSON_string = JSON.stringify(tmp, JSONreplacer); //turn object in to string
							localStorage["js_translate_"+$('html').attr('lang')+"_"+filepath] = JSON_string;
						}

					}
				});
			}
		});
	};
})(jQuery);


//Load in language text
$.load_js_translation('common');


Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

/*
jQuery Url Plugin
 * 2010-06-10 - URL: http://ostico.it/content/javascript/jquery/jquery-url-plugin-improvement
 */
(function($) {
    $.url = {};
    $.extend($.url, {
        _params : {},
        init : function(urlPath) {
        	if (typeof urlPath == 'undefined') { urlPath = document.location.href; }
            var paramsRaw = "";
            try {
                paramsRaw = (urlPath.split("?", 2)[1] || "").split("#")[0].split("&") || [];
                for ( var i = 0; i < paramsRaw.length; i++) {
                    var single = paramsRaw[i].split("=");
                    if (single[0])
                        //fix for plus signs from John E on August 24th, 2009 on the Author's Blog
                        this._params[single[0]] = unescape(single[1].replace(/\+/g, " "));
                }
            } catch (e) {
                // alert(e);
            }
        },
        param : function(name, urlPath) {
        	if (typeof urlPath == 'undefined') { urlPath = document.location.href; }
            this.init(urlPath);
            return this._params[name] || "";
        },
        paramAll : function(urlPath) {
        	if (typeof urlPath == 'undefined') { urlPath = document.location.href; }
            this.init(urlPath);
            return this._params;
        }
    });
 
})(jQuery);

Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

bsp.util = {
	set_var: function(param, value, options) {
			if (typeof param == 'undefined') { return false; }
			if (typeof value == 'undefined') { return false; }
			var options = options || {};
			options.async = options.async || false; 

			$.ajax({ url: LANG_URL+'/serverside/set_var.php?'+param+'='+value, async: options.async });
	},
	floordec: function(i,decimals){
		var decimals = decimals || 2;
     	return Math.floor(i*Math.pow(10,decimals))/Math.pow(10,decimals);
	},
	ceildec: function(i,decimals){   
		var decimals = decimals || 2; 
     	return Math.ceil(i*Math.pow(10,decimals))/Math.pow(10,decimals);
	},
	formatMoney: function(n, options) {
		var options = options || {};
		options.decimal_places = options.decimal_places || 2;
		options.decimal = options.decimal || jsvars.DEC_POINT;
		options.thousands = options.thousands || jsvars.THOUSANDS_SEP;
		
		return parseFloat(n).formatMoney(options.decimal_places, options.decimal, options.thousands);
	}
}


if (typeof window.addEventListener != 'undefined') { 
	window.addEventListener('message', postMessage_callback, false); 
} else if (typeof window.attachEvent != 'undefined') { 
	window.attachEvent('onmessage', postMessage_callback); 
}

function postMessage_callback(e) {

	if ( e.origin.indexOf(location.hostname) == -1) { return ; }

	var route = js_routes.get(e.data);
	if(route) {
		js_routes.init(js_routes.get(e.data));
	} else {
		var tmp = $.parseJSON(e.data);
		$.each(tmp, function(i, val){
			bsp[i] = val;
		});
		//lets us run code when data is loadded
		$(document).trigger('postMessage_JSON');
	}
}

function postMessage_iframe_setup(obj) {
	obj.load(function(){
		if(bsp.hasPostMessage){
			$(this)[0].contentWindow.postMessage('{"parent_protocol":"'+location.protocol+'", "i_am_an_iframe":true, "iframe_id":"'+$(this).attr('id')+'"}', 'https://'+location.hostname);
		}
	});

}

$(document).ready(function(){
	if($.url.param('js_routes') != ''){
		js_routes.page_has_reloaded = 1;
		js_routes.init($.url.param('js_routes'));
	} else if (typeof jsvars.js_routes != 'undefined') {
		js_routes.page_has_reloaded = 1;
		js_routes.init(jsvars.js_routes);
	}
});

$('html').on('click','[data-js_routes]', function(){
	js_routes.init($(this).attr('data-js_routes'));
	return false;
});

var js_routes = {
	init: function(route) {
		bsp.hash = {};

		bsp.hash.full = route;

		var tmp_pos = bsp.hash.full.indexOf('?');
		if(tmp_pos != -1) {
			bsp.hash.query = bsp.hash.full.slice(tmp_pos);
			bsp.hash.query = bsp.hash.query.replace('?','');
			bsp.hash.route = bsp.hash.full.slice(0,tmp_pos);
		} else {
			bsp.hash.query = '';
			bsp.hash.route = bsp.hash.full;
		}

		bsp.hash.routes = [];
		tmp_routes = bsp.hash.route.split('/');
		$.each(tmp_routes, function(index, value){
			if(value != '') {
				bsp.hash.routes.push(value);
			}		
		});

		if(bsp.hash.query != '') {
			bsp.hash.params = {};
			var tmp_pairs = bsp.hash.query.split('&');
			$.each(tmp_pairs, function(index, value){
				var tmp_array = value.split('=');
				bsp.hash.params[tmp_array[0]] = tmp_array[1].replace(/::/g,'=');
				// replace :: with = sign for easy var passing in the hash
			});
			
		} else {
			bsp.hash.params = [];
		}

		js_routes.run();
	},
	run: function() {
		var should_go_to_next = 0;
		$(bsp.hash.routes).each(function(i, val){
			switch(val)
			{
			// case 'popup':
			//   	window.open(bsp.hash.params.url, "_blank", decodeURI(bsp.hash.params.params) );
			//   break;
			case 'trigger_click':
			  	$('.js_route_trigger_click').click();
			  	should_go_to_next = 0;
			break;
			case 'trigger_form_submit':
			  	$('.js_route_form_submit').submit();
			  	should_go_to_next = 0;
			break;
			case 'unset-input':
			  	$('.js_route_unset').val('');
			  	should_go_to_next = 1;
			break;
			case 'closeModalWindows': 
				if(bsp.signup_modal) { hideDialog(bsp.signup_modal); }
				if(bsp.login_modal) { hideDialog(bsp.login_modal); }
				if(bsp.show_password_obj) { hideDialog(bsp.show_password_obj); }
				should_go_to_next = 0;
			break;
			case 'continueDownload':
				//needed to show credit charge alert even
				//to those who have opted out
				if(js_routes.page_has_reloaded) {
					bsp.creditChargeAlert = 0;
				}
				$(document).ready(function(){
					//if a promo code if present then only continue if the code matches your mode
					if(jsvars.promo_info.length) {
						if(jsvars.promo_info.trans_type == 'cash' && jsvars.photo_payment_method == 'currency') {
							ImageDetail.downloadAttempt();
						} else if (jsvars.promo_info.trans_type == 'credits' && jsvars.photo_payment_method == 'credits') {
							ImageDetail.downloadAttempt();
						}
					} else {
						//if no promo code is present they continue
						ImageDetail.downloadAttempt();
					}
				});
				if(bsp.signup_modal) { hideDialog(bsp.signup_modal); }
				if(bsp.login_modal) { hideDialog(bsp.login_modal); }
				should_go_to_next = 0;
			  break;
			case 'simple_login':
			case 'login':
				if(bsp.signup_modal) { hideDialog(bsp.signup_modal); }
			  	login({ 'action':bsp.hash.routes[1], "template":val});
			  	should_go_to_next = 0;
			  break;
			case 'signup':
				if(bsp.login_modal) { hideDialog(bsp.login_modal); }
			  	bsp.https_modal('signup',{ 'action':bsp.hash.routes[1]});
			  	should_go_to_next = 0;
			  break;
			case 'showAlert':
				bsp.alert(bsp.hash.routes[1]);
				should_go_to_next = 0;
			  break;
			case 'iframe_resize':
				//easy way for an iframe to tell the parent to resize it
				$('#'+bsp.hash.routes[1]).height(bsp.hash.routes[2]);
			  	should_go_to_next = 0;
			  break;
			default:
			}

			if(should_go_to_next == 0) { return false; }
		});
	},
	clean_url: function(text) {
		return text.replace(/js_routes=.*?(&|$)/g, '').replace(/\?$/,'');
	},
	get: function(url) {

		var uri = url.match(/js_routes=.*?(?=&|$)/);

		if (uri != null) {
			uri[0] = uri[0].split('=');
		} else {
			uri = [];
			uri[0] = ['',''];
		}
		if(typeof uri[0][1] == 'undefined') { uri[0][1] = ''; }

		return uri[0][1];
	},
	for_next_page: function(route, options){
			var options = options || {};
			return bsp.util.set_var('js_routes', route, options);
	}

}



function log(msg) {
	if (!window['console']) return;
    window.console.log(msg);
}

function vof(x, thisObj) {
	if(typeof(x) == 'function')
		if(!thisObj)
			return x();
		else
			return x.call(thisObj);
	return x;
}

function accessor(thisObj, defaultValue) {
	var val = defaultValue;
	return function(v) {
		if(typeof(v) == 'undefined') return val;
		val = v;
		return thisObj;
	}
}

function isdef(x) {
	return typeof(x) != 'undefined';
}

bsp.user = {
	credits: {
		add: function(credits) {
			$('.user_credits').text(jsvars.user.credits + credits);
			jsvars.user.credits = jsvars.user.credits + credits;

		},
		get: function() {
			return jsvars.user.credits;
		}
	},
	photo_payment_method: {
		set: function(type, options){
				var options = options || {};
				return bsp.util.set_var('photo_payment_method', type, options);
		}
	},
	isLoggedIn: function() {
		return (jsvars.user.id == 0) ? false : true;
	}
};

/*
 * jQuery.fn.autoResize 1.14
 * --
 * https://github.com/padolsey/jQuery.fn.autoResize
 * --
 */ 
(function(a){function e(b,c){if(b.data("AutoResizer")){b.data("AutoResizer").destroy()}c=this.config=a.extend({},d.defaults,c);this.el=b;this.nodeName=b[0].nodeName.toLowerCase();this.originalHeight=b.height();this.previousScrollTop=null;this.value=b.val();if(c.maxWidth==="original")c.maxWidth=b.width();if(c.minWidth==="original")c.minWidth=b.width();if(c.maxHeight==="original")c.maxHeight=b.height();if(c.minHeight==="original")c.minHeight=b.height();if(this.nodeName==="textarea"){b.css({resize:"none",overflowY:"hidden"})}b.data("AutoResizer",this);c.animate.complete=function(a){return function(){c.onAfterResize.call(b);return a.apply(this,arguments)}}(c.animate.complete);this.bind()}function d(b){this.filter(d.resizableFilterSelector).each(function(){new e(a(this),b)});return this}var b="ar"+ +(new Date),c=d.defaults={onResize:function(){},onBeforeResize:function(){return 123},onAfterResize:function(){return 555},animate:{duration:200,complete:function(){}},extraSpace:50,minHeight:"original",maxHeight:500,minWidth:"original",maxWidth:500};d.cloneCSSProperties=["lineHeight","textDecoration","letterSpacing","fontSize","fontFamily","fontStyle","fontWeight","textTransform","textAlign","direction","wordSpacing","fontSizeAdjust","paddingTop","paddingLeft","paddingBottom","paddingRight","width"];d.cloneCSSValues={position:"absolute",top:-9999,left:-9999,opacity:0,overflow:"hidden"};d.resizableFilterSelector=["textarea:not(textarea."+b+")","input:not(input[type])","input[type=text]","input[type=password]","input[type=email]","input[type=url]"].join(",");d.AutoResizer=e;a.fn.autoResize=d;e.prototype={bind:function(){var b=a.proxy(function(){this.check();return true},this);this.unbind();this.el.bind("keyup.autoResize",b).bind("change.autoResize",b).bind("paste.autoResize",function(){setTimeout(function(){b()},0)});if(!this.el.is(":hidden")){this.check(null,true)}},unbind:function(){this.el.unbind(".autoResize")},createClone:function(){var c=this.el,e=this.nodeName==="textarea"?c.clone():a("<span/>");this.clone=e;a.each(d.cloneCSSProperties,function(a,b){e[0].style[b]=c.css(b)});e.removeAttr("name").removeAttr("id").addClass(b).attr("tabIndex",-1).css(d.cloneCSSValues);if(this.nodeName==="textarea"){e.height("auto")}else{e.width("auto").css({whiteSpace:"nowrap"})}},check:function(a,b){if(!this.clone){this.createClone();this.injectClone()}var c=this.config,d=this.clone,e=this.el,f=e.val();if(f===this.prevValue){return true}this.prevValue=f;if(this.nodeName==="input"){d.text(f);var g=d.width(),h=g+c.extraSpace>=c.minWidth?g+c.extraSpace:c.minWidth,i=e.width();h=Math.min(h,c.maxWidth);if(h<i&&h>=c.minWidth||h>=c.minWidth&&h<=c.maxWidth){c.onBeforeResize.call(e);c.onResize.call(e);e.scrollLeft(0);if(c.animate&&!b){e.stop(1,1).animate({width:h},c.animate)}else{e.width(h);c.onAfterResize.call(e)}}return}d.width(e.width()).height(0).val(f).scrollTop(1e4);var j=d[0].scrollTop;if(this.previousScrollTop===j){return}this.previousScrollTop=j;if(j+c.extraSpace>=c.maxHeight){e.css("overflowY","");j=c.maxHeight;b=true}else if(j<=c.minHeight){j=c.minHeight}else{e.css("overflowY","hidden");j+=c.extraSpace}c.onBeforeResize.call(e);c.onResize.call(e);if(c.animate&&!b){e.stop(1,1).animate({height:j},c.animate)}else{e.height(j);c.onAfterResize.call(e)}},destroy:function(){this.unbind();this.el.removeData("AutoResizer");this.clone.remove();delete this.el;delete this.clone},injectClone:function(){(d.cloneContainer||(d.cloneContainer=a("<arclones/>").appendTo("body"))).append(this.clone)}}})(jQuery)


$('html').on('click','[data-photo_payment_method]', function(){
	bsp.user.photo_payment_method.set($(this).attr('data-photo_payment_method'));
});

if(jsvars.credit_cart_tracking && ABtest.credit_bulk_download) {
	optimizely.push(['trackEvent', 'credits_bulk_download', jsvars.credit_cart_tracking*100]);
}

trackCurrencyPurchase = function() {
	if(typeof jsvars.purchase_info == 'undefined') { jsvars.purchase_info = 1111111; } //in case this gets lost

	if(!jsvars.bulk_purchase_info) { //do not fire fo bulk downloads
		_gaq.push(['_trackPageview', '/buy-image/']); //track purchase
	}

	if(jsvars.isStoreCardsExists) {
		_gaq.push(['_setCustomVar',3,'Card Saved','Yes',2]);
	} else {
		_gaq.push(['_setCustomVar',3,'Card Saved','No',2]);
	}

	var size_id_label = jsvars.purchase_info.tracking_name;
	var Total_Cost	= usaNumberNotation(jsvars.purchase_info.amount);
	
	var COUNTRY_CODE_3 = jsvars.COUNTRY_CODE_3;
	var order_id = jsvars.purchase_info.transid;
	var vendor = jsvars.purchase_info.vendor;
	var promo_code = jsvars.purchase_info.promo_code;
	var size_name = jsvars.purchase_info.size_name;

	var is_devel = '';
	if(jsvars.run_env && jsvars.run_env == 'local'){
		is_devel = 'YOU_ARE_ON_DEVEL_'; //the pixel will show in the console but not track
	}
	//adwords
	$('body').append('<img src="'+document.location.protocol+'//www.'+is_devel+'googleadservices.com/pagead/conversion/1070250879/?value='+Total_Cost+'&amp;label=inxvCOnxggIQ__aq_gM&amp;guid=ON&amp;script=0" />')

	//msn
	$('body').append('<img src="'+document.location.protocol+'//flex.'+is_devel+'atdmt.com/mstag/tag/8c7afb7e-83f9-48be-9981-9d9d5f7c0c66/analytics.html?dedup=1&domainId=815648&type=1&revenue='+Total_Cost+'&actionid=21662" />')	

	//Responsys
	$('body').append('<img src="'+document.location.protocol+'//'+is_devel+'bigstockmail.com/pub/cct?_ri_=X0Gzc2X%3DUQpglLjHJlYQf11QQQQQvQvQEtA&_ei_=&action=once&OrderTotal='+Total_Cost+'&OrderId='+order_id+'&CustomerId='+jsvars.user.id+'&Type=PAYGO" />')	

	//referralcandy
	$LAB.script(document.location.protocol + "//go."+is_devel+"referralcandy.com/purchase/s5eg9qq3t0k6f3ensloxs8ith.js");

	//Quantcast
	if(jsvars.purchase_info.first_purchase) {
		jsvars.purchase_info.first_purchase = 'NEW';
	} else {
		jsvars.purchase_info.first_purchase = 'EXISTING';
	}
	$('body').append('<img src="'+document.location.protocol+'//secure.'+is_devel+'quantserve.com/pixel/p-c54HQSXs5aAGA.gif?labels=_fp.channel.'+jsvars.purchase_info.first_purchase+',_fp.event.New+Order+Confirmation,_fp.order.'+order_id+',_fp.pcat.'+Total_Cost+'" />')	


	//analytics
	_gaq.push(['_addTrans',
		order_id, // order ID - required
		vendor, // affiliation or store name
		Total_Cost, // total - required
		'', // tax
		'', // shipping
		'', // city
		'', // state or province
		jsvars.COUNTRY_CODE_3 // country
	]); 
  
  	if(jsvars.bulk_purchase_info) {
		//add up how many of each "item"
  		var tmp_bulk = {};
  		for(var i in jsvars.bulk_purchase_info) {
  			if(typeof jsvars.bulk_purchase_info[i] == 'function') { continue; }
  			var item = jsvars.bulk_purchase_info[i];

  			tmp_bulk[item.tracking_name] = tmp_bulk[item.tracking_name] || {};
  			tmp_bulk[item.tracking_name].tracking_name = item.tracking_name;
  			tmp_bulk[item.tracking_name].amount = item.amount;
			
  			if(tmp_bulk[item.tracking_name].count) {
  				tmp_bulk[item.tracking_name].count += 1
  			} else {
  				tmp_bulk[item.tracking_name].count = 1;
  			}

  		}
		
		//add each "item" to google
  		for(var i in tmp_bulk) { 
			_gaq.push(['_addItem',
				order_id, // order ID - required
				tmp_bulk[i].tracking_name, // SKU/code - required
				'Image', // product name
				'', // category or variation
				tmp_bulk[i].amount, // unit price - required
				tmp_bulk[i].count // quantity - required
			]); 
  		}
  	} else {
		_gaq.push(['_addItem',
			order_id, // order ID - required
			size_id_label, // SKU/code - required
			'Image', // product name
			'', // category or variation
			Total_Cost, // unit price - required
			'1' // quantity - required
		]); 

  	}
	_gaq.push(['_trackTrans']); //submits transaction to the Analytics servers


	//Kenshoo
	var params = new Array();
	params[0]='id=197ee6e7-4397-48a1-b034-18a657f9468a';
	params[1]='type=conv';
	params[2]='val='+Total_Cost;
	params[3]='orderId='+order_id;
	params[4]='promoCode='+promo_code;
	params[5]='valueCurrency='+jsvars.CURRENCY_CODE;
	k_trackevent(params,'133');


	//adroll
	window.adroll_segments = "payasyougoconfirmation";
	if(typeof __adroll != 'undefined') { 
		//only call id adroll js has already loaded
		__adroll.render_pixel_code(adroll_adv_id, adroll_pix_id);
	}

	if(ABtest.paygo_bulk_purchase && jsvars.bulk_purchase_info) { 
		optimizely.push(['trackEvent', 'paygo_bulk_purchase', Total_Cost*100]);
	} else if (ABtest.paygo_single_purchase && !jsvars.bulk_purchase_info) { 
		optimizely.push(['trackEvent', 'paygo_single_purchase', Total_Cost*100]);
	}

};



//header
$(document).ready(function(){

	//this adds the lang selection to the URL
	$('.language_select li').click(function(){
		window.location = LANG_URL+'/set_lang/'+$(this).attr('class')+'?url='+window.location.pathname+window.location.search;
        return false;
	});
	
	$('#header2 .menu_item.credits').hover(function(){
		$(this).find('.onHover').show();
	},function(){
		$(this).find('.onHover').hide();
	});

	//search

	$('#formsearch .search_button').click(function(){
		_gaq.push(['_trackEvent', 'Search', 'click']);
	});



	var header_timeout = [];
	var header_timeout_this;
	var header_hover_timeout;
	var header_hover_this;
	$('#header2 .navbar table  td.menu_item').hover(function(){ 
			clearTimeout(header_timeout[$(this).attr('id')])
		
		header_hover_this = this;
		
		header_hover_timeout = setTimeout(function() {
			$('#header2').find('.top_link').removeClass('hover');
			$('#header2').find('.divider').css('visibility','visible');
			$('#header2').find('.dropdown').hide();
			$(header_hover_this).find('.dropdown').show();
			$(header_hover_this).find('.divider').css('visibility','hidden');
			$(header_hover_this).find('.top_link').addClass('hover');
		},100);
	},
	function(){
		clearTimeout(header_hover_timeout);
		
		header_timeout_this = this;
		
		header_timeout[$(this).attr('id')] = setTimeout(function() {
			if(typeof header_timeout_this == 'undefined') 
			{ 
				$('#header2').find('.top_link').removeClass('hover');
				$('#header2').find('.divider').css('visibility','visible');
				$('#header2').find('.dropdown').hide(); 
			} 
			else
			{ 
				$(header_timeout_this).find('.dropdown').hide();
				$(header_timeout_this).find('.divider').css('visibility','visible');
				$(header_timeout_this).find('.top_link').removeClass('hover');
			} 
		},300);
		
	});
	
	
	var search_options_timeout;
	$('#header2 .search .quick_options').hover(function(){
		clearTimeout(search_options_timeout)
		$(this).find('.options').show();
	},
	function(){
		search_options_timeout = setTimeout(function() {
			$('#header2 .search .quick_options').find('.options').hide();
		},300);
	});

	$('#header2 td.search .quick_options .options ul:first li').click(function(){
		$(this).find('input').val(true).change();
		$(this).parents('.options').hide();
	});
	$('#header2 td.search .quick_options .options ul.show_advanced_search').click(function(){
		$(this).parents('.options').hide();
	});
	
	

	$('#search_keyword').keyup(function(e) {
		if(e.keyCode == 13) {
			_gaq.push(['_trackEvent', 'Search', 'enter']);
			//document.formsearch.submit();
		}
	});

	
	$('#quick_options_photos').change(function(){
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_photos').show();
		$('#advsearch #mediatype [value=hide]').prop('selected',true);
		$('#advsearch #fphoto_format [value=]').prop('selected',true);
	});
	$('#quick_options_illustrations').change(function(){
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_illustrations').show();
		$('#advsearch #mediatype [value=only]').prop('selected',true);
		$('#advsearch #fphoto_format [value=]').prop('selected',true);
	});
	$('#quick_options_vectors').change(function(){
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_vectors').show();
		$('#advsearch #mediatype [value=any]').prop('selected',true);
		$('#advsearch #fphoto_format [value=vector]').prop('selected',true);
	});
	$('#quick_options_all').change(function(){
		$('#header2 td.search .quick_options .tab span').hide();
		$('#advsearch #mediatype [value=any]').prop('selected',true);
		$('#advsearch #fphoto_format [value=]').prop('selected',true);
	});
	
	var mediatype = $('#advsearch #mediatype').val();
	var fphoto_format = $('#advsearch #fphoto_format').val();
	
	if(mediatype == 'hide' && fphoto_format == '') {
		$('#quick_options_photos').prop('checked',true)
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_photos').show();
	} else if (mediatype == 'only' && fphoto_format == '') {
		$('#quick_options_illustrations').prop('checked',true)
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_illustrations').show();
	} else if (mediatype == 'any' && fphoto_format == 'vector') {
		$('#quick_options_vectors').prop('checked',true)
		$('#header2 td.search .quick_options .tab span').hide();
		$('#header2 td.search .quick_options .tab span.show_vectors').show();
	} else if (mediatype == 'any' && fphoto_format == '') {
		$('#quick_options_all').prop('checked',true)
		$('#header2 td.search .quick_options .tab span').hide();
	}
	
	//homepage slideshow_2_0
	//
	// SLIDESHOW 2.0
	//
	if($('.slideshow_2_0').length){
	
		bsp.slideshow_2_0 = {};
		bsp.slideshow_2_0.animation_in_progress = 0;
		// * util functions
		bsp.slideshow_2_0.auto_rotate = function() {
			if(bsp.slideshow_2_0.animation_in_progress == 0) {
				_gaq.push(['_trackEvent', 'slideshow_2_0', 'Slides_Auto_Rotated', bsp.slideshow_2_0.slides_to_left+2, bsp.slideshow_2_0.slides_to_left+2, true]);
				bsp.slideshow_2_0.animation_in_progress = 1;
				if(bsp.slideshow_2_0.slides_to_right) {
					bsp.slideshow_2_0.go_right();
				} else { 
					bsp.slideshow_2_0.go_start();
				}
			}
		};
		bsp.slideshow_2_0.go_right = function() {
			$('.slideshow_2_0 .right_arrow').unbind('click');
			$('.slideshow_2_0 .left_arrow').unbind('click');
			if(bsp.slideshow_2_0.slides_to_right == 0) {
				bsp.slideshow_2_0.go_start();
			} 
			$('.slideshow_2_0 .position_relative').animate({ left:'-='+bsp.slideshow_2_0.width }, 1000,
			function(){
				bsp.slideshow_2_0.bind_hover_text();
				bsp.slideshow_2_0.slides_to_right -= 1;
				bsp.slideshow_2_0.slides_to_left += 1;
				bsp.slideshow_2_0.bind_arrow_clicks();
				bsp.slideshow_2_0.animation_in_progress = 0;
			});
		};
		bsp.slideshow_2_0.go_left = function() {
			$('.slideshow_2_0 .right_arrow').unbind('click');
			$('.slideshow_2_0 .left_arrow').unbind('click');
			if(bsp.slideshow_2_0.slides_to_left ==0) {
				bsp.slideshow_2_0.go_end();
			}
			$('.slideshow_2_0 .position_relative').animate({ left:'+='+bsp.slideshow_2_0.width }, 1000,
			function(){
				bsp.slideshow_2_0.bind_hover_text();
				bsp.slideshow_2_0.slides_to_right += 1;
				bsp.slideshow_2_0.slides_to_left -= 1;
				bsp.slideshow_2_0.bind_arrow_clicks();
				bsp.slideshow_2_0.animation_in_progress = 0;
			});
		};
		bsp.slideshow_2_0.go_start = function() {
			bsp.slideshow_2_0.slides_to_left = 0;
			bsp.slideshow_2_0.slides_to_right = bsp.slideshow_2_0.slides - 1;
			$('.slideshow_2_0 .position_relative').css('left',0);
		
		};
		bsp.slideshow_2_0.go_end = function() {
			bsp.slideshow_2_0.slides_to_left = bsp.slideshow_2_0.slides - 1;
			bsp.slideshow_2_0.slides_to_right = 0;
			$('.slideshow_2_0 .position_relative').css('left',-((bsp.slideshow_2_0.slides-1) * bsp.slideshow_2_0.width));
		};
		bsp.slideshow_2_0.bind_hover_text = function() {
			if(bsp.slideshow_2_0.slides > 1) {
				$('.slideshow_2_0 .item').hover(function(){
					$(this).find('.hover').show();
				},function(){
					$(this).find('.hover').hide();
				});
				
				$('.slideshow_2_0 .item .hover').click(function(){
					if($(this).find('a').length) {
						document.location = $(this).find('a').attr('href');
					}
				});
			}
		}
		
		bsp.slideshow_2_0.bind_arrow_clicks = function() {
			$('.slideshow_2_0 .right_arrow').click(function(){
				bsp.slideshow_2_0.should_stop_animation = 1;
				clearInterval(bsp.slideshow_2_0.interval);
				$('.slideshow_2_0 .item').unbind('mouseenter mouseleave');
				bsp.slideshow_2_0.go_right();
			});	
			$('.slideshow_2_0 .left_arrow').click(function(){
				bsp.slideshow_2_0.should_stop_animation = 1;
				clearInterval(bsp.slideshow_2_0.interval); 
				$('.slideshow_2_0 .item').unbind('mouseenter mouseleave');
				bsp.slideshow_2_0.go_left();
			});
		}

		bsp.slideshow_2_0.set_auto_rotate = function() {
			bsp.slideshow_2_0.interval = setInterval("bsp.slideshow_2_0.auto_rotate()",7000);
		}

		
		bsp.slideshow_2_0.bind = function() {
		
			if(!bsp.slideshow_2_0.interval) {
				bsp.slideshow_2_0.interval = setInterval("bsp.slideshow_2_0.auto_rotate()",7000);
			}
			bsp.slideshow_2_0.width = $('.slideshow_2_0').width();
			bsp.slideshow_2_0.slides = $('.slideshow_2_0 .slide').length;
			bsp.slideshow_2_0.should_stop_animation = 0;
			bsp.slideshow_2_0.slides_to_left = 0;
			bsp.slideshow_2_0.slides_to_right = bsp.slideshow_2_0.slides - 1;
			$('.slideshow_2_0 .position_relative').css('left',0);
			
			$('.slideshow_2_0 .inner_wrapper').css('width',  $('.slideshow_2_0 .slide').length * bsp.slideshow_2_0.width);
			bsp.slideshow_2_0.bind_hover_text();
			$('.slideshow_2_0 .left_arrow, .slideshow_2_0 .right_arrow').unbind('click');
			bsp.slideshow_2_0.bind_arrow_clicks();
			
			$('.slideshow_2_0 ').unbind('mouseenter mouseleave');
			$('.slideshow_2_0 ').hover(function(){
				$('.slideshow_2_0 .right_arrow').show();
				$('.slideshow_2_0 .left_arrow').show();
				clearInterval(bsp.slideshow_2_0.interval);
			},function(){
				$('.slideshow_2_0 .right_arrow').hide();
				$('.slideshow_2_0 .left_arrow').hide();
				if(bsp.slideshow_2_0.should_stop_animation == 0) {
					bsp.slideshow_2_0.interval = setInterval("bsp.slideshow_2_0.auto_rotate()",7000);
				}
			});
					
		
		}//bind
	
		_gaq.push(['_trackEvent', 'slideshow_2_0', 'Slides_Auto_Rotated', 1, 1, true]);

		bsp.slideshow_2_0.bind();
		
		$(window).load(function(){
			if(!$('.slideshow_2_0').hasClass('off')) {
				$.get(LANG_URL+'/serverside/homepage_slideshow_2_0.php', {'preview_id':jsvars.cms_preview_id}, function(data) {
					$('.slideshow_2_0 .inner_wrapper').html(data);
					var first_slide = $('.slideshow_2_0 .inner_wrapper .slide:first').clone().addClass('first_slide_placeholder');
					$('.slideshow_2_0 .inner_wrapper').append(first_slide);
					bsp.slideshow_2_0.bind();
				});
			}
		});
	
	}
	//end slideshow_2_0
	
	
});//ready


var loadScript = (function() {
	
	function exists(parts) {
		var node = window;
		for(var i=0; i < parts.length; i++) {
			if(!node[parts[i]]) {
				return false;
			}
			node = node[parts[i]];
		}
		return true;
	}
	
	return (function(url, objSig, cb) {
	
		var parts = objSig.split('.');
		
		if(exists(parts)) {
			if(cb) cb();
			return;
		}
	
		var hd = document.getElementsByTagName('head')[0];
		var sc = document.createElement('script');
		var intr;
		
		sc.type = "text/javascript";
		sc.src = url;
		hd.appendChild(sc);
		
		intr = window.setInterval(function() {
			if(!exists(parts)) return;
			window.clearInterval(intr);
			if(cb) cb();
		}, 10);
	});
})();

var loadScripts = (function() {
							
	function doLoad(index, urls, objSigs, cb) {
		loadScript(urls[index], objSigs[index], function() {
			if(index==urls.length-1) {
				if(cb) cb();
				return;
			}
			doLoad(index+1, urls, objSigs, cb);
		});
	}
							
	return (function(urls, objSigs, cb) {
		doLoad(0, urls, objSigs, cb);
	});
})();

function UIFor(el) {
	var cache = {};
	UIFor = function(el) {
		if(!el) el = $('body').get()[0];
		var id = $.data(el);
		if(cache[id]) return cache[id];
		return (cache[id] = (new UI()).create(el)
				.init().draw());
	};
	return UIFor(el);
}

function UI() {
	this.create = function(domElement) {
    	var children = [], deathHandler;

		this.create = function() {};

        this.draw = function() {
			this.drawn = true;
            return this;
        };
		/* init() is designed to be called only once. Child class implementations of init
		 * will be called once and then re-assigned such that subsequent calls to init
		 * will do nothing. */
        this.init = function() {
			this.init = function() { return this; };
            return this;
        };
        this.de = function() {
        	return domElement;
        };
        this.dispose = function() {};
        this.ce = function() {
        	return this.de();
        };
        this.addChild = function(childObject) {
        	var env = this;
        	if(childObject instanceof Array) {
        		return childObject.each(function(o) {
        			env.addChild(o);
        		});
        	}
            childObject.parent = (function(env) {
            	return function() {
            		return env;
            	};
            })(this);
            childObject.root = function() {
            	var out = this.parent();
            	while(true) {
            		if(!out['parent']) return out;
            		out = out.parent();
            	}
            };
            children[children.length] = childObject;

            this.ce().appendChild(childObject.de());
            return childObject;
        };
        function unb(el) {
        	$(el).unbind();
        	for(var i=0; i < el.childNodes.length; i++) {
        		if(el.childNodes[i].nodeName == '#text')
        			continue;
        		unb(el.childNodes[i]);
        	}
        	return el;
        }

        this.removeChild = function(childObject) {
			childObject = vof(childObject, this);
        	for(var i=0; i < children.length; i++) {
        		if(children[i] == childObject) {
        			this.ce().removeChild(unb(children[i].preDeath().de()));
        			children[i].dispose();
        			children.splice(i, 1);
        		}
        	}
        };
        this.preDeath = function(fn) {
        	if(typeof(fn) == 'undefined') {
        		if(deathHandler) deathHandler();
        		return this;
        	}
        	deathHandler = fn;
        	return this;
        };
        this.indexOf = function(childObject) {
        	if(childObject == this) return -1;
        	for(var i=0; i < children.length; i++)
        		if(children[i] == childObject) return i;
        	return -1;
        };
        this.removeChildren = function(fn) {
        	var more = function() {};
        	while(true) {
	        	try {
	        		var env = this;
	        		this.eachChild(function(ch) {
	        			if(fn && fn(ch) === false) return;
	        			env.removeChild(ch);
	        			throw new more();
	        		});
	        		break;
	        	} catch(e) {
	        		if(!(e instanceof more)) throw e;
	        	}
        	}
        };
        this.eachChild = function(fn) {
        	for(var i=0; i < children.length; i++)
        		if(fn(children[i], i) === false) break;
        };
		this.children = function(a) {
			if(!isdefined(a))
				return children;
			children = a;
			return this;
		};
        this.numChildren = function() {
        	return children.length;
        };
        this.firstChild = function(fn) {
        	if(children.length == 0) return null;
        	if(fn) fn.call(children[0]);
        	return children[0];
        };
        this.childAt = function(index) {
        	return children[index];
        };
        this.redraw = function() { 
			if(!this.drawn) return;
			this.draw();
            for(var i=0; i < children.length; i++)
            	children[i].redraw();
            return this;
        };
        this.op = function(fn) {
        	if(fn) fn.call(this);
        	return this;
        };
        return this;
	};
}

var Canv = (function(Canv) {
	Canv.prototype = new UI();
	return Canv;
})(function() {
	this.create = (function(create) {
		return function(initFn, drawFn) {
			create.apply(this, [document.createElement('div')]);
			this.init = (function(init) {
				return function() {
					this.de().style.position = 'absolute';
					if(initFn) initFn.call(this);
					return init.call(this);
				};
			})(this.init);
			this.draw = (function(sup) {
				return function() {
					if(drawFn) drawFn.call(this);
					return sup.call(this);
				};
			})(this.draw);
			return this;
	   };
	})(this.create);
});

var Canvas = function(initFn, drawFn) {
	return new Canv().create(initFn, drawFn);
};

var Layer = (function() { 
	var bseDepth = 800, depth = bseDepth, layer = 0, stack = [];
	return function(initFn, drawFn) {
		var resize;
		
		function firstModal() {
			var firstVisible;
			for(var i = 0; i < stack.length; i++) {
				if((!firstVisible) && stack[stack.length-1-i].overlay()) {
					$(stack[stack.length-1-i].overlay()).css('visibility', 'visible');
					firstVisible = true;
					continue;
				}
				if(stack[stack.length-i-1].overlay())
					$(stack[stack.length-i-1].overlay()).css('visibility', 'hidden');
			}
			return null;
		}

		return Canvas(function() {
			var env = this;
			layer++;
			$(this.de()).css('z-index', depth+(2*layer));
			if(this.modal()) {
				$('body').get()[0].appendChild((function(de, o) { 
					o.overlay(de);
					$(de)
					.addClass('bsp_overlay')
					.css('z-index', (depth+(2*layer))-1)
					.css('position', 'absolute')
					.css('left', 0).css('top', 0);
					return de;
				})(document.createElement('div'), this));
			}
			firstModal();
			
			resize = function() {
				env.draw();
			};
			$(window).resize(resize)
			.scroll(resize);
			
			if(initFn) initFn.call(this);
		}, function() {
			if(this.overlay()) {
				$(this.overlay()).width($(window).width())
				.height($(window).height())
				.css('left', $(window).scrollLeft())
				.css('top', $(window).scrollTop());
			}

			if(drawFn) drawFn.call(this);
		}).op(function() {
			this.modal = accessor(this, true);
			this.overlay = accessor(this);
			this.dispose = function() {
				layer--;
				if(this.modal()) $('body').get()[0].removeChild(this.overlay());
				stack.splice(index.call(this), 1);
				$(window).unbind('resize', resize).unbind('scroll', resize);
				function index() {
					for(var i=0; i < stack.length; i++) {
						if(stack[i] == this) return i;
					}
				}
				firstModal();
			};
			this.isTopDialog = function() {
				return stack[stack.length-1] == this;	
			};
			stack[stack.length] = this;
			index = stack.length-1;
		});
	};
})();


var Dialog = function(initFn, drawFn) {
	var titleBar, contentCntr, title, width, height, bse, closable = true, dc, 
		firstDraw = true, ctOverflow = 'auto';
		
	return Layer(
		function() {
			var env = this, i = 0;
			$(contentCntr).css('overflow', ctOverflow);
			$(this.de()).addClass('dialog');
			if(dc) for(i=0; i < dc.length; i++) {
				$(this.de()).addClass(dc[i]);
			}
			$(titleBar).html(title||(closable ? '&nbsp;' : ''));
			if(!title) { 
				$(titleBar).addClass('empty');
			}
			if(closable)
				titleBar.appendChild((function(a) {
					$(a).attr('href', '#')
					.addClass('xlink')
					.html($('#close_text').text()+' x')
					.click(function(e) {
						env.parent().removeChild(env);
						e.preventDefault();
					});
					return a;
				})(document.createElement('a')));
				
			if(isdef(width)) {
				$(this.de()).width(width);
				$(contentCntr).width(this.de().offsetWidth);
			}
			if(isdef(height)) {
				$(this.de()).height(height);
				$(contentCntr).height(this.de().offsetHeight - titleBar.offsetHeight);
			}
			
			$(this.de()).css('top',0).css('left',0);

			if(initFn) initFn.call(this);
		},
		function() {
			/* prevents parts of the dialog from being unaccessible esp. w/ low screen resolutions */
			if((!firstDraw) && ((this.de().offsetHeight > $(window).height()) 
					|| (this.de().offsetWidth > $(window).width()))) {
				return;
			}
			if(!firstDraw) return;
			firstDraw = false;
			if(drawFn) { 
				drawFn.call(this);
			} else { 
				if(width) $(this.de()).width(width);
				if(height) $(this.de()).height(height);
				$(this.de())
				.css('left', $(window).scrollLeft() + (($(window).width()/2) - (this.de().offsetWidth/2)))
				.css('top', $(window).scrollTop() + (($(window).height()/2) - (this.de().offsetHeight/2)));
			}
		}
	).op(function() {

		var lyr = this, ct;

		this.de().appendChild((bse = document.createElement('div')));
		$(bse).css('position', 'absolute');
		
		titleBar = document.createElement('div');
		$(titleBar).addClass('title')
			.css('position', 'relative')
			.css('z-index', 2);
		lyr.de().appendChild(titleBar);
		
		contentCntr = document.createElement('div');
		$(contentCntr).css('position', 'relative')
			.css('z-index', 1).css('overflow', 'auto')
			.addClass('content_wrapper');
		lyr.de().appendChild(contentCntr);
		contentCntr.appendChild((function(de, s) {
			s.ce = function() { return de; }
			$(de).addClass('content');
			return de;
		})(document.createElement('div'), this));

		this.dispose = (function(o, sup) {
			var isd = false;
			o.isDisposed = function() {
				return isd;
			}
			return function() {
				sup.call(this);
				isd = true;
				if(this.onDispose())
					this.onDispose()();
			};
		})(this, this.dispose);

		this.onDispose = accessor(this);
		this.redraw = function() {
			firstDraw = true;
			this.draw();
		}

		this.closable = function(x) {
			closable = x;
			return this;
		};
		
		this.draggable = function(x) {
			$(titleBar).css('cursor','move');
			$(this.de()).draggable();
		};
		
		this.title = function(x) {
			title = x;
			return this;
		};
		
		this.width = function(w) {
			width = w;
			return this;
		};
		
		this.height = function(h) {
			height = h;
			return this;
		};
		
		/* controls the overflow property of the content 
		 * container */
		this.contentOverflow = function(o) {
			ctOverflow = o;
			return this;
		};
		
		/* adds the given class to the main .dialog element */
		this.addClass = function(c) {
			if(!dc) dc = [];
			dc[dc.length] = c;
			return this;
		};
	});
};

var Cookie = {
	get: function(name) {
		if (document.cookie.length > 0) {
			var start = document.cookie.indexOf(name + "=");
			if (start==-1 || name=="")
				return null; 
			var end = document.cookie.indexOf(";", start);
			if (end==-1)
				end = document.cookie.length;
			return unescape(document.cookie.substring(start+name.length+1, end));
		}
		return null;
	},
	
	set: function(name, value, expire_days) {
		var domain = COOKIE_DOMAIN;
		var c_expires = "";
		var c_domain = "";
		if (isdef(expire_days)) {
			var date = new Date();
			date.setTime(date.getTime() + (expire_days*24*60*60*1000));
			var c_expires = "; expires=" + date.toGMTString();
		}
		if (domain) {
			var c_domain = "; domain=" + domain;
		}
		document.cookie = name + "=" + escape(value) + c_expires + "; path=/" + c_domain;
	},
	
	remove: function(name) {
		Cookie.set(name, null, -1);
	}
};

//
// track viewport size
//
$(function(){
	if(Cookie.get('viewport_tracked')){
		if(Cookie.get('viewport_tracked') == 1) {
			Cookie.set('viewport_tracked',2)
			_gaq.push(['_trackEvent', 'viewport', 'total', $(window).width()+'x'+$(window).height(), 0, true ]);
			_gaq.push(['_trackEvent', 'viewport', 'height', '', $(window).height(), true ]);
			_gaq.push(['_trackEvent', 'viewport', 'width', '', $(window).width(), true ]);
		}
	} else {
		Cookie.set('viewport_tracked',1)
	}
});

var _dgx_cache = {};

function showDialog(params) {
	var i, classes, dgx = Dialog(
		function() {
			if (isdef(params.htmlID)) {
				if (!isdef(_dgx_cache[params.htmlID])) {
					_dgx_cache[params.htmlID] = $('#'+params.htmlID);
					_dgx_cache[params.htmlID].parent()[0].removeChild(_dgx_cache[params.htmlID][0]);
				}
				$(this.ce())[0].appendChild(_dgx_cache[params.htmlID][0]);
				_dgx_cache[params.htmlID].show();
			}
			else {
				$(this.ce()).html(params.html);
			}
			if(typeof params.init == 'function') {
				params.init.call(this);
			}
		},
		function() {
			if (params.centered) { 
				$(this.de())
				.css('left', $(window).scrollLeft() + (($(window).width()/2) - (this.de().offsetWidth/2)))
				.css('top', $(window).scrollTop() + (($(window).height()/2) - (this.de().offsetHeight/2)));
			}
			else {
				var top = isdef(params.top) ? params.top : 72;
				var left = isdef(params.left) ? params.left : ($(window).width()/2) - (this.de().offsetWidth/2);
				$(this.de())
				.css('left', $(window).scrollLeft() + left)
				.css('top', $(window).scrollTop() + top);
			}
		}
	);
	
	if(params.onDispose) {
		dgx.onDispose(params.onDispose);
	}
	
	/* classes can be a string or an array of class names to be applied 
	 * to the dialog. */
	if(isdef(params.classes)) {
		if(typeof(params.classes) == 'string')
			classes = [params.classes];
		for(i=0; i < classes.length; i++) {
			dgx.addClass(classes[i]);
		}
	}
	
	if(isdef(params.width)) {
		dgx.width(params.width);
	}
	
	if(isdef(params.height)) {
		dgx.height(params.height);
	}
	
	if (isdef(params.modal)) {
		dgx.modal(params.modal);
	}
	else {
		dgx.modal(true);
	}
	
	if(isdef(params.closable)) {
		dgx.closable(params.closable);
	}
	
	if (isdef(params.title)) {
		dgx.title(params.title);
	}
	
	if (isdef(params.draggable)) {
		dgx.draggable(params.draggable);
	}
	
	if(isdef(params.contentOverflow)) {
		dgx.contentOverflow(params.contentOverflow);
	}
	
	return UIFor().addChild(dgx).init().draw();
}

function hideDialog(dgx) {
	if (dgx !== null) {
		dgx.parent().removeChild(dgx);
	}
}

$(document).ready(function() {
	// ie <a><button/></a> workaround
	//var is_ie7 = jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0,1)) <= 7;
	if (jQuery.browser.msie) {
		$('button.button').click(function(e) {
			if ($(this).attr('onclick') === null) {
				var parent = $(this).parent();
				if (parent.attr('onclick') === null) {
					var url = parent.attr('href');
					if (isdef(url)) {
						e.preventDefault();
						e.stopPropagation();
						go(url);
					}
				}
				else {
					parent.click();
				}
			}
		});
	}
	// this fixes a UI problem with underlines over buttons
	$('a button.button').parent().addClass('no-ul');
	

	if(window['pageCtl']) pageCtl();
});

function URL() {
	var parts = window.location.href.split('?'),
		urlParts = [], i, sp, ao;
	
	if(parts.length > 1) {
		urlParts = parts[1].split('&');
		for(i=0; i < urlParts.length; i++) {
			sp = urlParts[i].split('=');
			urlParts[i] = [null, null];
			if(sp.length) {
				urlParts[i] = [sp[0], null];
				if(sp.length > 1) {
					urlParts[i] = [sp[0], sp[1]];
				}
			}
		}
	}
	ao = {
		get : function(key) {
			var idx = indexOf(key);
			if(idx == -1) {
				return undefined;
			}
			return urlParts[idx][1];
		},
		put : function(key, value) {
			var idx = indexOf(key);
			if(idx == -1) {
				urlParts[urlParts.length] = [key, value];
				return this;
			}
			urlParts[idx][1] = value;
			return this;
		},
		toString : function() {
			var i, out = parts[0];
			for(i=0; i < urlParts.length; i++) {
				if(i==0) { out += '?'; }
				else { out += '&'; }
				out += urlParts[i][0]+'=';
				out += urlParts[i][1];
			}
			return out;
		}
	};
	URL = function() {
		return ao;
	}
	return ao;
	
	
	function indexOf(key) {
		var i;
		for(i=0; i < urlParts.length; i++) {
			if(urlParts[i][0] == key)
				return i;
		}
		return -1;
	}
}

// extend jquery to clear a specified form, ie: $('form').clearForm()
$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

// extend jquery to set cursor positions in a textarea
$.fn.setCursorPosition = function(pos) {
	if ($(this).get(0).setSelectionRange) {
		$(this).get(0).setSelectionRange(pos, pos);
	}
	else if ($(this).get(0).createTextRange) {
		var range = $(this).get(0).createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function showElementId(id) {
	$(id).show();
}

function hideElementId(id) {
	$(id).hide();
}

function toggleDisplayElementId(id) {
	var el = $(id);
	
	if (el.css('display') == 'none') {
		el.show();
	}
	else {
		el.hide();
	}
}

bsp.alert = function(options) { log(options);
	if(typeof options == 'string') {
		var tmp = options;
		options = {};
		options.message = tmp;
	} else {
		var options = options || {};
	}
	options.type = options.type || 'focus';

	if(options.clear) { $('.js_global_alert').remove(); }
	if(!options.message) { return false; }

	var focus = '<div class="message_cntr js_global_alert" style="position: relative;"><div class="focusbox rounded"><dl><dt>'+options.message+'</dt></dl></div><div id="smbox_0" class="msgbox-close" style="top: -14px; right: 5px;">close x</div></div>';
	var error = '<div class="message_cntr js_global_alert" style="position: relative;"><div class="errorbox rounded"><dl><dt>'+options.message+'</dt></dl></div><div id="smbox_0" class="msgbox-close" style="top: -14px; right: 5px;">close x</div></div>';
	var alert = '<div class="message_cntr js_global_alert" style="position: relative;"><div class="alertbox rounded"><dl><dt>'+options.message+'</dt></dl></div><div id="smbox_0" class="msgbox-close" style="top: -14px; right: 5px;">close x</div></div>';

	if(options.type == 'focus') {
		$('#header2').after(focus);
	} else if (options.type == 'error') {
		$('#header2').after(error);
	} else if (options.type == 'alert') {
		$('#header2').after(alert);
	};

};

bsp.alert_clear = function() {
	$('.js_global_alert').remove();
};

$('html').on('click','.js_global_alert .msgbox-close', function(){
	$(this).parents('.js_global_alert').remove();
	return false;
});

function go(url) {
	document.location.href = url;
	return false;
}


function signup(options) {
	var options = options || {};
	return bsp.https_modal('signup', options);
}

function login(options) {
	var options = options || {};
	return bsp.https_modal('login', options);
}

bsp.https_modal = function(type, options) {
	//options.action
	//options.template
	//options.json (string) ex: '{"name":"yourName"}'
	if (bsp.user.isLoggedIn()) { return true; }

	var options = options || {};
	options.closable = options.closable || true;
	options.onDispose = options.onDispose || false;
	if(typeof options.json == 'string') { options.json = encodeURIComponent(options.json); } else { options.json = ''; } 

	if (options.action == 'continueDownload') {
		Cookie.set('tmp_image_size', $('form#image_download_select .credits_input:checked').attr('credits'));
	};

	if(typeof options.action != 'undefined') {
		if(document.location.href.match('\\?')) {
			options.action = '&js_routes='+options.action;
		} else {
			options.action = '?js_routes='+options.action;
		}
	} else {
		options.action = '';
	}

	if(type == 'signup') {
		options.template = options.template || 'signup';
		options.classes = options.classes || 'white';
		var tmp_iframe = $('<iframe id="signup_iframe" class="'+(options.template || '')+'" src="https://'+location.hostname+LANG_URL+'/signup/modal/?uri='+encodeURIComponent(js_routes.clean_url(document.location.href.replace(/#.*?$/,''))+options.action)+'&return_to_here=false&template='+(options.template || '')+'&json='+(options.json || '')+'"  scrolling="no" />');
		postMessage_iframe_setup(tmp_iframe)
		bsp.signup_modal = showDialog({title:lang[options.template], html:tmp_iframe,  closable:options.closable, onDispose:options.onDispose, classes:options.classes  });
	} else if(type == 'login') {
		options.classes = options.classes || '';
		(options.template == 'login') ? options.template = 'login_or_signup' : '';
		options.template = options.template || 'login_or_signup';
		var tmp_iframe = $('<iframe id="login_iframe" class="'+(options.template || '')+'" src="https://'+location.hostname+LANG_URL+'/serverside/login.php?uri='+encodeURIComponent(js_routes.clean_url(document.location.href.replace(/#.*?$/,''))+options.action)+'&return_to_here=false&template='+(options.template || '')+'&json='+(options.json || '')+'"  scrolling="no" />');
		postMessage_iframe_setup(tmp_iframe)
		bsp.login_modal = showDialog({ title:lang[options.template], html:tmp_iframe, closable:options.closable, onDispose:options.onDispose, classes:options.classes });
	}

	return false;
}

$(document).ready(function(){

	$('.signup_paypal').click(function(){ 
		if(jsvars.user.id){
			document.location = $(this).data('paypal_action')+'?tracking_id='+jsvars.tracking_id;
		} else {
			$.get(LANG_URL+'/purchase/paypal_modal/', {
				'tracking_id':jsvars.tracking_id,
				"paypal_action":$(this).data('paypal_action'),
				"has_editorial_licence": has_editorial_licence,
				"has_special_licence": has_special_licence
			}, 
			function(data){
				var html = $('<div>'+data+'</div>');
				bsp.signup_modal = showDialog({title:'Checkout with PayPal', html: html, classes:'white' });
			});
		}
		return false;
	});


	$('a.simple_login').click(function(){ return login({'template':'simple_login'}); });
	
	$('#LoginCntr form input#uname').focus(); 

	$('#LoginCntr form').submit(function(){
		$.ajax({
			type: 'POST',
			url: $('#LoginCntr form').attr('action'),
			data: $('#LoginCntr form').serialize(),
			success: function(data){
				if(data && data.status == 1) {

					_gaq.push(['_trackEvent', 'login', 'success']);
					if(js_routes.get($.url.param('uri'))) {
						js_routes.for_next_page(js_routes.get($.url.param('uri')));
					}
					parent.location = js_routes.clean_url($.url.param('uri'));
				} else {
					$('#LoginCntr .errors').html(data.errors[0]);
					$('#LoginCntr .text').addClass('error');
					_gaq.push(['_trackEvent', 'login', 'error']);
				}
			},
			error: function() {
				alert($('#login_ajax_fail').text());
			},
			dataType: 'json'
		});

		return false;
	});

	$('#password_check #password-field').focus(); 
	$('#password_check form').submit(function(){
		$.post($(this).attr('action'), $(this).serialize(), function(data){

			if(data && data.status == 1) {
				if(bsp.hasPostMessage) {
					parent.postMessage('js_routes=/continueDownload/', bsp.parent_protocol+'//'+location.hostname);
				} else {
					parent.location = $.url.param('uri');
				}

			} else {
				$('#password_check .errors').text(data.error);
				$('#password_check .text').addClass('error');
			}
		},'json')
		return false;
	});
	$('#password_check form .cancel').click(function(){
		if(bsp.hasPostMessage) {
			parent.postMessage('js_routes=/closeModalWindows/', bsp.parent_protocol+'//'+location.hostname);
		} else {
			parent.location = $.url.param('uri');
		}
	});

	$('html').on('click','a.switch_to_signup', function(){
		if(bsp.hasPostMessage) {
			if(bsp.i_am_an_iframe) {
				parent.postMessage('js_routes='+tmp_routes, bsp.parent_protocol+'//'+HTTP_HOST);
			} else {
				js_routes.init('signup');
			}
		} else {
			parent.location = full_url;
		}
		return false;
	});

	$('html').on('click','.send_guest_validation_again', function(){
		var $this = $(this);
		var user_id = $(this).data('id');

		$.ajax({
			type: 'POST',
			url: '/serverside/guest_validation_email.php?id='+user_id,
			success: function(data){
				if($this.parents('.message_cntr').length){
					$this.parents('.message_cntr').find('.errorbox').removeClass('errorbox').addClass('focusbox')
					.find('dt').html(data);
				} else if($this.parent().hasClass('errors')) {
					if(bsp.hasPostMessage) {
						parent.postMessage('js_routes=/showAlert/'+data, bsp.parent_protocol+'//'+location.hostname);
						parent.postMessage('js_routes=/closeModalWindows/', bsp.parent_protocol+'//'+location.hostname);
					} else {
						parent.location = $.url.param('uri');
					}

				}
			},
			dataType: 'text',
			async: false
		});

		return false;
	});

});



$(document).ready(function() {

(function($) {

	$.fn.BSPsearch = function(options) {

		var opts = $.fn.BSPsearch.get_options(options);

		return $(this).each(function() {
			$this = $(this);
			
			if($this.find('.'+opts.fields.search_phrase['class']).val() == '') {
				$this.find('.'+opts.fields.search_phrase['class'])
					.val(opts.fields.search_phrase['default'])
					.css("color",opts.fields.search_phrase.blur_color)
			}

			//on submit
			$this.submit(function(){
				var url = $.fn.BSPsearch.get_url($(this), opts);
				if($(this).hasClass('mini-site')) {
					_gaq.push(['_link', url]); 
				} else {
			    	document.location = url;					
				}
				return false;
			});

			//keypress
			$this.keypress(function(e){
				$this = $(this);
				if($(e.target).hasClass(opts.fields.search_phrase['class']) || $(e.target).parents('.'+opts.fields.search_phrase['class']).length ){
					if(e.which == 13){
						$this.submit();
					}
				}
			});

			//on focus
			$this.find('.'+opts.fields.search_phrase['class']).focus(function(){
				var kw = $(this).val();
				$(this).setCursorPosition(kw.length);
				if (kw == opts.fields.search_phrase['default']) {
					$(this).val("").css("color",opts.fields.search_phrase.focus_color);
				}
			});

			//on blur
			$this.find('.'+opts.fields.search_phrase['class']).blur(function(){
				if ($(this).val() == "") {
					$(this).css("color",opts.fields.search_phrase.blur_color).val(opts.fields.search_phrase['default']);
				}
			});

			$this.click(function(e) {
				if($(e.target).hasClass(opts.reset) || $(e.target).parents('.'+opts.reset).length ){
					$.fn.BSPsearch.reset($(this), opts);
					return false;
				}
			});
			
			$.fn.BSPsearch.toggleAdvancedSearch($(this));

		});
	};

	$.fn.BSPsearch.get_options = function(options) {
		var options = $.extend({}, $.fn.BSPsearch.defaults, options);
 		
		var tmp_fields = {};
		$.each($.fn.BSPsearch.defaults.fields, function(i, v){
			if(typeof options.fields != 'undefined' && options.fields[i] != 'undefined') {
				tmp_fields[i] = $.extend({}, $.fn.BSPsearch.defaults.fields[i], options.fields[i]);
			} else {
				tmp_fields[i] = $.fn.BSPsearch.defaults.fields[i];
			}
		});
		options.fields = tmp_fields;

		return $.extend({}, $.fn.BSPsearch.defaults, options);

	};

	$.fn.BSPsearch.get_url = function($this, options) {

		var opts = $.fn.BSPsearch.get_options(options);
		var url = $this.attr('action');
		var c = 0;
		var tmp = [];

		$.each(opts.fields, function(i, v){
		
			if(!$this.find('.'+opts.fields[i]['class']).length) { return true; }

			var value = $this.find('.'+opts.fields[i]['class']).val();
			var name = $this.find('.'+opts.fields[i]['class']).attr('name');

			if(i == 'search_phrase' && value != opts.fields[i]['default'] ) {
				var tmp_val = encodeURIComponent(value.trim().replace(/ /g,'-')).replace(/%2F/g,'/');
				if(tmp_val) { tmp_val += '/'; }
				url += tmp_val;
			} else if(value != opts.fields[i]['default']) {
		    	tmp[c++] = name + '=' + value;
		    }

		});
	    
	    if(tmp.length) {
	    	url += '?'+ tmp.join('&');
	    }

	    return url;

	};

	$.fn.BSPsearch.toggleDimmer = function() {
		if($('#advsearch_dimmer').length) {
			$('#advsearch_dimmer').remove();
		} else {
			$('body').append('<div id="advsearch_dimmer" class="bsp_overlay" style="position:absolute; top:0; left:0; width:100%; height:'+$(document).height()+'px; z-index:100;"></div>');
		}
	};

	$.fn.BSPsearch.reset = function($this, opts) {

		$.each(opts.fields, function(i, v){
			$this.find('.'+opts.fields[i]['class']).each(function(){
				var type = this.type, tag = this.tagName.toLowerCase();
				if (type == 'text' || type == 'password' || tag == 'textarea')
					this.value = '';
				else if (type == 'checkbox' || type == 'radio')
					this.checked = false;
				else if (tag == 'select')
					this.selectedIndex = 0;
			});
		});
		
		$this.find('label').each(function() {
			$(this).removeClass('custom');
		});

	}

	$.fn.BSPsearch.toggleAdvancedSearch = function($this, options) {

		var opts = $.fn.BSPsearch.get_options(options);

		$this.find('.'+opts.advanced_search.toggle).click(function(){

		$this.find('.'+opts.advanced_search['class']).toggle();
			if($this.find('.'+opts.advanced_search['class']).css('display') == 'none') {
				//hide it
				$this.removeClass('formsearch_advanced');
				$('body').removeClass('advsearch_z_index');
				$.fn.BSPsearch.toggleDimmer();
			} else {
				//show it
				$this.addClass('formsearch_advanced');
				$('body').addClass('advsearch_z_index');
				$.fn.BSPsearch.toggleDimmer();
			}


			return false;
		});


	};

	$.fn.BSPsearch.defaults = {
		url: LANG_URL + '/search/',
		fields: {
			search_phrase: {
				'class': 'search_phrase',
				'default': $('#searchBar_default_text').html(),
				focus_color: '#000',
				blur_color: '#787878'
			},
			sort: {
				'class': 'sort_order',
				'default': 'hot'
			},
			category: {
				'class': 'category',
				'default': ''
			},
			media: {
				'class': 'media_type',
				'default': 'any'
			},
			photographer: {
				'class': 'photographer',
				'default': ''
			},
			orientation: {
				'class': 'orientation',
				'default': ''
			},
			file_type: {
				'class': 'file_type',
				'default': ''
			},
			release: {
				'class': 'release',
				'default': 'Both'
			},
			mature: {
				'class': 'mature',
				'default': 'n'
			}
			
		},
		advanced_search: {
			'class': 'advanced_search',
			toggle: 'toggleAdvancedSearch'
		},
		reset: 'reset_options'
	};
})(jQuery);

$('#formsearch').BSPsearch();
$('.single_search').BSPsearch({
	fields: {
		search_phrase: {
			'default': $('.single_serach [placeholder]').attr('placeholder')
		}
	}
});
     


});//ready



String.prototype.trim = function(pattern) {
	return this.lTrim(pattern).rTrim(pattern);
}
String.prototype.lTrim = function(pattern) {
	if(pattern == null) {
		pattern = /\s/;
	}
	else if(typeof(pattern).toString().toLowerCase() == 'string') {
		pattern = new RegExp(pattern);
	}
	var i = 0;
	while(i < this.length-1 && pattern.test(this.charAt(i))) i++;
	return this.substring(i,this.length);
}
String.prototype.rTrim = function(pattern) {
	if(pattern == null) {
		pattern = /\s/;
	} else if(typeof(pattern).toString().toLowerCase() == 'string') {
		pattern = new RegExp(pattern);
	}
	var i=this.length-1;
	while(i >= 0 && pattern.test(this.charAt(i))) i--;
	return this.substring(0,i+1);
}
// thanks IE6
Array.prototype.indexOf = function() {
	for(var i=0; i < this.length; i++) {
		if(this[i] == arguments[0]) return i;
	}
	return -1;
}



/*
*
* ABSTRACT CART
*
*/

bsp.cart = {
	ids : [],
	count: 0,
	remove : function(id, options) {
		$.ajax({
			url: LANG_URL+'/cart/remove/',
			data: {"image_id":id},
			type: "GET",
			dataType: "json",
			success: function(response) {
				//log(response)
				bsp.cart.count = response.data.total_item_count || response.data.total_items;
				delete bsp.cart.ids[id];
				options.callback ? options.callback.call({},response) : '';
				$(document).trigger('cart_removed');
			}
		});
	},
	add : function(id, options) {
		var options = options || {};
		options.credit_cost = options.credit_cost || jsvars.default_image_size || 2;

		var data = {"image_id":id, "credit_cost":options.credit_cost};

		if(options.format_id) { data.format_id = options.format_id; }

		if(options.license_id) { data.license_id = options.license_id; }

		$.ajax({
			url: LANG_URL+'/cart/add/',
			data: data,
			type: "GET",
			dataType: "json",
			success: function(response) {
				if(response.type == 'success') {
					bsp.cart.count = response.data.total_item_count;
					bsp.cart.ids.push(id);
					options.callback ? options.callback.call({},response) : '';
					$(document).trigger('cart_added');
				} else {
					bsp.alert_clear();
					bsp.alert({type:"alert",message:lang.fifty_cart_items});
					$('html, body').animate({scrollTop:0}, 'fast');
				}
			}
		});
	},
	update : function(options) {

		options.credit_cost = options.credit_cost || jsvars.default_image_size || 2;

		var data = {"credit_cost":options.credit_cost};
		var route = LANG_URL+'/cart/update/';

		if(options.image_id) { 
				data.image_id = options.image_id; 
		} else {
			route += 'all/';
		}

		if(options.format_id) { data.format_id = options.format_id; }

		if(options.license_id) { data.license_id = options.license_id; }

		$.ajax({
			url: route,
			data: data,
			type: "GET",
			dataType: "json",
			success: function(response) {
				//log(response)		
				options.callback ? options.callback.call({},response) : '';
				$(document).trigger('cart_size_set');	
			}
		});
	}
}
bsp.cart.ids = jsvars.cart_ids || [];
bsp.cart.count = jsvars.cart_ids.length || 0;

$(document).bind('cart_added cart_removed',function(){
	$('.num_cart_images').html(bsp.cart.count);
	if(bsp.cart.count > 1) {
		$('.cart_many_text').show();
		$('.cart_single_text').hide();

	} else if(bsp.cart.count == 1) {
		$('.cart_many_text').hide();
		$('.cart_single_text').show();
	} else {
		$('.cart_many_text').hide();
		$('.cart_single_text').show();
	}
});

$(function(){
	$('.cart.menu_item').click(function(){
		document.location = $('.cart.menu_item').find('a:first').attr('href');
		return false;
	});
});

/*
*
* PROMO
*
*/
bsp.promo = {
	get_prices:  function(subtotal){
		if(jsvars.promo_info && jsvars.promo_info.amount) {
			var full_discount = subtotal * (jsvars.promo_info.amount / 100);
			var total = bsp.util.floordec(subtotal - full_discount);
			var display_discount = bsp.util.ceildec(full_discount);

			return {
				"total": total.toFixed(2),
				"discount": display_discount.toFixed(2),
				"subtotal": subtotal.toFixed(2)
			}
		}
		return {"total":subtotal.toFixed(2)}
	}
}

/*
*
* ABSTRACT ADD TO LIGHTOBX
*
*/

bsp.lightbox = {
	modal: null,
	showLightboxChooser: function(photo_id, options) {
		var options = options || {};
		options.type = options.type || "chooser_new";
		options.title = options.title || lang.add_to_light_box;

		if (login()) {
			
			var content = $.ajax({url: LANG_URL+"/account/lightbox/0/ajax?action="+options.type+"&image_id="+photo_id, async:false}).responseText;
			
			bsp.lightbox.modal = showDialog({"html":content, "title":options.title, top:300, width:350});
		}
	},
	changeLightboxChooser: function(value) {
		if (value == '0') {
			$('#lightbox_create_fields').show();
			$('#lightbox_name').focus();
		}
		else {
			$('#lightbox_create_fields').hide();
		}
	},
	addToLightbox: function(data) {
	
		if (data.photo_id < 1 || (data.lightbox_id < 1 && data.lightbox_name.length < 1)) {
			return false;
		} else {
			hideDialog(bsp.lightbox.modal);
			bsp.lightbox.modal = null;
		}
		if (data.lightbox_id > 0) {
			$.get(
				LANG_URL+"/image-" + data.photo_id + "/null/ajax",
				{"action":"add-to-lightbox", "photo_id":data.photo_id, "lightbox_id":data.lightbox_id},
				function(r, status) { 
					data.callback ? data.callback.call({},r) : '';
					$(document).trigger('lightbox_item_added');
				},
				"json"
			);
		} else {
			$.get(
				LANG_URL+"/image-" + data.photo_id + "/null/ajax",
				{"action":"add-to-new-lightbox", "photo_id":data.photo_id, "lightbox_name":data.lightbox_name, "make_default":data.new_lightbox_default},
				function(r, status) { 
					data.callback ? data.callback.call({},r) : '';
					$(document).trigger('lightbox_created');
					$(document).trigger('lightbox_item_added');
				},
				"json"
			);
		}
	}
}

$('html').on("change",'#lightbox_chooser_new select', function(){
	bsp.lightbox.changeLightboxChooser($(this).val())
});




function newsletter_signup() {
	email = document.getElementById('newsletter_email').value
	var reg = new RegExp(bsp.regex.email);
	if(reg.test(email) == false) {
	 	msgBox = $('#newsletter_error')
	 	msgBox.html($('#invalid_email_format').text());
	 	msgBox.css('display','block')
		return false;
	}
	$.ajax({ 	'url': LANG_URL+"/newsletter/signup/", 
				'data': {'email':email,'inline':'1'},
				'type': 'POST',
				'dataType': 'test',
				'complete' : function(jqXHR, textStatus) {
					if ( jqXHR.responseText==1 ) { 
						_gaq.push(['_trackPageview', '/newsletter-signup/']);
						msgBox = $('#newsletter_error')
						msgBox.html($('#thank_you_text').text());
						msgBox.css('display','block');
					}
				}
			});
	return true;
}

function set_placeholder_text(objref, text, clear) {
	if ( objref.value == text && clear ) {
		objref.value = ''
	} else if ( objref.value == '' && !clear ) {
		objref.value = text
	}
}

jQuery.fn.alpha_sort_children = function() {
	return this.each(function(){
		var mylist = $(this);
		var listitems = mylist.children(':not(.sort_skip)').get();
		listitems.sort(function(a, b) {
			var compA = $(a).text().toUpperCase()
						.replace("Ä", "A").replace("Ö", "O").replace("Å", "A");
			var compB = $(b).text().toUpperCase()
						.replace("Ä", "A").replace("Ö", "O").replace("Å", "A");
			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		})
		$.each(listitems, function(idx, itm) { mylist.append(itm); });
	});
};


$('html').on('mouseenter','select.country_code_select',function(){
	if($(this).attr('prev_set') != 'true') { //only do it once
		$(this).alpha_sort_children();
		var prev = $(this).attr('prev');
		$(this).val(prev);
		$(this).attr('prev_set','true')
    	$(this).val($(this).find('[selected]').val());
	}
});


var RecaptchaOptions = {
   theme : 'white',
   lang : Cookie.get('lang')
};
function load_recaptcha(){
    Recaptcha.create("6Leslr0SAAAAAAgjLZVuUYBL3Yxo5kXmgq4UiMK-",
      "recaptcha",
      {
        theme: "white",
        lang :Cookie.get('lang')
      }
    );
}
 
 
$(document).ready(function(){
if($('#formcoupon input#coupon_code').length) {
        $('form input#coupon_code').focus(function(){
        	if($('#recaptcha').html() === '') {
                load_recaptcha();
            }
        });
        
        $('form input#coupon_code').blur(function(){
                if($('form input#coupon_code').val() == ''){
                Recaptcha.destroy();
                }
        });

        if($('form input#coupon_code').val() != '') { //if it's set show the captcha
        	$('form input#coupon_code').focus();
        }
        
}//if

if($('#signup_form').length){

	if(Cookie.get('promo')) {
		$('h1.default').hide();
		$('h1.promo').show();
	}

        if($('input#promo').val().length > 0 && $('div#recaptcha').html() == '') {
            load_recaptcha();
        }
        
        $('input#promo').bind('keyup blur focus',function(e){
            if($('input#promo').val().length > 0 && $('div#recaptcha').html() == '') {
                load_recaptcha();
            } else if($('input#promo').val().length == 0) {
                Recaptcha.destroy();
                $('div#recaptcha').html('');
            }
            
        });

}//if

});

function showOverlay() {
	var o = document.getElementById('overlay');
	o.style.display = 'inline-block';
}

function hideOverlay() {
	var o = document.getElementById('overlay');
	o.style.visibility = 'none';
};

Surveyor = {
	survey_html : '',
	dgx_ref : '',
	
	loadit : function(survey_code) {
		var dialog_params = {
			closable : true,
			width : 600,
			title : '&nbsp;'
		};
		$.ajax({
			url : LANG_URL+'/surveys/'+survey_code+'?do=get',
			success: function(response) {
				if ( response=='' ) {
				        return;
				}
				dialog_params.html      = response;
				Surveyor.dgx_ref = showDialog(dialog_params);
			}
		});
	},
	
	unloadit : function() {
		hideDialog(Surveyor.dgx_ref);
		return;
	},
	
	submitit : function(survey_code, post_data, callback) {
		$.post(LANG_URL+'/surveys/'+survey_code+'?do=save', post_data,
			function(response) {
				if ( typeof(callback)=="function" ) {
					callback(response);
				}
			}
		);
		return false;
	}
};
$(window).load(function(){
	if(typeof jsvars.load_surveyor != 'undefined') {
		Surveyor.loadit(jsvars.load_surveyor);
	}
});

/*! LAB.js (LABjs :: Loading And Blocking JavaScript)
    v1.2.0 (c) Kyle Simpson
    MIT License
*/
(function(p){var q="string",w="head",L="body",M="script",u="readyState",j="preloaddone",x="loadtrigger",N="srcuri",E="preload",Z="complete",y="done",z="which",O="preserve",F="onreadystatechange",ba="onload",P="hasOwnProperty",bb="script/cache",Q="[object ",bw=Q+"Function]",bx=Q+"Array]",e=null,h=true,i=false,k=p.document,bc=p.location,bd=p.ActiveXObject,A=p.setTimeout,be=p.clearTimeout,R=function(a){return k.getElementsByTagName(a)},S=Object.prototype.toString,G=function(){},r={},T={},bf=/^[^?#]*\//.exec(bc.href)[0],bg=/^\w+\:\/\/\/?[^\/]+/.exec(bf)[0],by=R(M),bh=p.opera&&S.call(p.opera)==Q+"Opera]",bi=("MozAppearance"in k.documentElement.style),bj=(k.createElement(M).async===true),v={cache:!(bi||bh),order:bi||bh||bj,xhr:h,dupe:h,base:"",which:w};v[O]=i;v[E]=h;r[w]=k.head||R(w);r[L]=R(L);function B(a){return S.call(a)===bw}function U(a,b){var c=/^\w+\:\/\//,d;if(typeof a!=q)a="";if(typeof b!=q)b="";d=((/^\/\//.test(a))?bc.protocol:"")+a;d=(c.test(d)?"":b)+d;return((c.test(d)?"":(d.charAt(0)==="/"?bg:bf))+d)}function bz(a){return(U(a).indexOf(bg)===0)}function bA(a){var b,c=-1;while(b=by[++c]){if(typeof b.src==q&&a===U(b.src)&&b.type!==bb)return h}return i}function H(t,l){t=!(!t);if(l==e)l=v;var bk=i,C=t&&l[E],bl=C&&l.cache,I=C&&l.order,bm=C&&l.xhr,bB=l[O],bC=l.which,bD=l.base,bn=G,J=i,D,s=h,m={},K=[],V=e;C=bl||bm||I;function bo(a,b){if((a[u]&&a[u]!==Z&&a[u]!=="loaded")||b[y]){return i}a[ba]=a[F]=e;return h}function W(a,b,c){c=!(!c);if(!c&&!(bo(a,b)))return;b[y]=h;for(var d in m){if(m[P](d)&&!(m[d][y]))return}bk=h;bn()}function bp(a){if(B(a[x])){a[x]();a[x]=e}}function bE(a,b){if(!bo(a,b))return;b[j]=h;A(function(){r[b[z]].removeChild(a);bp(b)},0)}function bF(a,b){if(a[u]===4){a[F]=G;b[j]=h;A(function(){bp(b)},0)}}function X(b,c,d,g,f,n){var o=b[z];A(function(){if("item"in r[o]){if(!r[o][0]){A(arguments.callee,25);return}r[o]=r[o][0]}var a=k.createElement(M);if(typeof d==q)a.type=d;if(typeof g==q)a.charset=g;if(B(f)){a[ba]=a[F]=function(){f(a,b)};a.src=c;if(bj){a.async=i}}r[o].insertBefore(a,(o===w?r[o].firstChild:e));if(typeof n==q){a.text=n;W(a,b,h)}},0)}function bq(a,b,c,d){T[a[N]]=h;X(a,b,c,d,W)}function br(a,b,c,d){var g=arguments;if(s&&a[j]==e){a[j]=i;X(a,b,bb,d,bE)}else if(!s&&a[j]!=e&&!a[j]){a[x]=function(){br.apply(e,g)}}else if(!s){bq.apply(e,g)}}function bs(a,b,c,d){var g=arguments,f;if(s&&a[j]==e){a[j]=i;f=a.xhr=(bd?new bd("Microsoft.XMLHTTP"):new p.XMLHttpRequest());f[F]=function(){bF(f,a)};f.open("GET",b);f.send("")}else if(!s&&a[j]!=e&&!a[j]){a[x]=function(){bs.apply(e,g)}}else if(!s){T[a[N]]=h;X(a,b,c,d,e,a.xhr.responseText);a.xhr=e}}function bt(a){if(typeof a=="undefined"||!a)return;if(a.allowDup==e)a.allowDup=l.dupe;var b=a.src,c=a.type,d=a.charset,g=a.allowDup,f=U(b,bD),n,o=bz(f);if(typeof d!=q)d=e;g=!(!g);if(!g&&((T[f]!=e)||(s&&m[f])||bA(f))){if(m[f]!=e&&m[f][j]&&!m[f][y]&&o){W(e,m[f],h)}return}if(m[f]==e)m[f]={};n=m[f];if(n[z]==e)n[z]=bC;n[y]=i;n[N]=f;J=h;if(!I&&bm&&o)bs(n,f,c,d);else if(!I&&bl)br(n,f,c,d);else bq(n,f,c,d)}function Y(a){if(t&&!I)K.push(a);if(!t||C)a()}function bu(a){var b=[],c;for(c=-1;++c<a.length;){if(S.call(a[c])===bx)b=b.concat(bu(a[c]));else b[b.length]=a[c]}return b}D={script:function(){be(V);var a=bu(arguments),b=D,c;if(bB){for(c=-1;++c<a.length;){if(B(a[c]))a[c]=a[c]();if(c===0){Y(function(){bt((typeof a[0]==q)?{src:a[0]}:a[0])})}else b=b.script(a[c]);b=b.wait()}}else{for(c=-1;++c<a.length;){if(B(a[c]))a[c]=a[c]()}Y(function(){for(c=-1;++c<a.length;){bt((typeof a[c]==q)?{src:a[c]}:a[c])}})}V=A(function(){s=i},5);return b},wait:function(a){be(V);s=i;if(!B(a))a=G;var b=H(t||J,l),c=b.trigger,d=function(){try{a()}catch(err){}c()};delete b.trigger;var g=function(){if(J&&!bk)bn=d;else d()};if(t&&!J)K.push(g);else Y(g);return b}};if(t){D.trigger=function(){var a,b=-1;while(a=K[++b])a();K=[]}}else D.trigger=G;return D}function bv(a){var b,c={},d={"UseCachePreload":"cache","UseLocalXHR":"xhr","UsePreloading":E,"AlwaysPreserveOrder":O,"AllowDuplicates":"dupe"},g={"AppendTo":z,"BasePath":"base"};for(b in d)g[b]=d[b];c.order=!(!v.order);for(b in g){if(g[P](b)&&v[g[b]]!=e)c[g[b]]=(a[b]!=e)?a[b]:v[g[b]]}for(b in d){if(d[P](b))c[d[b]]=!(!c[d[b]])}if(!c[E])c.cache=c.order=c.xhr=i;c.which=(c.which===w||c.which===L)?c.which:w;return c}p.$LAB={setGlobalDefaults:function(a){v=bv(a)},setOptions:function(a){return H(i,bv(a))},script:function(){return H().script.apply(e,arguments)},wait:function(){return H().wait.apply(e,arguments)}};(function(a,b,c){if(k[u]==e&&k[a]){k[u]="loading";k[a](b,c=function(){k.removeEventListener(b,c,i);k[u]=Z},i)}})("addEventListener","DOMContentLoaded")})(window);



function usaNumberNotation(number) {
	number = number+''; //type cast as string
	var comma_pos = number.indexOf(',');
	var period_pos = number.indexOf('.');

	if(comma_pos != -1 && period_pos != -1){ //over 1000
		if(comma_pos > period_pos) {
			var number = number.split(',')
			
			number[0] = number[0].replace('.',',');
			return number[0]+'.'+number[1];
		}
	} else { //under 1000
		if(comma_pos) {
			return number.replace(',','.');
		}
	}
	//if already in USA format
	return number;
}

//
// Backwards compatability for HTML placeholder attr
//
$(document).ready(function(){
	if(!bsp.html5.placeholder()) {
		$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == '' || input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
			$('[placeholder]').parents('form').submit(function() { 
				$(this).find('[placeholder]').each(function() {
					var input = $(this);
					if (input.val() == input.attr('placeholder')) {
						input.val('');
					}
				})
			});		
	}
});


$(window).load(function(){
	$('input#newsletter_email').val($('div#enter_email_address_hover').text());
	$('input#newsletter_email').focus(function(){
		set_placeholder_text(this, $('div#enter_email_address_hover').text(), 1);
	});
	$('input#newsletter_email').blur(function(){
		set_placeholder_text(this, $('div#enter_email_address_hover').text(), 0);
	});

});

$(document).ready(function(){
	if($('.bsp_mode').length) {
		$('.bsp_mode img.logo').css('outline','5px solid #'+Math.floor(Math.random()*16777215).toString(16));
		setInterval(
		"$('.bsp_mode img.logo').css('outline','5px solid #'+Math.floor(Math.random()*16777215).toString(16));", 5000);
	}

});


// 
//	Social Buttons: +1 and twitter and facebook
//
$(window).load(function(){
	if($('.g_plus_1').length) { 
	  	window.___gcfg = {lang: jsvars.USER_LANGUAGE};
		(function() { 
			var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
			po.src = 'https://apis.google.com/js/plusone.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		})();
	}

	if($('.twitter-share-button').length) {
		(function() {
			var tw = document.createElement('script'); tw.type = 'text/javascript'; tw.async = true;
			tw.src = 'http://platform.twitter.com/widgets.js';
			$(tw).load(function(){
				twttr.events.bind('tweet', function(event) {
				  if (event) {
				    var targetUrl;
				    if (event.target && event.target.nodeName == 'IFRAME') {
				      targetUrl = extractParamFromUri(event.target.src, 'url');
				    }
				    _gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
				  }
				});
			})
			var tws = document.getElementsByTagName('script')[0]; tws.parentNode.insertBefore(tw, tws);
		})();
	}

	(function() {
	    var e = document.createElement('script');
	    e.async = true;
	    e.src = (document.location.protocol == 'file:' ? 'http:' : document.location.protocol) + '//connect.facebook.net/'+jsvars.FULL_LANGUAGE_CODE+'/all.js';
	    $('#fb-root').append(e);
	}());
	window.fbAsyncInit = function() {
		FB.init({status: true, cookie: true, xfbml: false});
		FB.XFBML.parse($('#footer2')[0]);
		FB.XFBML.parse($('.detailpage_top')[0]);
		FB.XFBML.parse($('#view_photo_share')[0]);
	    FB.Event.subscribe('edge.create', function(targetUrl){
	        _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
	    });
	    FB.Event.subscribe('edge.remove', function(targetUrl){
	        _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
	    });
	    FB.Event.subscribe('message.send', function(targetUrl) {
	        _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
	    });
	};

});

$(function(){
	//
	// snapengage
	//

	$('body').prepend('<div style="visibility: hidden; position:absolute; right:999999999999px;"><img src="'+document.location.protocol+'//snapabug.appspot.com/statusImage?w='+jsvars.snapengage+'" border="0" id="snap_a_bug_enabled_test" /></div>');
	// if width > 2 then agents are online; 
	//$('#snap_a_bug_enabled_test').width()
	$LAB.script(document.location.protocol + "//snapabug.appspot.com/snapabug.js").wait(function(){
		//need to be on the page before we call snapengage
		$('body').append('<div id="SnapABug_W"></div><div id="SnapABug_WP"></div><div id="SnapABug_Applet"></div>');

		SnapABug.setLocale(jsvars.USER_LANGUAGE);
		SnapABug.initAsync(jsvars.snapengage);
		SnapABug.allowOffline(false); //only show chat option when agents are online
		SnapABug.setUserEmail(jsvars.user.email);
		SnapABug.setDomain( COOKIE_DOMAIN.split('.')[COOKIE_DOMAIN.split('.').length-2] + '.' + COOKIE_DOMAIN.split('.')[COOKIE_DOMAIN.split('.').length-1] );
		SnapABug.setStartChat($('#snapengage_welcome').text());

		SnapABug.setCallback('Open', function(agent) {
			_gaq.push(['_trackEvent', 'SnapEngage', 'Open', agent]);
		});

		SnapABug.setCallback('Close', function(what, agent) {
			_gaq.push(['_trackEvent', 'SnapEngage', 'Close', what]);
		});

		SnapABug.setCallback('StartCallme', function(phoneNumber) {
			_gaq.push(['_trackEvent', 'SnapEngage', 'StartCallme', phoneNumber]);
		});

		var seAgent;
		SnapABug.setCallback('OpenProactive', function(agent, msg) { 
			seAgent = agent;
			_gaq.push(['_trackEvent', 'SnapEngage', 'proactivePrompt', agent]);
		});

		SnapABug.setCallback('StartChat', function(email, msg, type) {
			if(bsp.user.isLoggedIn()) {
				setTimeout(function(){ //snapengage needs a few seconds before this will work as per their own developer's advice
					SnapABug.sendTextToChat(jsvars.user.name+': ht'+'tp:/'+'/ww'+'w.bigstockphoto'+'.com/'+'admin/'+'user/'+'general?id='+jsvars.user.id+' ');
				},5000)
			} else {
				setTimeout(function(){ //snapengage needs a few seconds before this will work as per their own developer's advice
					SnapABug.sendTextToChat('This user is not logged in');
				},5000)
				
			}
			
			if (type == 'proactive') {
				_gaq.push(['_trackEvent', 'SnapEngage', 'proactiveEngaged', seAgent]);
			} else {
				_gaq.push(['_trackEvent', 'SnapEngage', 'StartChat', type]);
			}
		});

		if($('.auto_start_snap_engage').length && ($('#snap_a_bug_enabled_test').width() > 2)){
			SnapABug.startChat($('#snapengage_welcome').text());			
		}

	});

}); //snapengage

function extractParamFromUri(uri, paramName) {
	  if (!uri) {
	    return;
	  }
	  var uri = uri.split('#')[0];  // Remove anchor.
	  var parts = uri.split('?');  // Check for query params.
	  if (parts.length == 1) {
	    return;
	  }
	  var query = decodeURI(parts[1]);

	  // Find url param.
	  paramName += '=';
	  var params = query.split('&');
	  for (var i = 0, param; param = params[i]; ++i) {
	    if (param.indexOf(paramName) === 0) {
	      return unescape(param.split('=')[1]);
	    }
	  }
	}

