// JavaScript Document

var toolTip = null;
var cityDataSet = null;
var cityAutoComplete = null;
var FilterModule = null;
var SortModule = null;
var showSortRegion = null;
var showFilterRegion = null;
var hiddenField = null; // for city auto complete submit
var LocationModule = null; 
var showLocationRegion = null; 
var PictureModule = null;
var CityPickerModule = null;
var startComment = -1;

var MagModule = null;
var bigImageOut = 1;
var overImage = 0;
var praiseID = 0;

// decode html entities
function get_ents(str)
{
	var temp=document.createElement("pre");
	temp.innerHTML=str;
	return temp.firstChild.nodeValue;
}

// ----------------------------------------------------For Loading Container --------------------------------------------
var LoadingContainer = 
		new YAHOO.widget.Panel("loadingDialog",  
			{ width:"80px", 
			  fixedcenter:true, 
			  close:false, 
			  draggable:false, 
			  zindex:15000,
			  modal:false,
			  visible:false
			} 
	);
// ------------------------------------ Delete Comment -----------------------------------------------------------
var deleteCommentStart = function(o)
{ 
	LoadingContainer.show();
};
var deleteCommentSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		prepareFilter();							
	}
};
var deleteCommentFailure = function(o)
{ 
	LoadingContainer.hide();
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};

function deleteComment(comment_id)
{
	var callback = 
	{
		success: deleteCommentSuccess,
		failure: deleteCommentFailure,
		customevents: { onStart: deleteCommentStart },
		timeout: 20000
	}
		
		YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
		var cObj = YAHOO.util.Connect.asyncRequest('POST', '/deletecomment_s.php', callback, 'commentID='+comment_id); 	
}

// ---------------------------------------block comment ---------------------------------------------------

var blockCommentSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		prepareFilter();							
	}
};
var blockCommentFailure = function(o)
{ 
	LoadingContainer.hide();
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};

function blockComment(comment_id)
{
	var callback = 
	{
		success: blockCommentSuccess,
		failure: blockCommentFailure,
		customevents: { onStart: deleteCommentStart },
		timeout: 20000
	}
		
		YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
		var cObj = YAHOO.util.Connect.asyncRequest('POST', '/blockcomment_s.php', callback, 'commentID='+comment_id); 	
}

// ------------------------------------ Report Abuse -----------------------------------------------------------

var reportAbuseStart = function(o)
{ 
	LoadingContainer.show();
};
var reportAbuseSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		wineWarning("Thank you for reporting abuse.  We will review this posting.");	
	}
};
var reportAbuseFailure = function(o)
{ 
	LoadingContainer.hide();
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};

function reportAbuse(comment_id)
{
	var callback = 
	{
		success: reportAbuseSuccess,
		failure: reportAbuseFailure,
		customevents: { onStart: reportAbuseStart },
		timeout: 20000
	}
	
	YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/reportabuse_s.php', callback, 'commentID='+comment_id+'&type=2'); 	
}

// -------------------------- get comments (using summarized links on bottom of page------------------------------------
function getComments(comment_id)
{
	startComment = comment_id;
	prepareFilter();
}


// ------------------------------------ Post Comment -----------------------------------------------------------
var postCommentStart = function(o)
{ 
	LoadingContainer.show();
};
var postCommentSuccess = function(o)
{ 
	LoadingContainer.hide();
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		if (twitterName.length > 0 && document.getElementById("TweetTalk").checked)
		{		
			tweetComment(Response);
		}
		prepareFilter();
		document.getElementById("commentText").value = ""; // clear comment text
	}
};
var postCommentFailure = function(o)
{ 
	LoadingContainer.hide();
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};

function postComment()
{
	comment = document.getElementById("commentText").value;
	if (comment.length > 0 && comment!="Enter your comment")
	{
		var callback = 
		{
			success: postCommentSuccess,
			failure: postCommentFailure,
			customevents: { onStart: postCommentStart },
			timeout: 30000
		}
		
		comment = comment.replace("&", "%26");
		YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
		var cObj = YAHOO.util.Connect.asyncRequest('POST', '/postcomment_s.php', callback, 'comment='+comment+'&type=2'); 	
	}
}

// ------------------------------------ Comments -----------------------------------------------------------
	
var commentsStart = function(o)
{ 
	LoadingContainer.show();
};
var commentsSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		document.getElementById("comments").innerHTML = o.responseText;
		
	}
	LoadingContainer.hide();
};
var commentsFailure = function(o)
{ 
	LoadingContainer.hide();
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};
	
		
// ----------------------------------------------------------------------------------------------------------------------
var handleOK = function() 
{
	wineWarningDialog.hide();
	LoadingContainer.hide();
};

var wineWarningDialog = new YAHOO.widget.SimpleDialog("warningDialog", 
						{	 
						width: "350px", 
//							effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}, 
							fixedcenter:true,
					    	zIndex:15000,
					  		modal: true,
	              			constraintoviewport : true, 
						    visible:false,
							draggable:false, 
							buttons: [ { text:"OK", handler:handleOK, isDefault:true }]
						});	


var wineWarning = function(warningText)
{
	wineWarningDialog.setHeader("<div class=\"hd\"><div class=\"tl\"></div><span>Wine Talk Issue</span><div class=\"tr\"></div></div>");

	var bodyText = '<div class="dialogWrap"><div class="column_D"><table class="warningFormat" border="0" cellspacing="0" cellpadding="0"><tr><td>' + warningText + '</td></tr></table></div></div>';
	
	wineWarningDialog.setBody(bodyText);
	wineWarningDialog.render(document.body);		
	wineWarningDialog.show();
};

function zipSubmit()
{
	zipValue = document.getElementById("ZipEdit").value;
	cityValue = document.getElementById("CityEdit").value;
	
	if (zipValue.match(/^[0-9]{5}$/))
		window.location = "/winetalk/"+zipValue;
	else if (cityValue != 'Enter City' && cityValue.match(/^[a-zA-Z](([a-zA-Z])|(\s))+$/))  // starts with a letter, then can include letters or spaces
		window.location = "/winetalk/"+escape(cityValue);	
	else
		wineWarning("The zip code or city you entered appears to be invalid. When entering a city name, please do not enter the state as well, but rather select the appropriate city from the autocomplete drop down box.");
}

function showEventLocation()  
{
	if (!LocationModule.cfg.getProperty("visible"))
	{
		LocationModule.show();
		showLocationRegion.show();
	}
	else
	{
		LocationModule.hide();
		showLocationRegion.hide();
	}
	document.getElementById("showLocationRegion").className = 'tabText';
}

function regionMouseOver(e, imageElement)
{
	this.className = 'tabTextOver'; 
	imageElement.src = DownArrowGray.src;
}
function regionMouseOut(e, imageElement)
{
	this.className = 'tabText'; 
	imageElement.src = DownArrow.src;
}
function regionMouseOverUp(e, imageElement)
{
	this.className = 'tabTextOver'; 
	imageElement.src = UpArrowGray.src;
}
function regionMouseOutUp(e, imageElement)
{
	this.className = 'tabText'; 
	imageElement.src = UpArrow.src;
}
// format text display in autocomplete select box
var cityFormat = function(oResultData, sQuery, sResultMatch) 
{ 
	return oResultData.city + ", " + oResultData.state;
}
var dataErrorHandler  = function( oSelf , sQuery ) 
{
	wineWarning("There was a communication error or your session timed out. Please refresh the page and try again.");
};
// call page with new zip when an autocomplete selection is made
var itemSelected = function (sTyle, aArgs)
{
	var DataObj = aArgs[2]; // 0 is the AC instance, 1 the LI element
	document.getElementById("hiddenField").value = DataObj.zip; // don't seem to need this line...
	window.location = "/winetalk/"+DataObj.zip;
};
// ------------------------------------ Zoom for Images ----------------------------------------------

// when they clicked on a zoomed in event image
function wineImageOut()
{
	bigImageOut = 1;
	document.getElementById("bigImage").style.cursor = "default";
	document.getElementById("picMod").style.cursor = "default";
	PictureModule.hide();
}

var magnifyOver = function()
{
	timeoutID = setTimeout("magnifyStillIn()",500);
	overImage = 1;
	document.getElementById("magnifyImg").src='/wineempty.gif';
};
var magnifyOut = function(o)
{
	document.getElementById("magnifyImg").style.cursor = "url('/magcursor.cur'), default";
	document.getElementById("magnifyImg").src='/wineempty.gif';
	overImage = 0;
	clearTimeout(timeoutID);
};
function magnifyStillIn()
{
	wineBigImageIn();
	overImage = 2;
}

var wineSmallImageOut = function(o)
{
	document.getElementById("magnifyImg").src='/wineempty.gif';
};

var wineImageLoaded = function(o)
{
	PictureModule.show();	
};

// show zoomed in event image
function wineImageIn(imageElement, bigImage)
{
	bigImageFile = bigImage;
	xyID = imageElement.id;
	x = YAHOO.util.Dom.getX(xyID);
	y = YAHOO.util.Dom.getY(xyID);
	
	PictureModule.cfg.setProperty("x", x);
	PictureModule.cfg.setProperty("y", y);
	
	if (bigImageOut == 0)  // if it's 0, then we never left the zoom feature, so load the new image.
	{
		wineBigImageIn();
	}
	else
	{
		MagModule.cfg.setProperty("x",x+50);
		MagModule.cfg.setProperty("y",y+50);	
	MagModule.setBody("<div class=\"magModule\"><img id='magnifyImg' onmouseover='magnifyOver();' onmouseout='magnifyOut();' onclick='wineBigImageIn();' src='/macgif2.gif'></div>");
		MagModule.render(document.body);													  
		MagModule.show();
	}
}
var wineBigImageIn = function()
{		
	bigImageOut = 0;
	PictureModule.setBody("<div id=\"picMod\" class=\"pictureModule\"><img id=\"bigImage\" src=\""+bigImageFile+"\" /></div>");
	document.getElementById("bigImage").style.cursor = "url('zoomout.cur'), default";
	document.getElementById("picMod").style.cursor = "url('zoomout.cur'), default";
	YAHOO.util.Event.addListener("bigImage", "load", wineImageLoaded);   // once the wine image is loaded, we're good to show
	document.getElementById("magnifyImg").style.cursor = "url('zoomout.cur'), default";
};

// --------------------------------------------------------------------------------
function cityChoose(cityImage)
{
	if (CityPickerModule.cfg.getProperty("visible"))
		CityPickerModule.hide();
	else
	{
		xyID = cityImage.id;
		x = YAHOO.util.Dom.getX(xyID);
		y = YAHOO.util.Dom.getY(xyID);
		
		CityPickerModule.cfg.setProperty("x", x+1);
		CityPickerModule.cfg.setProperty("y", y+17);
		CityPickerModule.render();
		CityPickerModule.show();		
	}
}
function cityPickerOut()
{
	CityPickerModule.hide();
};

// --------------------------------------------------------------------------------
function sortChange(e)
{
	prepareFilter();
}

var DownArrowGray = new Image;
var DownArrow = new Image;
DownArrow.src="/Images/downarrow.gif";
DownArrowGray.src="/Images/downarrowgray.gif";
var UpArrowGray = new Image;
var UpArrow = new Image;
UpArrow.src="/Images/uparrow.gif";
UpArrowGray.src="/Images/uparrowgray.gif";


// ---------------------------------------------Twitter / FB ---------------------------------------------

var praiseDeal = function(commentID)
{
	praiseID = commentID;
	var callback = 
	{
		success: praiseDealSuccess,
		failure: filterFailure,
		customevents: { onStart: filterStart },
		timeout: 30000
	}

	YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/praisedeal_s.php', callback, 'commentID='+commentID); 
	return false;					
};

var praiseDealSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		document.getElementById("wineDeal"+praiseID).innerHTML = Response;
	}
	LoadingContainer.hide();
};


var reTweet = function(commentID)
{
	var callback = 
	{
		success: reTweetSuccess,
		failure: filterFailure,
		customevents: { onStart: filterStart },
		timeout: 30000
	}

	YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/retweet_s.php', callback, 'commentID='+commentID); 
	return false;					
};

var reTweetSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		document.getElementById("commentText").value = get_ents(Response);
		countChars();
		window.location = "#SayAnchor";
	}
	LoadingContainer.hide();
};

var tweetSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	LoadingContainer.hide();
};

var tweetComment = function(commentID)
{
	var callback = 
	{
		success: tweetSuccess,
		failure: filterFailure,
		customevents: { onStart: filterStart },
		timeout: 30000
	}
	comment = document.getElementById("commentText").value;
	comment = comment.replace("&", "%26");

	YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/tweetcomment_s.php', callback, 'comment='+comment+'&commentID='+commentID); 
	return false;					
};

var publishSuccess = function(o)
{ 
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	LoadingContainer.hide();
};

var permissionResult = function(permissions)
{
	wineWarning("Facebook permissions should now be granted. Please re-Post the comment to complete!");	
};

var FBPermission = function(hasPermission)
{
	var comment = document.getElementById("commentText").value;

	if (hasPermission)
	{
		var callback = 
		{
			success: publishSuccess,
			failure: filterFailure,
			customevents: { onStart: filterStart },
			timeout: 30000
		}
//		comment = comment.replace("&", "%26");
	
		YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
		var cObj = YAHOO.util.Connect.asyncRequest('POST', '/fbstreamtalk_s.php', callback, 'comment='+comment+'&twitterName='+twitterName); 

		postComment();				

		return false;						
	}
	else
	{
		FB.Connect.showPermissionDialog('publish_stream', permissionResult, true, null);
	}
};

var load_feed = function()
{
	if (facebookLoggedIn && document.getElementById("FacebookTalk").checked)
	{
	    FB.Facebook.apiClient.users_hasAppPermission('publish_stream', FBPermission);
	}
	else if (document.getElementById("FacebookTalk").checked && !facebookLoggedIn)
	{
		FB.Connect.requireSession(facebook_onlogin);	
	}
	else postComment();	
}

function facebook_onlogin()
{
	window.location = "https://www.winemcgee.com/connect.php";
}

var countChars = function(e)
{
	if (userID != -1)
	{
		var count = document.getElementById("commentText").value.length;
		document.getElementById("charcount").innerHTML = count;
	}
}
//------------------------- filter / show more comments --------------------------------------------

function prepareFilter()
{
	var callback = 
	{
		success:filterSuccess,
		failure:filterFailure,
		customevents: { onStart: filterStart },
		timeout: 30000
	};
	
	var postText = "";
	
	if (zipCodeSet)
		postText = postText + "zip=" + zipCode + "&";
		
	if (startComment != -1)
	{
		postText = postText + "commentStart=" + startComment + "&";		
		startComment = -1;
	}

	YAHOO.util.Connect.initHeader('X-Signature', transaction_sig); 
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/winetalkfilter_s.php', callback, postText); 
	return false;
}
var filterStart = function(o)
{ 
	LoadingContainer.show();
};
var filterSuccess = function(o)
{ 
	LoadingContainer.hide();
	var Response = o.responseText;
	if (Response.substring(0,7) == "[error]")
	{
		wineWarning(Response.substring(7,Response.length));	
	}
	else
	{
		document.getElementById("comments").innerHTML = o.responseText;
	}
};
var filterFailure = function(o)
{ 
	wineWarning("There was a communication error on the WineMcGee servers. Please try again later.");
};

// ---------------------------- Show location selector---------------------------------------------


function yourCity()
{
	LocationModule.show();
	showLocationRegion.show();
}
// --------------------------------------------- Init ---------------------------------------------

function init()
{
//  LoadingContainer.setHeader("<div class=\"hd\"><div class=\"tl\"></div><span>Loading - Please Wait</span><div class=\"tr\"></div></div>");
	LoadingContainer.setBody('<img src="/Images/ajaxload.gif" />');
	LoadingContainer.render(document.body);

	LocationModule = new YAHOO.widget.Module("getLocalRegion", { visible: false });  
	LocationModule.render();   
	showLocationRegion = new YAHOO.widget.Module("showLocationRegion", { visible: false });  
	showLocationRegion.render();   
	YAHOO.util.Event.addListener("showLocationRegion", "mouseover", regionMouseOverUp, document.getElementById("upArrowLocation"));
	YAHOO.util.Event.addListener("showLocationRegion", "mouseout", regionMouseOutUp, document.getElementById("upArrowLocation"));

	YAHOO.util.Event.addListener("zipSubmit", "click", zipSubmit);

    cityDataSet = new YAHOO.util.XHRDataSource("/citysearch.php");
    cityDataSet.responseType = YAHOO.util.DataSource.TYPE_XML;
    cityDataSet.responseSchema = 
	{
        resultNode: "location",
		fields: 
		[ 
			"city" ,
			"state",
			"zip" 	
		]
    };
	
	cityAutoComplete = new YAHOO.widget.AutoComplete("CityEdit", "cityAutoContainer", cityDataSet);
	cityAutoComplete.resultTypeList = false; 
	cityAutoComplete.formatResult = cityFormat;
	cityAutoComplete.dataErrorEvent.subscribe(dataErrorHandler);
	cityAutoComplete.itemSelectEvent.subscribe(itemSelected);	
	
// -------- overlay for picture expand ------------------------
    PictureModule = new YAHOO.widget.Overlay("picture1", { 
										  xy:[-2000,-2000],	
								  		  effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.40},
										  visible:false 
  	 								      });   	
										  												  
	PictureModule.setBody("<div id=\"picMod\" class=\"pictureModule\"></div>");
	PictureModule.render(document.body);													  
	YAHOO.util.Event.addListener("picture1", "click", wineImageOut);
	YAHOO.util.Event.addListener("picture1", "mouseOut", wineImageOut);
	PictureModule.cfg.setProperty("zindex", 99999);
	
    MagModule = new YAHOO.widget.Overlay("magnify", { 
										  xy:[-2000,-2000],	
										  visible:false 
  	 								      });   	

	MagModule.cfg.setProperty("zindex", 88888);
	MagModule.setBody("<div class=\"magModule\"><img id='magnifyImg' onmouseover='magnifyOver();' onmouseout='magnifyOut();' onclick='wineBigImageIn();' src='/macgif2.gif'></div>");
	MagModule.render(document.body);	
	
	YAHOO.util.Event.addListener("sort1", "click", sortChange);
	YAHOO.util.Event.addListener("sort2", "click", sortChange);
	YAHOO.util.Event.addListener("sort3", "click", sortChange);
	YAHOO.util.Event.addListener("sort4", "click", sortChange);
	
	YAHOO.util.Event.addListener("commentSubmit", "click", load_feed);
	

// -------- city picker ------------------------

    CityPickerModule = new YAHOO.widget.Overlay("cityPicker", { 
										  xy:[-2000,-2000],	
										  visible:false 
  	 								      });   	

	CityPickerModule.setBody("<div id=\"cityPickerMod\" onclick=\"cityPickerOut();\" class=\"tweetCities\"><p class=\"glo under\"><a href=\"/winetalk/00000\">GLOBAL</a></p><p class=\"chi under\"><a href=\"/winetalk/chicago\">CHICAGO</a></p><p class=\"det under\"><a href=\"/winetalk/detroit\">DETROIT</a></p><p class=\"hou under\"><a href=\"/winetalk/houston\">HOUSTON</a></p><p class=\"la under\"><a href=\"/winetalk/los-angeles\">LOS ANGELES</a></p><p class=\"nyc under\"><a href=\"/winetalk/new-york\">NEW YORK</a></p><p class=\"phi under\"><a href=\"/winetalk/philadelphia\">PHILLY</a></p><p class=\"por under\"><a href=\"/winetalk/portland\">PORTLAND</a></p><p class=\"sa under\"><a href=\"/winetalk/san-antonio\">SAN ANTONIO</a></p><p class=\"sd under\"><a href=\"/winetalk/san-diego\">SAN DIEGO</a></p><p class=\"sf underDark\"><a href=\"/winetalk/san-francisco\">SAN FRANCISCO</a></p><p class=\"yourZip\"><a href=\"#\" onclick=\"yourCity(); return false;\">OR YOUR CITY</a></p><p class=\"yourZipExplain\">Click to localize WineMcGee by entering your city or zip code.</p></div>");
	CityPickerModule.render(document.body);													  
	CityPickerModule.cfg.setProperty("zindex", 99999);
				
}
YAHOO.util.Event.onDOMReady(init);
