var appURL = 'www.persistentfan.com';
//pfan.it?
if(location.href.indexOf("pfan") >= 0) {
	appURL = 'www.pfan.it';
} 
//var imageClear = imageURL + '/images/clear.gif';
//var imageNew = imageURL + '/images/new.png';
var currentslideVideo = 1;
var anonfnc = [ ];
var newText = "<font color='#FF0000'>[New]</font>&nbsp;";
var bubbleMsgs = [ ];
var bubbleTop = [ ];
var bubbleLeft = [ ];
bubbleMsgs[0] = "<br><img src='http://i.persistentfan.com/images/search/OrangArrow_up.gif' height='45' width='45'>&nbsp;&nbsp;If you click on a trending topic, you can watch the latest relevant videos and share them with your friends";
bubbleTop[0] = 186;
bubbleLeft[0]=88;
bubbleMsgs[1] = "<BR>If you click on the red arrows you <img src='http://i.persistentfan.com/images/search/OrangArrow_right.gif' height='45' width='45'> can flip through the list of videos and watch more";
bubbleTop[1] = 250;
bubbleLeft[1]=165;
bubbleMsgs[2] = "<BR>If you sign up and then login with your Twitter account, you can tweet about the cool videos you find!<br>&nbsp;&nbsp;&nbsp;&nbsp;<img src='http://i.persistentfan.com/images/search/OrangArrow_down.gif' height='45' width='45'>";
bubbleTop[2] = 18;
bubbleLeft[2]=568;
bubbleMsgs[3] = "<BR>If you sign up, you will get notified <img src='http://i.persistentfan.com/images/search/OrangArrow_right.gif' height='45' width='45'> when new cool videos become available and can share with friends!";
bubbleTop[3] = 180;
bubbleLeft[3]=200;
bubbleMsgs[4] = "<BR>If you click on the 'Watch Videos' button you'll see videos other Persistent Fans are watching<br>&nbsp;<img src='http://i.persistentfan.com/images/search/OrangArrow_down.gif' height='45' width='45'>";
bubbleTop[4] = 260;
bubbleLeft[4]=45;
var bubbleTitle = "Did you know?";
var bubbleShown = false;
var curPlayVid;
var pfTimestamp;


function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		cntfield.value = maxlimit - field.value.length;
	}
}

function twitterOAuth(document) { 
	var oOptions = {
		method: "post",
		onSuccess: function (transport) {
			window.location.replace(transport.responseText);
		}
	};
	var oRequest = new Ajax.Request("http://" + appURL + "/TwitterOAuthServlet.qs", oOptions);
}

function fBRemove() { 
	var oOptions = {
		method: "post",
		parameters: "platformID=1",
		onSuccess: function (transport) {
			window.location.replace(transport.responseText);
		},
		onFailure: function (transport) {
			document.getElementById('fbLogout').innerHTML = transport.responseText;
		}
	};
	var oRequest = new Ajax.Request("http://" + appURL + "/RemoveAuthServlet.qs", oOptions);
}

function tweet(document) { 
	var oOptions = {
		method: "post",
		parameters: "tweet=" + encodeURIComponent(document.getElementById('tweetTxt').value) + "&url=" + encodeURIComponent(document.getElementById('urlPublish').value),
		onSuccess: function (transport) {
			document.getElementById('tweetStatus').innerHTML = transport.responseText;
			document.getElementById('tweetTxt').value = ' ';
		},
		onFailure: function (transport) {
			document.getElementById('tweetStatus').innerHTML = transport.responseText;
		}
		
	};
	var oRequest = new Ajax.Request("http://" + appURL + "/TweetServlet.qs", oOptions);
}


function descNewVideo(document, slideNum, id) { 
	if (thumbDescNew2[slideNum] === '1') { 
		document.getElementById(id).src = imageNew;  
	} else { 
		document.getElementById(id).src = imageClear;  
	} 
} 
function descNewVideo2(document, slideNum, id, newItem) { 
	if (newItem === '1') { 
		document.getElementById(id).src = imageNew;  
		document.getElementById(id).style.width = '85px';
		document.getElementById(id).style.height = '16px';  
		
	} else { 
		document.getElementById(id).src = imageClear;  
	} 
} 

function addProductViewed(productID) { 
	var oOptions = {
		method: "post",
		parameters: "productID=" + productID,
		onSuccess: function (oXHR, oJson) {
		}
	};
	var oRequest = new Ajax.Request("http://" + appURL + "/AddProductViewedServlet.qs", oOptions);
}

function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
  }

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) { endstr = document.cookie.length; }
  return unescape(document.cookie.substring(offset, endstr));
  }


function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
    }
  return null;
  }

// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
  //alert("An error occured of type:" + errorCode);
}

// This function is called when the player changes state
function onPlayerStateChange(newState) {
	var t;
  if(newState === 0) {
  	//ended, grab the next one
  	if(currentslideVideo === 1) {
  		currentslideVideo = -1;
  	} else {
  		currentslideVideo = currentslideVideo - 2;
  	}
  	nextSlideVideo(document,2,3,1);
  	t = newState;
  } else if(newState == 1) {
  	t = newState;
  } else if(newState == 2) {
  	t = newState;
  } else if(newState == 3) {
  	t = newState;
  } else {
  	t = newState;
	}  	
//	var val = getCookie('userID');
//  	 if(val === null) {
//			//fire if not logged in  	
//			var win = new Window({className: "alphacube", width:350, height:400, zIndex: 100, resizable: true, title: "Sample window", showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, draggable:true, wiredDrag: true});
//			win.getContent().innerHTML= "xxxx";
//			win.showCenter();
//		}
//}
}

function updatePlayerInfo() {
  // Also check that at least one function exists since when IE unloads the
  // page, it will destroy the SWF before clearing the interval.
  if(ytplayer && ytplayer.getDuration) {
	var widgetVal = window.location.pathname;

  	if( (ytplayer.getCurrentTime() > 3 && ytplayer.getCurrentTime() < 4 ) &&  bubbleShown === false) {
			var val = getCookie('userID');
  	  if(val !== null || widgetVal.indexOf("/widget") !== -1) {
  	  	return;
  	  }
  		//cookie?
  		var bubbleNum = getCookie('bubbleMsg');
  		var msg;
  		if(bubbleNum === null) {
  			bubbleNum = 0;
  		} else {
  			bubbleNum = parseInt(bubbleNum)+1;
  		}
  		if(bubbleNum < bubbleMsgs.length ) {
	 			msg = bubbleMsgs[bubbleNum];
	  		//write cookie
				var today = new Date();
				var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);	  		
				var bLeft = bubbleLeft[bubbleNum] + ((screen.width - 1024)/2);
				var bTop = bubbleTop[bubbleNum] + ((screen.height - 768)/2);
				setCookie('bubbleMsg',bubbleNum,expiry);
				var win = new Window({className: "alphacube", width:350, height:150, top:bTop, left:bLeft, resizable: true, title: bubbleTitle, showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, draggable:true, wiredDrag: true});
				win.getContent().innerHTML= msg;
				win.show();
				bubbleShown = true;
//				win.showCenter();
				//instrument for GA
				pageTracker._trackEvent("Visitor", "Bubble",bubbleNum + '');

			}
		}
	}
}

// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("ytPlayer");
  setInterval(updatePlayerInfo, 250);
  updatePlayerInfo();
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	ytplayer.addEventListener("onError", "onPlayerError");
}


function videoPopup(document, slideID,video, img, title, amazonLink, amazonMsg, productID, autoplay) {
	var channel = '';
	video = video.replace("\/watch","");
	if(slideID !== 0) {
		//clear prev?
		if(curPlayVid !== 0 && document.getElementById("nowplaying"+curPlayVid)) {
			document.getElementById("nowplaying"+curPlayVid).src="/images/search/clear.gif";
			document.getElementById("nowplayingframe"+curPlayVid).className="";		
		}
		curPlayVid = slideID;
	}
	//show now playing
	if(document.getElementById("nowplaying"+curPlayVid)) {
		document.getElementById("nowplaying"+curPlayVid).src="/images/search/nowplaying.gif";
		document.getElementById("nowplayingframe"+curPlayVid).className="nowplaying";		
	}
	//instrument for GA
	 pageTracker._trackEvent("Video", "Play",title);
		//video already playing?
		var player = document.getElementById("ytPlayer");
		if(player !== null) {
			player.clearVideo();
			player.loadVideoByUrl(video,0);
			bubbleShown = false;
		} else if (document.getElementById('vid') !== null) {
			document.getElementById('vid').value = ' ';
			var flashvars = false;
			var params = {
				wmode: "opaque",
				allowScriptAccess: "always"
			};
			var attributes = {
				allowfullscreen: "true",
				id: "ytPlayer"
			};		
			var so = swfobject.embedSWF(video + "?fs=1&autoplay=1&color1=0x2b405b&color2=0x6b8ab6&border=1&enablejsapi=1&playerapiid=player1&rel=0", "vid", "420", "330", "9", "http://www.persistentfan.com/images/expressInstall.swf", flashvars, params, attributes);
//		var so = swfobject.embedSWF(video + "?fs=1&autoplay=1&color1=0x2b405b&color2=0x6b8ab6&border=1", "vid", "420", "330", "9", "http://www.persistentfan.com/images/expressInstall.swf", flashvars, params, attributes);
	} else {
		//iphone so modify URL
		var videoMod = video.replace("\/v\/","?v=");
		window.location.replace(videoMod); 
		addProductViewed(productID);
		return false;
	}
	
		//set productID
		document.getElementById('productIDPublish').value = productID;
		document.getElementById('imgPublish').value = img;
		document.getElementById('titlePublish').value = title;
		//change space to '-'
		title = title.replace(newText,"");
		var encTitle = encodeURIComponent(title.replace(/ /g, "-"));
		if(document.getElementById('vidTitle2') !== null) {
			channel = encodeURIComponent(document.getElementById('vidTitle2').innerHTML.replace(/ /g,"-"));
		}
		document.getElementById('urlPublish').value='http://www.persistentfan.com/video/' + productID + '/' + channel + '/' + encTitle + '/' + 'tweet';
		document.getElementById('vidUrlPublish').value=video;
		document.getElementById('shareURLtxt').value='http://www.persistentfan.com/video/' + productID + '/' + channel + '/' + encTitle + '/' + 'share';
		//show fbshare
		if(document.getElementById('fbShareDiv')) {
			document.getElementById('fbShareDiv').style['display'] = 'block'; 
		}
		//digg share
		if(document.getElementById('DiggShare')) {
			document.getElementById('DiggShare').href='http://digg.com/submit?url='+encodeURIComponent(document.getElementById("urlPublish").value)+'&title='+document.getElementById("titlePublish").value+'&media=video';
		}
		//show twitter share
		//if(document.getElementById('tweetShareDiv')) {
		//	document.getElementById('tweetShareDiv').style['display'] = 'block'; 
		//}
		//if tweets available
		if (document.getElementById('tweetTxt')) {
			document.getElementById('tweetTxt').value = "Check out the \"" + title.replace(newText,"") + "\" video on @PersistentFan ";
			textCounter(document.getElementById('tweetTxt'),document.getElementById('tweetLength'),125);
		}
		//set fb like btn in iframe using value from shareURLtxt above
		if(document.getElementById('fbLike')) {
			var s = "http://www.facebook.com/plugins/like.php?href="+encodeURIComponent('http://www.persistentfan.com/video/' + productID + '/' + channel + '/x/share')+"&amp;layout=button_count&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21";
			document.getElementById('fbLike').src = s;
			//"http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.persistentfan.com%2Fwatch%2FThe%2BLibertines&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80		
		}
		if(autoplay !== 1) {
			addProductViewed(productID);
		}
	return false;
}


//@TODO - api seems to call *name* twice in a row?? (e.g. (document, URL, name, name, videoClick, videoMsg, productID), false);
//Refactor??
function modifySlideVideo2(document, id, num, imageTypeID, desc, img, imgHeight, imgWidth, URL, productID, autoplay) { 
	var name = desc.replace(/\+/g, " ");
	//IE?
	if (document.getElementById('slide' + id + 'VideoHref').detachEvent && anonfnc[id]) {
		document.getElementById('slide' + id + 'VideoHref').detachEvent('onclick', anonfnc[id], false);
	} else if (document.getElementById('slide' + id + 'VideoHref').removeEventListener ) {
		//everyone else
		document.getElementById('slide' + id + 'VideoHref').removeEventListener('click', anonfnc[id], false);
	}
	
	if (imageTypeID === 1) {
	} else {
		document.getElementById('slide' + id + 'Video').src = img;
		document.getElementById('slide' + id + 'Video').style.width = imgWidth + 'px';
		document.getElementById('slide' + id + 'Video').style.height = imgHeight + 'px';  
		//IE?
		if (document.getElementById('slide' + id + 'VideoHref').attachEvent) {
			document.getElementById('slide' + id + 'VideoHref').attachEvent('onclick', anonfnc[id] = function (a, b, c, d, e, f, g, h) { 
				return function () {
					videoPopup(a, b, c, d, e, f, g, h); 
					return false;
				};
			}
			(document, id, URL, name, name, videoClick, videoMsg, productID), false);
		} else if (document.getElementById('slide' + id + 'VideoHref').addEventListener) {
			document.getElementById('slide' + id + 'VideoHref').addEventListener('click', anonfnc[id] = function (a, b, c, d, e, f, g, h) { 
				return function () {
					videoPopup(a, b, c, d, e, f, g, h); 
					return false;
				};
			}
			(document, id, URL, img, name, videoClick, videoMsg, productID), false);
		}
		
		//document.getElementById('overlay' + id).src = imageURL + '/images/play_overlay.png';
	}
	document.getElementById('desc' + id + 'Video').innerHTML = name; 
	var add = document.getElementById('productID' + id);
	if (add !== null) {
		add.href = 'http://' + appURL + '/validateHome.do?action=invite&productID=' + productID + '&trackID=mostRecent';  
	}
	//autoplay?
	if(autoplay === 1) {
		videoPopup(document, 0, URL, img, name, videoClick, videoMsg, productID, autoplay);
	}
}

function prevSlideVideo2(document, imageTypeID, numItems) 
{
	if(numItems === undefined) {
		numItems = 3;
	}
	currentslideVideo -= numItems;
	if (currentslideVideo <= 1) {
		currentslideVideo = 1;
		document.getElementById('leftArrowVideo').src = imageURL + '/images/search/left_arrow_off.gif';
	}
	document.getElementById('rightArrowVideo').src = imageURL + '/images/search/right_arrow.gif';
	descNewVideo(document, currentslideVideo, 'desc1NewVideo');
	modifySlideVideo(document, 1, 0, imageTypeID);
	if(numItems > 1) {
		descNewVideo(document, currentslideVideo + 1, 'desc2NewVideo');
		modifySlideVideo(document, 2, 1, imageTypeID);
	}
	if(numItems > 2) {
		descNewVideo(document, currentslideVideo + 2, 'desc3NewVideo');
		modifySlideVideo(document, 3, 2, imageTypeID);
	}
	if(document.getElementById('tImage2')) {
		var val2 = document.getElementById('tImage2').src;
		document.getElementById('tImage2').src = val2 + "-" + currentslideVideo;
	}
}


function clearSlideVideo2(document, id, imageTypeID ) { 
	document.getElementById('slide' + id + 'Video').src = imageClear;  
	//document.getElementById('overlay' + id).src = imageClear;
//	document.getElementById('slide' + id + 'VideoHref').sethref = ' ';  
//	document.getElementById('desc' + id + 'Video').style['display'] = 'none';  
	document.getElementById('desc' + id + 'Video').value = ' ';  
	document.getElementById('desc' + id + 'Video').innerHTML = ''; 
	var add = document.getElementById('productID' + id);
//	if (add !== null) {
//		addhref = ' ';
//	}
} 

function callRotator(document, imageTypeID, currentslideVideo, numItems, autoplay) {
	var descID, descIDInt;
	var product, listType, name;
	var curAutoPlay=0;
	//listtype?
	if(document.getElementById('vidTitle2') !== null) {
		product = encodeURIComponent(document.getElementById('vidTitle2').innerHTML);
	} else {
		listType = "topList";
	}

	if(pfTimestamp === undefined) {
		pfTimestamp='';
	}
	var oOptions = {
		method: "post",
		parameters: "product=" + product + "&item=" + currentslideVideo + "&numItems=" + numItems + "&listType=" + listType + "&t=" + pfTimestamp,
		onSuccess: function (transport) {
			var json = transport.responseText.evalJSON(true);
			// iterate
			var len = json.length - 1;
		    for (var x = 0; x < json.length; x++) {
		    	var item = json[x];
		    	name = decodeURIComponent(item.desc);
		    	descIDInt = x + 1;
		    	descID = 'desc' + descIDInt + 'NewVideo';
					//new?
					if(item.newItem === "1") {
						name = newText + name;
					}
					//autoplay?
					if(autoplay === 1 && curPlayVid === descIDInt) {
						curAutoPlay = 1;
					} else {
						curAutoPlay = 0;
					}
		    	
		    	modifySlideVideo2(document, x + 1, x, imageTypeID, name, item.img, item.imgHeight,
		    						item.imgWidth, item.url, item.productID, curAutoPlay);
				//descNewVideo2(document, currentslideVideo + x, descID, item.newItem);
			}				
			//clean up anything left
			for (x = json.length; x < numItems; x++) {
		    	descIDInt = x + 1;
		    	descID = 'desc' + descIDInt + 'NewVideo';
				clearSlideVideo2(document, x + 1 , imageTypeID); 
				//descNewVideo2(document, currentslideVideo + x, descID, 0); 
			} 

		},
		onFailure: function (oXHR, oJson) {
			;
		}
	};
	var oRequest = new Ajax.Request("http://" + appURL + "/RotatorServlet.qs", oOptions);
}

function prevSlideVideo(document, imageTypeID, numItems) 
{
	if(numItems === undefined) {
		numItems = 3;
	}
	currentslideVideo -= numItems;
	if (currentslideVideo <= 1) {
		currentslideVideo = 1;
		document.getElementById('leftArrowVideo').src = imageURL + '/images/search/left_arrow_off.gif';
	}
	document.getElementById('rightArrowVideo').src = imageURL + '/images/search/right_arrow.gif';
	//call rotator
	callRotator(document, imageTypeID, currentslideVideo, numItems);
}


//@TODO - convert to use new signatures on called methods
function nextSlideVideo(document, imageTypeID, numItems, autoplay) 
{
	if(numItems === undefined) {
		numItems = 3;
	}
	
	if (currentslideVideo + numItems > maxslidesVideo) {
		  return;
	}
	currentslideVideo += numItems;
	if (currentslideVideo + 1 >= maxslidesVideo) {
		document.getElementById('rightArrowVideo').src = imageURL + '/images/search/right_arrow_off.gif';  
	} 
	document.getElementById('leftArrowVideo').src = imageURL + '/images/search/left_arrow.gif';  

	//call rotator
	callRotator(document, imageTypeID, currentslideVideo, numItems, autoplay);


} 


function showItemDialog(document) { 
	var productGroup = document.getElementById('productGroup').value;	
	var searchQuery = document.getElementById('searchQuery').value;	
	var frm = document.getElementById('searchForm');
//	if(productGroup == "0" || searchQuery === "" || searchQuery === null) {
	if (searchQuery === "" || searchQuery === null) {
		if (frm) { frm.submit(); }
	} else {
		Dialog.info("Retrieving item information",
 		{top: 100, width: 450, className: "alphacube", showProgress: "true"});

		var oOptions = {
			method: "post",
			parameters: "searchQuery=" + encodeURIComponent(searchQuery) + "&productGroup=1",
			onSuccess: function (oXHR, oJson) {
				if (frm) { 
					frm.submit(); 
					}
			}
		};
		var oRequest = new Ajax.Request("http://" + appURL + "/AddQueryServlet.qs", oOptions);
	}
}		

function isEmail(string) {
    return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) !== -1);
}

function validateInput(document) {
	var email, pw, pw2, msg = "ok";

	if (document.getElementById('email') !== null) {
		email = document.getElementById('email').value;
	}
	if (document.getElementById('password') !== null) {
		pw = document.getElementById('password').value;
	}
	if (document.getElementById('password2') !== null) {
		pw2 = document.getElementById('password2').value;
	}


	if (pw !== pw2) {
		msg = "Passwords don't match";
	} else if (pw === undefined || pw.length < 6) {
		msg = "Passwords must be a minimum of 6 characters";
	//strong pw?
	//checkPassword(??) if return is <0.5, too weak
	} else if (pw !== "******" && checkPassword(pw) < 0.5) {
		msg = "Password needs to be stronger";
	//valid email syntax?
	} else if (!isEmail(email)) {
		msg = "Invalid email address";
	}
	
	return msg;
}

function validateSettings(document) {
	var result = validateInput(document);
	if (result !== "ok") {
		document.getElementById('error_msg').innerHTML = result; 
		document.getElementById('error_msg').show();
		return false; 
	}
}

function validateMailInput(document) {
	if (document.getElementById('emailTo') !== null) {
		email = document.getElementById('emailTo').value;
	}
	if(!isEmail(email)) {
			return "Invalid 'to' email address";
	} 
	if (document.getElementById('emailFrom') !== null) {
		email = document.getElementById('emailFrom').value;
	}
	if(!isEmail(email)) {
			return "Invalid 'from' email address";
	} 
	if (document.getElementById('subject') !== null) {
		if (document.getElementById('subject').value === null || document.getElementById('subject').value === "" ) {
			return "Invalid subject";
		}
	}
	
	if (document.getElementById('message') !== null) {
		if (document.getElementById('message').value === null || document.getElementById('message').value === "") {
			return "Invalid message";
		}
	}
	return "ok";
}

function validateMailShare(document) {
	var result = validateMailInput(document);
	if (result !== "ok") {
		document.getElementById('error_msg').innerHTML = result; 
		document.getElementById('error_msg').show();
		return false; 
	} else {
			document.getElementById('error_msg').hide();
	}
}

function open_signup(document) {
	var email, pw, pw2, userName;

	Dialog.confirm(document.getElementById('signup').innerHTML, {className: "alphacube", width: 400, 
		okLabel: "sign up", cancelLabel: "cancel", 
		onOk: function (win) {
			var result = validateInput(document);
			if (result === "ok") {
				//@todo - duplicate code from validate, cleanup
				if (document.getElementById('email') !== null) {
                	email = document.getElementById('email').value;
				}
				if (document.getElementById('password') !== null) {
					pw = document.getElementById('password').value;
				}
				if (document.getElementById('password2') !== null) {
					pw2 = document.getElementById('password2').value;
				}
				if (document.getElementById('userName') !== null) {
					userName = document.getElementById('userName').value;
				}
				var oOptions = {
					method: "post",
					parameters: "email=" + email + "&password=" + pw + "&password2=" + pw2 + "&userName=" + userName,
					onSuccess: function (oXHR, oJson) {
						//reload
						window.location.replace('/home'); 
					},
					onFailure: function (oXHR, oJson) {
						document.getElementById('login_error_msg').innerHTML = 'Server error'; 
						document.getElementById('login_error_msg').show(); 
						return false;
					}
				};
				var oRequest = new Ajax.Request("http://" + appURL + "/AddAccountServlet.qs", oOptions);
			} else {
				//show error
				document.getElementById('login_error_msg').innerHTML = result; 
				document.getElementById('login_error_msg').show(); 
				Windows.focusedWindow.updateHeight();
				return false;
			}	
			return true;
		}
	});
}

function signup (document) {
	var email, pw, pw2, userName;

			var result = validateInput(document);
			if (result === "ok") {
				//@todo - duplicate code from validate, cleanup
				if (document.getElementById('email') !== null) {
                	email = document.getElementById('email').value;
				}
				if (document.getElementById('password') !== null) {
					pw = document.getElementById('password').value;
				}
				if (document.getElementById('password2') !== null) {
					pw2 = document.getElementById('password2').value;
				}
				if (document.getElementById('userName') !== null) {
					userName = document.getElementById('userName').value;
				}
				var oOptions = {
					method: "post",
					parameters: "email=" + email + "&password=" + pw + "&password2=" + pw2 + "&userName=" + userName,
					onSuccess: function (oXHR, oJson) {
						//reload
						window.location.replace('/view'); 
					},
					onFailure: function (oXHR, oJson) {
						document.getElementById('login_error_msg').innerHTML = 'Server error'; 
						document.getElementById('login_error_msg').show(); 
						return false;
					}
				};
				var oRequest = new Ajax.Request("http://" + appURL + "/AddAccountServlet.qs", oOptions);
			} else {
				//show error
				if(document.getElementById('login_error_msg')) {
					document.getElementById('login_error_msg').innerHTML = result; 
					document.getElementById('login_error_msg').style['display'] = 'block'; 
				}
				return false;
			}	
			return true;
		}


function open_login(document) {
	Dialog.confirm(document.getElementById('login').innerHTML, {windowParameters: {className: "alphacube", width: 400, 
		okLabel: "sign in", cancelLabel: "cancel", 
		onOk: function (win) {
			var email = '';
			var pw = '';
			if (document.getElementById('email') !== null) {
				email = document.getElementById('email').value;
			}
			if (document.getElementById('password') !== null) {
				pw = document.getElementById('password').value;
			}
			var oOptions = {
				method: "post",
				parameters: "email=" + email + "&password=" + pw,
				onSuccess: function (oXHR, oJson) {
					//reload
					window.location.replace('/validateHome.do');
				},
				onFailure: function (oXHR, oJson) {
					document.getElementById('login_error_msg').innerHTML = 'Invalid combo'; 
					document.getElementById('login_error_msg').show(); 
					Windows.focusedWindow.updateHeight();
					return false;
				}
			};
			var oRequest = new Ajax.Request("http://" + appURL + "/LoginServlet.qs", oOptions);
			//return true;
		}
	}});
}

function login(document) {
			var email = '';
			var pw = '';
			if (document.getElementById('email') !== null) {
				email = document.getElementById('email').value;
			}
			if (document.getElementById('password') !== null) {
				pw = document.getElementById('password').value;
			}
			var oOptions = {
				method: "post",
				parameters: "email=" + email + "&password=" + pw,
				onSuccess: function (oXHR, oJson) {
					//reload
					window.location.replace('/validateHome.do');
				},
				onFailure: function (oXHR, oJson) {
					document.getElementById('login_error_msg').innerHTML = 'Invalid combo'; 
					document.getElementById('login_error_msg').show(); 
					return false;
				}
			};
			var oRequest = new Ajax.Request("http://" + appURL + "/LoginServlet.qs", oOptions);
			//return true;
		}
	

function sendMail(){
	win = window.open("/mail.do?message="+document.getElementById('shareURLtxt').value,'emailWindow','height=400,width=500');
}


