//************************************** HELPERS *****************************************************//

function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}

function num_to_month(num){
	var nmonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	
	return nmonth[num-1].substring(0,3);
}

function parseDate(input, format) {
	format = format || 'yyyy-mm-dd'; // default format
	var parts = input.match(/(\d+)/g), 
	i = 0, fmt = {};
	// extract date-part indexes from the format
	format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });
	
	return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

function trim2Word(p,len){
	var tempStr = p.substring(0,len);
	var tempArr = tempStr.split(" ");
	return p.substring(0, len - tempArr[tempArr.length-1].length - 1)
}

function dtConvert(dateStr){
	
	var arr = dateStr.split("-");
	//console.log(parseFloat(arr[1]));
	return num_to_month(parseFloat(arr[1])) + " " + arr[2];
}

//************************************** EVENT HANDLERS *****************************************************//

function showPopup(){
	var ts = new Date().getTime();
	console.log((ts - hlOnTime) + " : {showPopup}: ");
	if(((ts - hlOnTime) < 495)||(hlRestIdx < 0 ) ) { return; }
	console.log((ts - hlOnTime) + " : {showPopup pass}: ");
	
	$('#pop_up').empty();
	$('#pop_up').append("<img class='pop_imgHL' src='" + restArr[hlRestIdx].revArr[hlRevIdx].imgLink  + "'>");
	$('#pop_up').append("<div class='pop_excerpt'>" + restArr[hlRestIdx].revArr[hlRevIdx].excerpt + "</div>");
	$('#pop_up').css({ left: (hlRestIdx * 295 + 400) + "px", top: (hlRevIdx * 30) + 400 + "px", "z-index": 99});
	$('#pop_up').animate({ opacity: 1, left: '-=10' }, 200);
}

function hidePopup(){
	hlRestIdx = -1;
	hlRevIdx = -1;
	$('#pop_up').animate({ opacity: 0, left: '+=10' }, 200);
	//setTimeout(function(){ $('#pop_up').css({ "z-index": -99}); }, 200);
}

function scrollLeftOn(e){
	scrollLeftFlag = 1;
	scrollLeftZone = this.id;
	scrollRightZone = "r" + this.id.substring(1,3);
	scrollPanel = 'slider' + this.id.substring(this.id.length-1,this.id.length);
	
	$('#' + this.id).css('background','#FFD8BA');
	$('#' + this.id).children().first().css('background-position','0px -56px');
	scrollLeft();
	console.log(scrollPanel + " : {mouseover}: scroll left on");
}

function scrollLeftOff(e){
	scrollLeftFlag = 0;
	$('#'  + this.id).css('background','#FFFFFF');
	$('#'  + this.id).children().first().css('background-position','0px 0px');
	console.log(this.id + " : {mouseover}: scroll left off");
}

function scrollRightOn(e){
	scrollRightFlag = 1;
	scrollRightZone = this.id;
	scrollLeftZone = "l" + this.id.substring(1,3);
	scrollPanel = 'slider' + this.id.substring(this.id.length-1,this.id.length);
	
	$('#' + this.id).css('background','#FFD8BA');
	$('#' + this.id).children().first().css('background-position','0px -168px');
	scrollRight();
	console.log(scrollPanel + " : {mouseover}: scroll right on");
}

function scrollRightOff(e){
	scrollRightFlag = 0;
	$('#' + this.id).css('background','#FFFFFF');
	$('#' + this.id).children().first().css('background-position','0px -112px');

	console.log(this.id + " : {mouseover}: scroll right off");
}

function scrollLeft(){
	var timestamp = new Date().getTime();
	var leftPx =($('#' + scrollPanel).css('left').substring(0, $('#' + scrollPanel).css('left').length-2));
	var widthPx = parseFloat($('#container').css('width').substring(0, $('#container').css('width').length-2)) + 200;
	
	console.log("left: start panel : " + Math.floor(-leftPx/214));
	console.log("left: loaded panels : " + Math.floor(widthPx/214));
	
	if(scrollLeftFlag == 1){
		if(leftPx < 0){
			setTimeout("scrollLeft()", 20);
			$('#' + scrollPanel).css('left', '+=15');
			$('#' + scrollLeftZone).css('visibility', 'visible');
			$('#' + scrollLeftZone).css('cursor', 'pointer');
			$('#' + scrollRightZone).css('visibility', 'visible');
		}else{
			$('#' + scrollLeftZone).css('visibility' , 'hidden');
			$('#' + scrollLeftZone).css('cursor', 'default');
		}
	}
}

function scrollRight(){
	var leftPx = parseFloat($('#' + scrollPanel).css('left').substring(0, $('#' + scrollPanel).css('left').length-2));
	var widthPx = parseFloat($('#container').css('width').substring(0, $('#container').css('width').length-2));
	var scrollerWidth = parseFloat($('#' + scrollPanel).css('width').substring(0, $('#' + scrollPanel).css('width').length-2));
	
	console.log(scrollPanel);
	console.log("right: start panel : " + $('#' + scrollPanel).css('left') + " : " + (widthPx) + " / " + scrollerWidth);
	console.log("right: loaded panels : " + Math.floor(scrollerWidth/224));
	
	if(scrollRightFlag == 1){
		if(leftPx > (widthPx - scrollerWidth - 200)){
			setTimeout("scrollRight()", 20);
			$('#' + scrollPanel).css('left', '-=15');
			$('#' + scrollRightZone).css('visibility', 'visible');
			$('#' + scrollRightZone).css('cursor', 'pointer');
			$('#' + scrollLeftZone).css('visibility', 'visible');
		}else{
			$('#' + scrollRightZone).css('visibility', 'hidden');
			$('#' + scrollRightZone).css('cursor', 'default');
		}
	}	
}

function hlOn(e){
	hlRestIdx = this.id.match(/rest(\d+)rev(\d+)/)[1]-1;
	hlRevIdx = this.id.match(/rest(\d+)rev(\d+)/)[2]-1;
	hlOnTime = new Date().getTime();
	
	//setTimeout("showPopup()", 500);
	console.log(hlOnTime + " : {mouseover}: " + this.id);
}


function hlOff(e){
	hidePopup();
	console.log(hlOnTime + " : {mouseoff}: " + this.id);
}

function winFocus(){
	hlOff();
}

function winBlur(){
	pauseRotation = true;
}

function reviewClick(e) {
	console.log(this.id); 
	event.preventDefault();
	event.stopPropagation();
	var artType = this.id.match(/(rest|open)(\d+)rev(\d+)/)[1];
	var restIdx = this.id.match(/(rest|open)(\d+)rev(\d+)/)[2];
	var revIdx = this.id.match(/(rest|open)(\d+)rev(\d+)/)[3];
	
	console.log(restIdx + " " + revIdx);
	if(artType == "rest"){
		window.open(restArr[restIdx].revArr[revIdx].articleLink);
	}else{
		window.open(openArr[restIdx].revArr[revIdx].articleLink);	
	}
}

/*********** GLOBALS*************/

var restArr;
var openArr;
var hlRestIdx;
var hlRevIdx;
var hlOnTime;
var scrollLeftFlag;
var scrollRightFlag;
var scrollLeftZone;
var scrollRightZone;
var scrollPanel;

//************************************** MAIN *****************************************************//


//****** CHECK BOX ***** //

var checkboxHeight = "25";

document.write('<style type="text/css">input.styled { display: none; }  .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].type == "checkbox" && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;
				
				inputs[a].checked = true;
				if(inputs[a].checked == true) {
					position = "0 -" + (checkboxHeight*2) + "px";
					span[a].style.backgroundPosition = position;
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				if(!inputs[a].getAttribute("disabled")) {
					span[a].onmousedown = Custom.pushed;
					span[a].onmouseup = Custom.check;
				} else {
					span[a].className = span[a].className += " disabled";
				}
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		
		if(element.checked == true) {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked != true) {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		
		if(element.checked == true) {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";;
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	}
}

$(document).ready(Initialize);

function Initialize(){
	//$(window).focus(winFocus);
	//$(window).blur(winBlur);
	
	jQuery("abbr.timeago").timeago();
	displayMain();
	//Custom.init();
	
	$(function(){
		$('#contactable').contactable({
			subject: 'A Feeback Message'
		});
	});

	$.ajax({
		url: "/cgi-bin/queryReviews.cgi",
		type: "GET",
		data: ({ n: 20 }),
		complete: handleResponse,
		contentType: "text/xml; charset=\"utf-8\""
	});
	$.ajax({
		url: "/cgi-bin/queryOpenings.cgi",
		type: "GET",
		data: ({ n: 20 }),
		complete: handleResponse,
		contentType: "text/xml; charset=\"utf-8\""
	});
	if(0){
		$.ajax({
			url: "/cgi-bin/queryArticles.cgi",
			type: "GET",
			data: ({ n: 20 }),
			complete: displayReviews,
			contentType: "text/xml; charset=\"utf-8\""
		});
	}
}

function displayMain(){
	createHeader();
	createLayout();
}

function createHeader(){
	//$("#header").empty();
	//$("#header").append("<div id='title'></div>");
	//$("#header").append("<div id='source_buttons'></div>");
	//$("#source_buttons").append("<div class='ckbox'><input type='checkbox' id='nyt_but' class='styled' />NYT</div></div>");
	//$("#source_buttons").append("<div class='ckbox'><input type='checkbox' id='nym_but' class='styled' />NYM</div></div>");
	//$("#source_buttons").append("<div class='ckbox'><input type='checkbox' id='sre_but' class='styled' />SRE</div></div>");
	//$("#source_buttons").append("<div class='ckbox'><input type='checkbox' id='voc_but' class='styled' />VOC</div></div>");
	//$("#source_buttons").append("<div class='ckbox'><input type='checkbox' id='tny_but' class='styled' />TNY</div></div>");
}

function createLayout(){
	//$('#slider1').empty();
	
	//$('#slider1').append("<div id='pop_up'></div>");
	
	$("body").append("<div id='header'></div>");
	$("body").append("<div class='slider_title' id='sl_title1'>reviews</div>");
	$("#sl_title1").css('top','50px');
	$("body").append("<div id='mid_band'></div>");
	$("body").append("<div class='slider_title' id='sl_title2'>openings</div>");
	$("#sl_title2").css('top','350px');
	$("body").append("<div id='bot_band'></div>");
	$("body").append("<div id='container'></div>");
	
	$("#header").append("<div id='title'></div>");
	
	$("body").append("<div class='left_zone' id='lz1'></div>");
	$("body").append("<div class='right_zone' id='rz1'></div>");
	$("body").append("<div class='left_zone' id='lz2'></div>");
	$("body").append("<div class='right_zone' id='rz2'></div>");
	
	//$("#container").append("<div class='slider_title' id='sl_title1'>[reviews]</div>");
	$("#container").append("<div class='panel_slider' id='slider1'></div>");
	//$("#container").append("<div class='slider_title' id='sl_title2'>[openings]</div>");
	$("#container").append("<div class='panel_slider' id='slider2'></div>");

	$('#slider1').css('left', '0px');
	$('#slider2').css('left', '0px');
	$('#slider2').css('top', '349px');

	$("#lz1").css('top','70px');
	$("#rz1").css('top','70px');
	$("#lz1").append("<div class='left_scroll_arrow'></div>");
	$("#rz1").append("<div class='right_scroll_arrow'></div>");
	
	$("#lz2").css('top','375px');
	$("#rz2").css('top','375px');
	$("#lz2").append("<div class='left_scroll_arrow'></div>");
	$("#rz2").append("<div class='right_scroll_arrow'></div>");
	
	$("#lz1").mouseenter(scrollLeftOn);
	$("#lz1").mouseleave(scrollLeftOff);
	$("#rz1").mouseenter(scrollRightOn);
	$("#rz1").mouseleave(scrollRightOff);
	
	$("#lz2").mouseenter(scrollLeftOn);
	$("#lz2").mouseleave(scrollLeftOff);
	$("#rz2").mouseenter(scrollRightOn);
	$("#rz2").mouseleave(scrollRightOff);
}

function setGMapOptions(latlng){
	var myOptions = {
		zoom: 15,
		center: latlng,
		disableDefaultUI: true,
		mapTypeControl:false,
		zoomControl: true,
		zoomControlOptions: {
			position: google.maps.ControlPosition.TOP_RIGHT
		},
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	return myOptions;
}


function Rest(xmlRest){
	this.restId = xmlRest.find("restId").text();
	this.fullname = xmlRest.find("restName").text();
	
	if(this.fullname.length > 26){  this.name = this.fullname.substring(0,25) + "..."; }
	else{  this.name = this.fullname;  }
	
	this.imgLink = xmlRest.find("imgLink").text();	
	this.phone = xmlRest.find("phone").text();
	this.cuisine = xmlRest.find("cuisine").text();
	this.address = xmlRest.find("address").text();
	this.city = xmlRest.find("city").text();
	this.zip = xmlRest.find("zip_code").text();
	this.neighborhood = xmlRest.find("neighborhood").text();
	
	this.latlng = new google.maps.LatLng(parseFloat(xmlRest.find("latitude").text()), parseFloat(xmlRest.find("longitude").text()));
	this.mapOptions = setGMapOptions(this.latlng);
	
	this.initMap = function(){ this.map = new google.maps.Map(document.getElementById("map" + this.id), this.mapOptions); }
	this.initMkr = function(){ this.mkr = new google.maps.Marker({position: this.latlng, map: this.map, title: this.name }); }
	
	this.revArr = new Array();
}

function Review(xmlRest){
	this.revId = xmlRest.find("reviewId").text();
	this.source= xmlRest.find("source").text();
	this.pubDate= xmlRest.find("pubDate").text();
	this.articleLink= xmlRest.find("articleLink").text();
	this.imgLink = xmlRest.find("imgLink").text();	
	this.excerpt = xmlRest.find("excerpt").text();	
	this.rating = xmlRest.find("rating").text();
}

function handleResponse(result){
	var qryType = $(result.responseXML).find("queryType").text();
	console.log(qryType);
	switch(qryType)
	{
		case "reviews":
			createReviewArr(result);
			displayReviews(0);
			break;
		case "openings":
			createOpeningArr(result);
			displayOpenings(0);
			break;
	}
}

function createReviewArr(result){
	restArr = new Array();
	var rest;
	var revCount = 0;
	var restCount = 0;
	console.log("Creating Restaurant Array...");
	$(result.responseXML).find("article").each(function(){
		var revId = $(this).find("reviewId").text();
		
		if(restArr.length == 0 || rest.restId != $(this).find("restId").text()){  //new restaurant
			rest = new Rest($(this));
			restArr.push(rest);
			restCount++;
		}
		
		rev = new Review($(this));
		restArr[restArr.length-1].revArr.push(rev);
		
		revCount++;
	});
	console.log("stored " + revCount + " reviews for " + restCount + " restaurants");
}

function createOpeningArr(result){
	openArr = new Array();
	var rest;
	var revCount = 0;
	var restCount = 0;
	console.log("Creating Openings Array...");
	$(result.responseXML).find("article").each(function(){
		var revId = $(this).find("reviewId").text();
		
		if(openArr.length == 0 || rest.restId != $(this).find("restId").text() || rest.restId < 0){  //new restaurant
			rest = new Rest($(this));
			openArr.push(rest);
			restCount++;
		}
		
		rev = new Review($(this));
		openArr[openArr.length-1].revArr.push(rev);
		
		revCount++;
	});
	console.log("stored " + revCount + " reviews for " + restCount + " restaurants");
}

function displayReviews(start){     	//----------- HIGHLIGHTED REVIEWS ----------- //
	$('#slider1').css('width',(restArr.length * 224)+'px');
	
	for(var i=0; i < restArr.length; i++){
		$('#slider1').append("<div class='rest_block' id='rest" + restArr[i].restId + "'></div>");
		var dvRestBlk = $("#rest" + restArr[i].restId);
		dvRestBlk.append("<div class='rev_pubdate'>" + dtConvert(restArr[i].revArr[0].pubDate).toUpperCase() + "</div>");
		dvRestBlk.append("<div class='rev_image'><img id='imghl" + restArr[i].restId + "' class='imgHL' src='" + restArr[i].imgLink  + "'></div>");
		
		if(restArr[i].fullname.length < 20){
			dvRestBlk.append("<div class='rest_name'>" + restArr[i].fullname + "</div>");
		}else{
			dvRestBlk.append("<div class='rest_name'>" + restArr[i].fullname.substring(0,20) + "... </div>");
		}
		dvRestBlk.append("<div class='rest_cuis'>" + restArr[i].cuisine + "</div>");
		dvRestBlk.append("<div class='rest_nbhood'>" + restArr[i].neighborhood + "</div>");
		
		for(var j=0; j < restArr[i].revArr.length; j++){
			dvRestBlk.append("<div class='rev_entry' id='rest" + i + "rev" + j + "'></div>");
			dvHL = $("#rest" + i + "rev" + j);
			dvHL.click(reviewClick);
			
			switch(restArr[i].revArr[j].source)
			{
				case "NYT":
					dvHL.append("<div class='rev_source'><img src='/img/nytimes_icon.png'></div>");
					rating =  parseFloat(restArr[i].revArr[j].rating) + 1;
					break;
				case "NYM":
					dvHL.append("<div class='rev_source'><img src='/img/nymag_icon.jpeg'></div>");
					rating =  parseFloat(restArr[i].revArr[j].rating);
					break;
				case "VOC":
					dvHL.append("<div class='rev_source'><img src='/img/voc_icon.png'></div>");
					rating = 0;
					break;
				case "SRE":
					dvHL.append("<div class='rev_source'><img src='/img/sts_icon.png'></div>");
					rating =  parseFloat(restArr[i].revArr[j].rating);
					break;
				case "TNY":
					dvHL.append("<div class='rev_source'><img src='/img/tony_icon.gif'></div>");
					rating =  parseFloat(restArr[i].revArr[j].rating);
					break;
				case "UDY":
					dvHL.append("<div class='rev_source'><img src='/img/udy_icon.png'></div>");
					rating =  parseFloat(restArr[i].revArr[j].rating);
					break;
				default:
					break;
			}
			
			var revStr = "";
			
			if(rating > 0){
				for(var k=0; k<5; k++){
					if(j < (rating)){
						//revStr = revStr + "<img src=\"http://xenger.com/img/x_star_nb.gif\" width=20 height=20 style=\"padding-left: 3px;\"/>";
					}
				}
			}else{
				//revStr = "NO RATING";
			}
			//console.log(i + " - " + j + " " + restArr[i].name);
		}
	}
}

function displayOpenings(start){    
	$('#slider2').css('width',(openArr.length * 224)+'px');
	for(var i=0; i < openArr.length; i++){
		$('#slider2').append("<div class='rest_block' id='open" + openArr[i].revArr[0].revId + "'></div>");
		var dvRestBlk = $("#open" + openArr[i].revArr[0].revId);
		dvRestBlk.append("<div class='rev_pubdate'>" + dtConvert(openArr[i].revArr[0].pubDate).toUpperCase() + "</div>");
		dvRestBlk.append("<div class='rev_image'><img id='imghl" + openArr[i].restId + "' class='imgHL' src='" + openArr[i].imgLink  + "'></div>");
		console.log(openArr[i].fullname.length);
		if(openArr[i].fullname.length < 20){
			dvRestBlk.append("<div class='rest_name'>" + openArr[i].fullname + "</div>");
		}else{
			dvRestBlk.append("<div class='rest_name'>" + openArr[i].fullname.substring(0,20) + "... </div>");
		}
		//dvRestBlk.append("<div class='rest_cuis'>" + openArr[i].cuisine + "</div>");
		//dvRestBlk.append("<div class='rest_nbhood'>" + openArr[i].neighborhood + "</div>");
		
		for(var j=0; j < openArr[i].revArr.length; j++){
			dvRestBlk.append("<div class='rev_entry' id='open" + i + "rev" + j + "'></div>");
			dvHL = $("#open" + i + "rev" + j);
			dvHL.click(reviewClick);
			
			switch(openArr[i].revArr[j].source)
			{
				case "NYT":
					dvHL.append("<div class='rev_source'><img src='/img/nytimes_icon.png'></div>");
					rating =  parseFloat(openArr[i].revArr[j].rating) + 1;
					break;
				case "NYM":
					dvHL.append("<div class='rev_source'><img src='/img/nymag_icon.jpeg'></div>");
					rating =  parseFloat(openArr[i].revArr[j].rating);
					break;
				case "VOC":
					dvHL.append("<div class='rev_source'><img src='/img/voc_icon.png'></div>");
					rating = 0;
					break;
				case "SRE":
					dvHL.append("<div class='rev_source'><img src='/img/sts_icon.png'></div>");
					rating =  parseFloat(openArr[i].revArr[j].rating);
					break;
				case "TNY":
					dvHL.append("<div class='rev_source'><img src='/img/tony_icon.gif'></div>");
					rating =  parseFloat(openArr[i].revArr[j].rating);
					break;
				case "UDY":
					dvHL.append("<div class='rev_source'><img src='/img/udy_icon.png'></div>");
					rating =  parseFloat(openArr[i].revArr[j].rating);
					break;
				default:
					break;
			}
			
			var revStr = "";
			
			if(rating > 0){
				for(var k=0; k<5; k++){
					if(j < (rating)){
						//revStr = revStr + "<img src=\"http://xenger.com/img/x_star_nb.gif\" width=20 height=20 style=\"padding-left: 3px;\"/>";
					}
				}
			}else{
				//revStr = "NO RATING";
			}
			//console.log(i + " - " + j + " " + openArr[i].name);
		}
	}
}

function doMove() {
	var blockdiv = $("#rest32");
	console.log(blockdiv.style.left);
	blockdiv.style.left = (blockdiv.style.left+10)+'px'; 	// pseudo-property code: Move right by 10px
	//setTimeout(doMove,20); 						// call doMove() in 20 msec
}
