// This file is for objects and functions related to non-static page content.
// -Tom Hirashima

//preload comPop bg
var comPopTop = new Image();
var comPopBtm = new Image();
comPopTop.src = imagesPrefix+'gfx/comPopTop.gif';
comPopBtm.src = imagesPrefix+'gfx/comPopBtm.gif';

var dynPop = {
popIsOn:false,
formStateChange:false,
doCompPop:function(myLink, userID, reviewID){
	var xmlHttpReq = Ajax.getTransport();
	if(xmlHttpReq){
	findPosition(myLink);
	var bigLongString ='<img src="'+comPopTop.src+'" id="comTop"><h4>Choose your Compliment Type:</h4><form id="compForm" name="compForm"><div>';
	bigLongString +='<input type="radio" name="type" id="plain" value="plain" checked="checked" onclick="javascript:dynPop.populate(\'At first I was afraid, I was petrified. Kept thinking I could never live without Yelp by my side. And then I found your reviews, they gave me strength to step out the door, and now I\\\'m calling all my friends and hitting the dance floor.\');"><img src="'+imagesPrefix+'ico/thanks_plain_sm.gif" /><label for="plain">Thank&nbsp;You</label>';
	bigLongString +='<input type="radio" name="type" id="cute" value="cute" onclick="javascript:dynPop.populate(\'Wait, do you model?\');"><img src="'+imagesPrefix+'ico/thanks_cute_pic_sm.gif" /><label for="cute">Cute&nbsp;Pic</label>';
	bigLongString +='<input type="radio" name="type" id="writer" value="writer" onclick="javascript:dynPop.populate(\'Oscar Wilde once said, &quot;Anybody can make history. Only a great man can write it.&quot;  You my friend, are this (wo)man.\');"><img src="'+imagesPrefix+'ico/thanks_good_writer_sm.gif" /><label for="writer" class="lineBreak">Good&nbsp;Writer</label>';
	bigLongString +='<input type="radio" name="type" id="hot" value="hot" onclick="javascript:dynPop.populate(\'Like a strip of bacon frying over an open fire, you\\\'re seriously sizzling.\');"><img src="'+imagesPrefix+'ico/thanks_hot_stuff_sm.gif" /><label for="hot">Hot&nbsp;Stuff</label>';
	bigLongString +='<input type="radio" name="type" id="note" value="note" onclick="javascript:dynPop.populate(\'\');"><img src="'+imagesPrefix+'ico/thanks_just_a_note_sm.gif" /><label for="note">Just&nbsp;a&nbsp;Note</label>';
	bigLongString +='<input type="radio" name="type" id="profile" value="profile" onclick="javascript:dynPop.populate(\'Your profile is like bad medicine. Bad medicine is what I need.\');"><img src="'+imagesPrefix+'ico/thanks_like_profile_sm.gif" /><label for="profile" class="lineBreak">Like&nbsp;Your&nbsp;Profile</label>';
	bigLongString +='<input type="radio" name="type" id="more" value="more" onclick="javascript:dynPop.populate(\'I know you must have a lot of other commitments and social activities that take away time from your Yelp reviews but I can\\\'t take it anymore...you have to write another review. It\\\'s like coffee in the morning and I\\\'ve started getting headaches from your absence so please think of the little guys and prioritize!\');"><img src="'+imagesPrefix+'ico/thanks_write_more_sm.gif" /><label for="more">Write&nbsp;More!</label>';
	bigLongString +='<input type="radio" name="type" id="cool" value="cool" onclick="javascript:dynPop.populate(\'You\\\'re so cool polar bears wear sweaters around you.\');"><img src="'+imagesPrefix+'ico/thanks_youre_cool_sm.gif" /><label for="cool">You\'re&nbsp;Cool</label>';
	bigLongString +='<input type="radio" name="type" id="photos" value="photos" onclick="javascript:dynPop.populate(\'Nice photos Leibovitz. Keep shooting!\');" ><img src="'+imagesPrefix+'ico/thanks_photos_sm.gif" /><label for="photos" class="lineBreak">Great Photo</label>';
	bigLongString +='<input type="radio" name="type" id="list" value="list" onclick="javascript:dynPop.populate(\'Even Craig couldn\\\'t compile a list so robust and entertaining.\');" ><img src="'+imagesPrefix+'ico/thanks_list_sm.gif" /><label for="list">Great Lists</label>';
	bigLongString +='<input type="radio" name="type" id="funny" value="funny" onclick="javascript:dynPop.populate(\'Once you get your own sitcom I\\\'ll be there to add the laugh track.\');" ><img src="'+imagesPrefix+'ico/thanks_funny_sm.gif" /><label class="lineBreak" for="funny">You\'re Funny</label></div>';	
	
	bigLongString +='<textarea id="thanksMessage" name="message" maxchar="100" onKeyPress="dynPop.setFormTrue();">At first I was afraid, I was petrified. Kept thinking I could never live without Yelp by my side. And then I found your reviews, they gave me strength to step out the door, and now I\'m calling all my friends and hitting the dance floor.</textarea>';
	bigLongString +='<p><a href="javascript:openCompSpell();" class="spellCheckIcon"><img src="'+imagesPrefix+'ico/spellcheck.gif" alt="spellcheck" /></a><span><a href="javascript:dynPop.turnOff();">Cancel</a> <input type="button" value="Send" id="compSubmitButton" onclick="dynPop.ajaxFormSubmit(\''+ userID +'\',\''+ reviewID +'\');"></span><input type="text" readonly="readonly" id="compFormStatus" name="compFormStatus" value="Status: Ready"></input></p></form><img src="'+comPopBtm.src+'" id="comBtm">';
	
	dynPop.dynPopEl(bigLongString);			
	}else{
	window.location = myLink.href;
	}	
},
doSendMessPop:function(myLink,userID,userName){
var xmlHttpReq = Ajax.getTransport();
findPosition(myLink);
	if(xmlHttpReq){
	var sendMessString = '<img src="'+comPopTop.src+'" id="comTop"><h4>Type your message to '+userName+' below:</h4><form id="compForm" name="compForm">';
	sendMessString += '<label for="messSubject" style="font-size:11px;font-weight:bold;color:#C41200;">Subject:</label> <input name="messSubject" id="messSubject"><br/><textarea id="sendMessage" name="message" maxchar="100"></textarea>';
	sendMessString += '<p><a href="javascript:openCompSpell();" class="spellCheckIcon"><img src="'+imagesPrefix+'ico/spellcheck.gif" alt="spellcheck" /></a><span><a href="javascript:dynPop.turnOff();">Cancel</a> <input type="button" value="Send" id="compSubmitButton" onclick="dynPop.submitMess(\''+userID+'\');"></span><input type="text" readonly="readonly" id="compFormStatus" name="compFormStatus" value="Status: Ready"></input></p></form><img src="'+comPopBtm.src+'" id="comBtm">';
	dynPop.dynPopEl(sendMessString);		
	}else{
		window.location = myLink.href;
	}
},
dynPopEl:function(innerContent){
	if(!dynPop.popIsOn){
	dynPop.thePop = document.createElement('div');
	dynPop.thePop.setAttribute('id','comPop');
	dynPop.nastySelectBox = document.getElementsByTagName('select');
	
	dynPop.thePop.innerHTML = innerContent;
	document.body.appendChild(dynPop.thePop);	
	if((document.body.clientWidth-posX)<350){
			dynPop.thePop.style.left = (posX-290) + "px";	
		}else{
			dynPop.thePop.style.left = (posX-10) + "px";
		}
		if(posY>234){
			dynPop.thePop.style.top = (posY - 234) + "px";
		}else{
			dynPop.thePop.style.top = (posY + 20) + "px";
		}
	new Draggable('comPop',{trans:false}); // This 'trans:false' is custom-hacked into prototype.js (avoids IE wierdness w/ transparent content). Will need to migrate if we upgrade.
	dynPop.popIsOn = true;
/*@cc_on
	/*@if (@_jscript_version <= 5.6)
		if(dynPop.nastySelectBox.length>0){
			for(var x=0;x<dynPop.nastySelectBox.length;x++){
				dynPop.nastySelectBox[x].style.visibility = 'hidden';
			}
		}
	/*@end		
@*/
	}
	else{
	dynPop.turnOff();
	}
},
turnOff:function(){
	document.body.removeChild(dynPop.thePop);
	dynPop.thePop = null;
	dynPop.popIsOn = false;
	dynPop.formStateChange = false;
/*@cc_on
	/*@if (@_jscript_version <= 5.6)
		if(dynPop.nastySelectBox.length>0){
			for(var x=0;x<dynPop.nastySelectBox.length;x++){
				dynPop.nastySelectBox[x].style.visibility = 'visible';
			}
		}
	/*@end		
@*/
},
ajaxFormSubmit:function(userID, reviewID){
	dynPop.compFormMessage = document.compForm.message;
	dynPop.compText = dynPop.compFormMessage.value; 
	var tehButtonz = document.compForm.elements["type"];
	for (var i=0;i<tehButtonz.length;i++)
	{
		if (tehButtonz[i].checked){
			dynPop.compType = tehButtonz[i].value;
		}
	}
	
    if (dynPop.compText != "" || dynPop.compText.length != 0){
		dynPop.compDict = {'action_add2': 1, 'userid':userID, 'review_id':reviewID, 'type': dynPop.compType, 
		'message': dynPop.compText, 'nocache': (new Date()).getTime()} ;	
		dynPop.compFormButton = document.getElementById('compSubmitButton');
		dynPop.compFormButton.disabled = true;
		document.compForm.compFormStatus.value = "Status: Sending...";				
		var opt = {
			 method: 'post',
			 postBody: xmlhttpreq_encode_dict(dynPop.compDict),
			 onSuccess: dynPop.handleCompResponse,
			 on404: serverNotFound,
			 onFailure: serverError
		};
		(new Ajax.Request('/thanx', opt));
		
	} else {
		alert('Please enter some text');
	}
},
submitMess:function(userID){
	dynPop.compFormSubject = document.compForm.messSubject;
	dynPop.compFormMessage = document.compForm.message;
	dynPop.compText = dynPop.compFormMessage.value;
	dynPop.compSub = dynPop.compFormSubject.value;
	
    if (dynPop.compText != "" || dynPop.compText.length != 0){
		dynPop.compDict = {'action_send_message': 1,'async':'true', 'dst':userID,  
		'subject':dynPop.compSub, 'message': dynPop.compText, 'nocache': (new Date()).getTime()} ;
		dynPop.compFormButton = document.getElementById('compSubmitButton');
		dynPop.compFormButton.disabled = true;
		document.compForm.compFormStatus.value = "Status: Sending...";		
		var opt = {
			 method: 'post',
			 postBody: xmlhttpreq_encode_dict(dynPop.compDict),
			 onSuccess: dynPop.handleMessResponse,
			 on404: serverNotFound,
			 onFailure: serverError
		};
		(new Ajax.Request('/mail', opt));
	} else {
		alert('Please enter some text');
	}
},
populate:function(msg) {
	var tgt = document.compForm.message;	
	if(dynPop.formStateChange!=true){
		tgt.value = msg;
	}
},
setFormTrue:function(){dynPop.formStateChange=true;},
handleCompResponse:function(req) {
    handleMatrix(req.responseText,
	comPopEmpty,
	function(reply){
	document.compForm.compFormStatus.value = "Status: Success! Compliment Sent.";
	document.compForm.compFormStatus.style.color = "green";
	setTimeout(dynPop.turnOff,1900);
	},
	comPopFail);
},
handleMessResponse:function(req) {
    handleMatrix(req.responseText,
	comPopEmpty,
	function(reply){
	document.compForm.compFormStatus.value = "Status: Success! Message Sent.";
	document.compForm.compFormStatus.style.color = "green";
	setTimeout(dynPop.turnOff,1900);
	},
	comPopFail);
}
}

function openCompSpell() {
	var txt = document.compForm.message;
	var speller = new spellChecker( txt );
	speller.openChecker();
}


//generic response handling
function handleMatrix(reqText,emptyFunction,successFunction,failFunction){
var reply = JSON.parse(reqText);
	if (!reply){ 
		emptyFunction();
	}else if (reply.success){
		successFunction(reply);
	}else{
		failFunction(reply);
	}
}
function comPopEmpty(){
	document.compForm.compFormStatus.value = "Error: An undefined error occurred.";
	document.compForm.compFormStatus.style.color = "red";
	document.compForm.disabled = false;
}
function comPopFail(reply){
	document.compForm.compFormStatus.value = "Status: Error!";
	document.compForm.compFormStatus.style.color = "red";
	alert(reply.msg);
	document.compForm.disabled = false;
	dynPop.compFormButton.value = "Go";
}
function serverNotFound(){
	alert('404: No response from server.');
} 
function serverError(){
	alert('Server error! Please try again later.');
}

/* Start user_details_thanx compliment approve/deny code.
*********************************************************/
var compHandle = {
approveComp:function(actionAnchor,thanxID,userID,thanxType){
compHandle.itemDiv = actionAnchor.parentNode.parentNode.parentNode.parentNode;
compHandle.bigThanks = thanxType;
var xmlHttpReq = Ajax.getTransport();
	if(xmlHttpReq){
		var myDict = {'action_approveAsync': 1, 'thanx_id':thanxID, 'userid':userID, 'nocache': (new Date()).getTime()} ;
		compHandle.approveLink = actionAnchor.parentNode;
		compHandle.linkBackup = compHandle.approveLink.innerHTML;
		compHandle.approveLink.innerHTML = 'Saving...';
		var opt = {
			 method: 'post',
			 postBody: xmlhttpreq_encode_dict(myDict),
			 onSuccess: compHandle.handleApproveResponse,
			 on404: serverNotFound,
			 onFailure: serverError
		};
		(new Ajax.Request('/thanx', opt));
		}else{
			window.location = actionAnchor.href;
		}
	},
handleApproveResponse:function(req) {
    handleMatrix(req.responseText,
		function(){
			alert('No reply from server! Please try again later.');
			compHandle.approveLink.innerHTML = linkBackup;
		},
		function(){
			compHandle.moveComp();
			var thxTypeCont = document.getElementById('userComplimentIcons');
			var die = thxTypeCont.getElementsByTagName('span');
			for(var i=0;i<die.length;i++){
				if(die[i].className.match(compHandle.bigThanks)){
				var compTypeCount = die[i].innerHTML;
				compTypeCount.replace("(","");
				compTypeCount.replace(")","");
				compTypeCount = eval(compTypeCount)+1;		
				die[i].innerHTML = "("+compTypeCount+")";
				}
				//else{
				//	var newThanks = '<span style="float:left;margin-right:3px;"><img src="/i/new/ico/thanks_.gif" alt="compliment icon" class="alignmid"/><br/><span class="miniOrange "'+compHandle.bigThanks+'>(1)</span><br/></span>';
				//}
			}
		},
		function(reply){
			alert('Error: '+reply.msg+' Please try again later.' );
			approveLink.innerHTML = linkBackup;
		}
		);
	},
moveComp:function(){
	myFadeSize = new fx.Height(compHandle.itemDiv.id, {duration:400});
	myFadeSize.toggle();	
	window.setTimeout("document.getElementById('holder').appendChild(compHandle.itemDiv)",500);
	window.setTimeout("myFadeSize.toggle('height')",600);
	//twice for cross-browser compat
	window.setTimeout("compHandle.itemDiv.setAttribute('className','approvedComp')",800);
	window.setTimeout("compHandle.itemDiv.setAttribute('class','approvedComp')",800);
	compHandle.approveLink.innerHTML = 'Saved!';
	//setting these here avoids moo.fx display issues
	window.setTimeout("document.getElementById(compHandle.itemDiv.id).style.overflow = 'visible'",900);	
	//window.setTimeout("document.getElementById(compHandle.itemDiv.id).style.position = 'relative'",900);
	}
}

////////////////////////
// Bookmark functions //
////////////////////////
function addBookMark(actionAnchor,flag,itemID,reviewID){
	findPosition(actionAnchor);
	if(!reviewID){reviewID='';}
	var xmlHttpReq = Ajax.getTransport();
	if(xmlHttpReq){
	if(flag=='biz'){	var myDict = {'action_add_biz': 1, 'biz_id':itemID, 'review_id':reviewID, 'nocache': (new Date()).getTime()} ; }
		else if(flag=='user')
		{	var myDict = {'action_add_user': 1, 'user_id':itemID, 'nocache': (new Date()).getTime()} ; } else {alert('Invalid action!');}		
		ajaxStatusMessage('Saving...');		
		var opt = {
			 method: 'post',
			 postBody: xmlhttpreq_encode_dict(myDict),
			 onSuccess: handleBookmarkResponse,
			 on404: serverNotFound,
			 onFailure: serverError
		};
		(new Ajax.Request('/bookmark', opt));
		}else{
		window.location = actionAnchor.href;
		}
}
function ajaxStatusMessage(mess){
	var d = document.createElement('div');
	d.setAttribute('id','ajaxStatusMessage');
	d.innerHTML = '<img src="'+imagesPrefix+'gfx/stat_mess_lft.gif"><p>'+mess+'</p><img src="'+imagesPrefix+'gfx/stat_mess_rt.gif">';
	document.body.appendChild(d);
		d.style.left = (posX) + "px";
		d.style.top = (posY - 45) + "px";
}
function handleBookmarkResponse(req){
	handleMatrix(req.responseText,
		function(){alert('empty');},
		function(reply){document.getElementById('ajaxStatusMessage').innerHTML='<img src="'+imagesPrefix+'gfx/stat_mess_lft.gif"><p>'+reply.msg+'</p><img src="'+imagesPrefix+'gfx/stat_mess_rt.gif">';window.setTimeout("document.body.removeChild(document.getElementById('ajaxStatusMessage'));",1500);},
		function(reply){alert('Error:'+reply.msg);}
	);
}

//////////////////////////////////////////////
// Category Picker functions on Biz Details //
//////////////////////////////////////////////
	function categoryPicker(aLink){
	var xmlHttpReq = Ajax.getTransport();
		if(xmlHttpReq){
		findPosition(aLink.parentNode);		
		document.getElementById('catBox').style.cssText='top:'+posY+'px;left:'+posX+'px;';
		ogCats = document.getElementById('biz_detailsnewCats').innerHTML;
		if(!biz_detailscategory_map.loaded){
		var myAjax = new Ajax.Request(
			'/biz_attribute?action_cat_tree=1', 
			{
				method: 'get',
				onComplete: function(req){
				biz_detailscategory_map = JSON.parse(req.responseText);
				biz_detailscategory_map['loaded'] = true;
				//must re-evaluate JSON'd string to array
				for(var i in biz_detailscategory_map){
					biz_detailscategory_map[i].children = eval(biz_detailscategory_map[i].children);
				}
				
				document.getElementById('biz_detailscategory_box').replaceChild(biz_detailsdraw_category(initIds, 'Choose One'),document.getElementById('loadingspan'));
				}
			});	
			
			var biz_detailsadiv = document.createElement('div');
			biz_detailsadiv.style.paddingTop="5px";
			document.getElementById('biz_detailscategory_box').appendChild(biz_detailsadiv);
			}
		}else{
			window.location = aLink.href;
		}
	}
	function closeCats(){
		document.getElementById('catBox').style.left='-999em';
		document.getElementById('biz_detailsnewCats').innerHTML = ogCats;
	}
	function updateCats(aLink,bizid){
		var form_modified = false;
		var xmlHttpReq = Ajax.getTransport();
		var inputs_in_form = document.cats_update.getElementsByTagName('input');
		var cats_in_form = [];
		for(var o=0;o<inputs_in_form.length;o++){
			if(inputs_in_form[o].name=='biz_details_categories'){
				cats_in_form.push(inputs_in_form[o]);
			}
		}		
		var tempDiv = document.createElement('div');
		tempDiv.innerHTML = ogCats;
		var cats_at_start = tempDiv.getElementsByTagName('input');
		
		function _submitForm(){
		
			if(xmlHttpReq){
				if(form_modified){
					var biz_cats = 'biz_id='+bizid+'&action_submit_cats=1&async=1&nocache='+ (new Date()).getTime();
					var tehElements=document.cats_update.getElementsByTagName('input');
					for(var i=0;i<tehElements.length;i++){
						if(tehElements[i].name=='biz_details_categories'){
							biz_cats+='&biz_details_categories='+encodeURIComponent(tehElements[i].value);	
						}else if(tehElements[i].type=='button'){
							tehElements[i].disabled=true;
						}
					}					
					var opt = {
					 method: 'post',
					 postBody: biz_cats,
					 onSuccess: handle_cat_reply,
					 on404: serverNotFound,
					 onFailure: serverError
					};
					(new Ajax.Request('/biz_attribute', opt));					
				}else{
					ajaxStatusMessage('Nothing changed.');				
					window.setTimeout("document.body.removeChild(document.getElementById('ajaxStatusMessage'));",2000);
				}
			}else{			
				document.cats_update.submit();
			}
			
		}
		if(document.cats_update.elements['biz_details_categories']){
			if(cats_in_form.length==cats_at_start.length){
				for(var x=0;x<cats_in_form.length;x++){
					if(cats_in_form[x].value!=cats_at_start[x].value){
						form_modified = true;
						break;
					}
				}				
				_submitForm();
			}else{				
				form_modified = true;
				_submitForm(); 
			}
		}else{
			ajaxStatusMessage('Please add some categories before submitting.');
			window.setTimeout("document.body.removeChild(document.getElementById('ajaxStatusMessage'));",2000);			
		}			
	}
	function handle_cat_reply(requesty) {	
		var tehElements=document.cats_update.getElementsByTagName('input');
		function enableButtons(){		
			for(var i=0;i<tehElements.length;i++){
				if(tehElements[i].type=='button'){
					tehElements[i].disabled=false;
				}
			}
		}
		reply = JSON.parse(requesty.responseText);
		if (!reply){
			alert('Error: no response from server.');
			enableButtons();
		}else if (reply.success){
			document.getElementById('catBox').style.left='-999em';
			posY = posY+40;
			ajaxStatusMessage(reply.msg);
			window.setTimeout("document.body.removeChild(document.getElementById('ajaxStatusMessage'));",2000);
			enableButtons();
			//start formatting for catgeory links on page
			if(reply.status){
				document.getElementById('cat_display').innerHTML = '';
				for(var x=0;x<tehElements.length;x++){
					if(tehElements[x].name=='biz_details_categories'){
						document.getElementById('cat_display').innerHTML+='<a href="/search?find_loc='+bizLocation+'&amp;radius=15&amp;cflt='+biz_detailscategory_map[tehElements[x].value].alias+'&amp;start=0">'+biz_detailscategory_map[tehElements[x].value].title+'</a>';
						if(document.cats_update.elements['biz_details_categories'].length>1){document.getElementById('cat_display').innerHTML+=', ';}
					}
				}
			}
		}else{
			alert('Error: '+reply.msg);
			enableButtons();
		}
	}
