/* Tour Embed Code supplied by http://tourwrist.com. LazyLoad 2.0.3 supplied by https://github.com/rgrove/lazyload/. */
LazyLoad=function(k){function p(b,a){var g=k.createElement(b),c;for(c in a)a.hasOwnProperty(c)&&g.setAttribute(c,a[c]);return g}function l(b){var a=m[b],c,f;if(a)c=a.callback,f=a.urls,f.shift(),h=0,f.length||(c&&c.call(a.context,a.obj),m[b]=null,n[b].length&&j(b))}function w(){var b=navigator.userAgent;c={async:k.createElement("script").async===!0};(c.webkit=/AppleWebKit\//.test(b))||(c.ie=/MSIE/.test(b))||(c.opera=/Opera/.test(b))||(c.gecko=/Gecko\//.test(b))||(c.unknown=!0)}function j(b,a,g,f,h){var j=function(){l(b)},o=b==="css",q=[],d,i,e,r;c||w();if(a)if(a=typeof a==="string"?[a]:a.concat(),o||c.async||c.gecko||c.opera)n[b].push({urls:a,callback:g,obj:f,context:h});else{d=0;for(i=a.length;d<i;++d)n[b].push({urls:[a[d]],callback:d===i-1?g:null,obj:f,context:h})}if(!m[b]&&(r=m[b]=n[b].shift())){s||(s=k.head||k.getElementsByTagName("head")[0]);a=r.urls;d=0;for(i=a.length;d<i;++d)g=a[d],o?e=c.gecko?p("style"):p("link",{href:g,rel:"stylesheet"}):(e=p("script",{src:g}),e.async=!1),e.className="lazyload",e.setAttribute("charset","utf-8"),c.ie&&!o?e.onreadystatechange=function(){if(/loaded|complete/.test(e.readyState))e.onreadystatechange=null,j()}:o&&(c.gecko||c.webkit)?c.webkit?(r.urls[d]=e.href,t()):(e.innerHTML='@import "'+g+'";',u(e)):e.onload=e.onerror=j,q.push(e);d=0;for(i=q.length;d<i;++d)s.appendChild(q[d])}}function u(b){var a;try{a=!!b.sheet.cssRules}catch(c){h+=1;h<200?setTimeout(function(){u(b)},50):a&&l("css");return}l("css")}function t(){var b=m.css,a;if(b){for(a=v.length;--a>=0;)if(v[a].href===b.urls[0]){l("css");break}h+=1;b&&(h<200?setTimeout(t,50):l("css"))}}var c,s,m={},h=0,n={css:[],js:[]},v=k.styleSheets;return{css:function(b,a,c,f){j("css",b,a,c,f)},js:function(b,a,c,f){j("js",b,a,c,f)}}}(this.document);

var embed_tour_ids=[];var krpano_width,krpano_height,whitelabel_id,open_in_app, app_store_url;

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) { str = '0' + str; }
    return str;
}

function isAppleMobileDevice(){
	return ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1));
}

function shouldOpenSceneInApp(){
	return (isAppleMobileDevice() && open_in_app);
}

function show_confirm(message, location){
	if (confirm(message)) { window.location = location; }
}

function open_scene_in_app(id, object, json){
	if (confirm("Would you like to view this scene in its iOS app?")) {
		window.location = whitelabel_id + "://" + pad(id,5);
	  var clickedAt = +new Date;
    setTimeout(function() {
			if (+new Date - clickedAt < 2000)
				show_confirm("You don't have the proper app installed. Would you like to install it?.", app_store_url);
    }, 500);
	} else {
		if (object.hasClass("popup")) { setup_colorbox(object); } else if (object.hasClass("direct")) {	object.html(""); }
		setup_krpano(object,json);
	}
}

function setupViewer(){}; // future use

function setup_krpano(object, json){
	tour_id = object.attr('id');
	if (object.hasClass("popup")) { targetID="inline_example_"+tour_id; } else if (object.hasClass("direct")) { targetID=tour_id; }
	var viewer=createPanoViewer({swf:"http://www.tourwrist.com/flash/krpano.swf",
															target:targetID,
															width:object.hasClass("popup")?"635":krpano_width,
															height:object.hasClass("popup")?"400":krpano_height,
															id:"twkrpano"+tour_id});
	viewer.addVariable("xml", json.pano.krpano_xml);
	viewer.addParam("wmode", "transparent");
	viewer.embed();
}

function setup_colorbox(object){
	tour_id = object.attr('id');
	jQuery(".tourwrist_tour_"+tour_id).colorbox({width:"702px",height:"500",inline:true,href:"#inline_example_"+tour_id});
}

function setup_inner_html(object, json){
	tour_id = object.attr('id');
	target=tour_id;
	if (object.hasClass("popup")){
		target="inline_example_"+target;
		object.html('<p><a class="tourwrist_tour_'+tour_id+'" title="'+json.pano.name+'" href="#" ><Inline HTML><img src="'+json.pano.thumb_url+'" style="border:1px solid #000;"></a></p><div style="display:none"><div id="inline_example_'+tour_id+'" style="padding:10px; background:#000;overflow:hidden;"></div></div>');
	} else if (object.hasClass("direct") && shouldOpenSceneInApp()) {
		object.html('<p><a class="tourwrist_tour_'+tour_id+'" title="'+json.pano.name+'" href="#" ><Inline HTML><img src="'+json.pano.large_thumb_url+'" style="border:1px solid #000;width:'+krpano_width+';height:'+krpano_height+' "></a></p><div style="position:relative;top:-250px;left:180px;" id="tap-to-view"><img src="http://www.tourwrist.com/assets/old_controls/controls_tw.png"></img></div>');
	}
}

function setup_embeds(json_data){
	jQuery('.tourwrist-tour-embed').each(function(){
		var tour_id=null;var obj=null;var target=null;
		tour_id=jQuery(this).attr('id');
		obj=jQuery(this);
		jQuery.each(json_data, function(index,value){
			//console.log(value);
			if (value.pano.id == tour_id) {
				setup_inner_html(obj, value);
				if (!shouldOpenSceneInApp()) {
					if (obj.hasClass("popup")) { setup_colorbox(obj); }
					setup_krpano(obj, value);
				} else {
					obj.one("click",function(){ open_scene_in_app(tour_id, obj, value); });
				}
			}
		});
	});
}

function get_data_from_server(){
	if (embed_tour_ids.length > 0) {
		var param_string="";
		jQuery.each(embed_tour_ids,function(index,value){param_string += "id[]="+value+"&";});
		jQuery.get('http://www.tourwrist.com/javascripts/pano_embed_data.json',param_string,function(data){setup_embeds(data);},'json').error(function(data,xhrobj){console.log("Got error "+data.status+" with xhr object "+xhrobj);});
	} else {
		console.log("no pano ids found on this page");
	}
}

function find_embed_divs(){
	jQuery('.tourwrist-tour-embed').each(function(){embed_tour_ids.push(jQuery(this).attr('id'));});
	get_data_from_server();
}

function loadEmbeds(width, height, openInApp, wlString, storeURL){
	krpano_width=width?width:"635"; krpano_height=height?height:"400";
	open_in_app=openInApp;
	whitelabel_id = wlString?"wl"+wlString:"tour";
	app_store_url = storeURL?storeURL:"http://itunes.apple.com/us/app/tour-wrist/id335671384?mt=8";
	js_array = ["http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js","http://tourwrist.s3.amazonaws.com/javascripts/colorbox/jquery.colorbox-min.js","http://www.tourwrist.com/flash/swfkrpano.js", "http://www.tourwrist.com/flash/krpanoiphone.license.js", "http://www.tourwrist.com/flash/krpanoiphone.js"];
	//if (isAppleMobileDevice()) {js_array.push("http://www.tourwrist.com/flash/krpanoiphone.license.js");js_array.push("http://www.tourwrist.com/flash/krpanoiphone.js");}
	LazyLoad.css("http://tourwrist.s3.amazonaws.com/stylesheets/colorbox.css");
	LazyLoad.js(js_array,function(){
		jQuery.noConflict();
		jQuery.ajaxTransport("+*", function( options, originalOptions, jqXHR ){
			if(jQuery.browser.msie && window.XDomainRequest){
			    var xdr;
			    return {
			        send: function( headers, completeCallback ){
			            xdr = new XDomainRequest();
			            xdr.open("get", options.url);
			            xdr.onload = function() {
			                if(this.contentType.match(/\/xml/)){
			                    var dom = new ActiveXObject("Microsoft.XMLDOM");
			                    dom.async = false;
			                    dom.loadXML(this.responseText);
			                    completeCallback(200, "success", [dom]);
			                } else { completeCallback(200, "success", [this.responseText]); }
			            };
			            xdr.ontimeout = function(){completeCallback(408, "error", ["The request timed out."]);};
			            xdr.onerror = function(){completeCallback(404, "error", ["The requested resource could not be found."]);};
			            xdr.send();
			      },
			      abort: function() {if(xdr)xdr.abort();}
			    };
			  }
		});
		jQuery(document).ready(function(){ find_embed_divs(); });
	});
}
