
$(function() {
	//util.initIRform();
	//reload the IR image occasionally - #irlaunchimage to https://instantrapport.com/present/?team=bravosupport&output=img
	/*
	if($("#irform").length) {
		util.irrefresh = setInterval(function() {
				var now = new Date();
				$("#irlaunchimage").attr("src", "https://instantrapport.com/present/?team=bravosupport&output=img&skiplog=true&nocache=" + now.valueOf());
																																						now = null;
			}, 5000)
	}
	*/
	if(typeof upload != "undefined") {
		util.tabs = {
			"photoHome": { exec: function() { upload.showPhotoHome() },
							hide: function() { upload.hidePhotoHome() } },
			"edit": { exec: function() { 
					upload.adjustHeight();
					if(upload.currview == "") { 
						upload.showDefaultView() 
					} else {
						try {
							var view = upload.currview.split("|");
							
							upload[view[0]](view[1]);
						} catch(e) {
							upload.hidePhotoHome();	
						}
					}
				} 
			},
			"community": { exec: function() { upload.showCommunityHome();  },
						hide: function() { upload.hideCommunityHome(); } },
			"share": { exec: function() { upload.showShareHome() },
						hide: function() { upload.hideShareHome() } },
			"buy": { exec: function() { upload.showShopHome() },
						hide: function() { upload.hideShopHome() } },
			"projects": { exec: function() { upload.showProjectsHome() },
						hide: function() { upload.hideProjectsHome() } }
			}   
		   }
  });
var util = {
	cartwindow: null,
	waitisopen: false,
	irrefresh: 0,
	getuser: function() {
		var username = document.cookie.match(/.*\bwizauth=([^\/]*).*/)
		if(username && username[1])
			return username[1];
		return null;
	},

	getname: function() {
		var name = document.cookie.match(/.*\bbravoname=([^\;]*)\;?.*/)
		if(name && name[1])
			return name[1];
		if(util.getuser() != null)
			return util.getuser();
		return null;
	},
userhome: function() {
		return "/users/" + util.getuser().toLowerCase().replace(/ /g, "_");
	},
userphotohome: function() {
		return util.userhome() + "/photos";
	},
userbuildhome: function() {
		return util.userhome() + "/build";
	},
getcommunity: function() {
		//set the community details
		var host = window.location.hostname;
		
		var work = host.split(".").reverse();
		work.splice(0,1);
		var comm = "";
		if(work[0] != "leepfrog" && work[0].indexOf("bravophoto") == -1) {
			comm = work[0];	
		} else if(work[0].indexOf("bravophoto") != -1 && ((work[1] && work[1] == "www") || typeof work[1] == "undefined")) {
			comm = work[0];
		} else {
			work.splice(0,1);
			comm = work[0];
		}
		
		return comm;
},
escHTML: function(str) {
	return str.replace(/\&/g, "&amp;").replace(/\"/g, '&quot;').replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
},
currencyFormat: function(amount) {
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + 0.005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	},
irlaunch: function() {
		window.open('', 'irvisitor','resizable,width=400,height=400');
		return true;
},
initIRform: function() {
		return;
		var form = $("#irform");
		if(!form.length)
			return;
		form.css("display", "inline");
		
		var num = "Photo Count Unavailable";
		if(!util.getuser()) {
			var ts = new Date();
			var id = "anon-" + ts.valueOf();
			var userid =  id + ":adfgkhfhGEUIIGYGHTksihdskdj==";
			var name = "Guest";
		} else {
			var userid = document.cookie.replace(/.*\bwizauth=([^\/]*[^\;]*).*/, "$1").replace(/\//, ":");
			var id = util.getuser();
			var name = util.getuser();
			if(typeof upload != "undefined" && upload.files)
				num = upload.files.length;
		}
		form.find("#irformuserid").val(userid);
		form.find("#irformname").val(name);
		form.find("#irformcommunity").val(util.getcommunity());
		form.find("#irformnumphotos").val(num);
},
showCart: function(openblank) {
		if(typeof openblank == "undefined")
			var openblank = false;
		if(openblank)
			return;

		var host = window.location.hostname;
		if (window.location.protocol == "https:") {
			window.location.href = "/cart";
		}
		else if (host.indexOf("bravophoto.com") != -1) {
			window.location.href = "https://" + host + "/cart";
		}
		else if (host.indexOf("dev8.leepfrog") != -1) {
			window.location.href = "/cart";
		}
		//need to transfer cookie
		else if ($('#cartform').length == 1) {
			if (document.cookie != "") {
				var cookieset = document.cookie.split(';');
				var wizstr = 'wizauth'
				for (var cookieindex=0;cookieindex < cookieset.length;cookieindex++) {
					var cookie = cookieset[cookieindex];
					var cookindex = cookie.indexOf(wizstr + '=');
					if ( cookindex >= 0) {
						$('#formwizauth').val(cookie.substring(wizstr.length+1+cookindex));
						break;
					}
				}
			}
			var cartformel = $('#cartform')[0];
			var parts = host.split(".").reverse();
			cartformel.action = "https://" + parts[1] + ".bravophoto.com/cart/";
			cartformel.submit();
		}
		else { //ie doesn't like this way
			//form not found log a warning
			handleError('util.js: showCart could not find "cartform" form for submission.', window.location.href, "N/A");

			//shouldn't happen but ... maintaining logic without form for now
			//check pagewiz logs for logged error above before removing this - EZ
			var parts = host.split(".").reverse();
			window.location.href = "https://" + parts[1] + ".bravophoto.com/cart";
		}

	},
wait: function(args) {
		if(typeof args == "undefined")
			var args = {};
		var title = "Wait";
		if(args.title)
			title = args.title;
		var message = "<h2>Please Wait</h2>This should only take a few seconds.";
		if(args.message)
			message = args.message;
		var src = "/images/loading_big.gif"
		if(args.imgsize) {
			if(args.imgsize == "small") {
				src = "/images/loading.gif";
			} else if(args.imgsize == "none") {
				src = "/images/cleardot.gif";
			}
		}	
		if(!util.waitisopen) {
			if(!$("#loadingwin").length) {
				var div = document.createElement("div");
				$(div).addClass("screen").attr("id","loadingwin").html('<table><tbody><tr><td><img src="' + src + '" class="loading" /></td><td><div></div></td></tr></tbody></table>');
				$("body").append(div);
				new lfjs.window(div);
			} else 
				$("#loadingwin").find("IMG.loading").attr("src", src);
	
			$("#loadingwin").find("table div:first").html(message).end()[0].activate({title: title});
			lfjs.window.wait();
			util.waitisopen = true;
		} else {
			$("#loadingwin").find("table div:first").html(message).end().find(".screentitle").text(title);
			
			$("#loadingwin").find("IMG.loading").attr("src", src);
		}
		
	},
nowait: function() {
		if(util.waitisopen) {
			lfjs.window.nowait();
			$("#loadingwin")[0].deactivate();
			util.waitisopen = false;
		}
	}


}


//if you include util.js twice, this becomes an infinite loop.  Check for that.
if(typeof util.stack == "undefined" && typeof lfjs != "undefined") {
	util.stack = {
		lfjsactivate: lfjs.window.prototype.activate,
		lfjsdeactivate: lfjs.window.prototype.deactivate,
		ids: [],
		ref: {},
		idx: -1,
		activate: function(args) {
			//if(window.console)
				//console.log(this);
			var id = this.win.id;
			/*
			//window.location.hash = id;
			var st = $('html,body').scrollTop();
			if(st > 1)
				st = 1
			else
				st = 2
			$('html,body').scrollTop(st);
			*/
			
			util.stack.ids.push(id);
			util.stack.ref[id] = { lfjswin: this, args: args};
			if(!this.isopen)
				util.stack.idx++;
			this.isopen = true;
			util.stack.lfjsactivate.apply(this, [args]);
		},
		deactivate: function(args) {
			this.isopen = false;
			util.stack.idx--;
			util.stack.lfjsdeactivate.apply(this, [args]);
		},
		collapse: function(collapseto) {
			if(typeof collapseto == "undefined") {
				var to = 0;
			} else {
				var to = parseInt(collapseto,10);	
			}
			if(to >= util.stack.ids.length){
				return;
			}
			for(var i=util.stack.ids.length-1; i >=to; i--) {
				var curr = util.stack.ref[util.stack.ids[i]].lfjswin;
				if($(curr.win).filter(":visible").length && curr.isopen == true) {
					curr.isopen = false;
					curr.deactivate();
					util.stack.idx--;
				}
			}
		},
		collapseTo: function(collapseto) {
			util.stack.collapse(collapseto);	
		}
	}
	lfjs.window.prototype.activate = util.stack.activate;
	lfjs.window.prototype.deactivate = util.stack.deactivate;
}

util.clipboard = function(domobj) {
		if(typeof ZeroClipboard == "undefined")
			return null;
		ZeroClipboard.setMoviePath( '/js/ZeroClipboard.swf' );
		this.clip = new ZeroClipboard.Client();
		
		var placeholder = document.createElement("span");
		var ts = new Date().valueOf() + '';
		
		placeholder.id = "utilcopy" + domobj.nodeName.toLowerCase() + ts.substring(Math.floor(Math.random()*ts.length));
		
		$(domobj).css({zIndex: "1"});
		var swfwidth = domobj.offsetWidth;		// Broken: $(domobj).width();
		var swfheight = domobj.offsetHeight;	// Broken: $(domobj).height();
		
		var washidden = false;
		if (swfwidth == 0 || swfwidth == 0) {
			washidden = true;
			//tweak any hidden parents so we can figure out where to put the button.
			var hiddenpar = $(domobj).parents(":hidden");
			var currpos = hiddenpar.css("position"); 
			
			hiddenpar.each(function() {
					if($(this).css("display") == "none") {
						$(this).attr( {"oldpos": $(this).css("position"), "olddsp":$(this).css("display")} );
						$(this).show().css({ visibility: "visible", position:"absolute"});
					}
				});
			swfwidth = domobj.offsetWidth;		// Broken: $(domobj).width();
			swfheight = domobj.offsetHeight;	// Broken: $(domobj).height();
		}
	
		if(/(input|button|img)/.test(domobj.nodeName.toLowerCase())) {
			var buttontext = domobj.value;
			var par = document.createElement("span");
			$(domobj).wrap(par).before(placeholder);
			//console.log("OW: " + domobj.offsetWidth + " - JQ Width: " + $(domobj).width());
			if(domobj.offsetWidth) {
				//swfwidth = domobj.offsetWidth;
				//swfheight = domobj.offsetHeight;
			}
		} else {
			var buttontext = $(domobj).html();
			$(domobj).prepend(placeholder);
		}
			
		var html = this.clip.getHTML( swfwidth, swfheight );
		
		this._threadSetHTML(placeholder, html);
		//$(placeholder).html(html);
		$(placeholder).find("OBJECT, EMBED").each(function() { $(this).css({position: "absolute", "z-index": "2"}) });
		
		if (washidden) {
			hiddenpar.each(function() {
					if($(this).attr("olddsp") == "none") {
						//$(this).hide().css({ visibility: "visible", position:$(this).attr("oldpos")});
					}
				});
		}
	}
util.clipboard.prototype._threadSetHTML = function(el, val) {
		var t = this;
		var s_el = el;
		var s_val = val;
		setTimeout(function() {
			$(s_el).html(s_val);
			t.clip.setText( "Copy meeee!" );
			}, 20);
}
util.clipboard.prototype.copy = function(text) {
	
		this.clip.setText( "Copy meeee!" );
}
