/*
 * It is a main Javascript file for list pages.
 */
(function( $ ) {
	// global variables for listing page
	var gVars = IMF.vars.listpage = {
		"maxRowPerNav": 3,
		"m":{
			 "en" : {
				"nav.matchCategory": "Matched Categories",
				"nav.relevantCategory": "Relevant Categories",
				"nav.nearbyCity": "Nearby Cities",
				"nav.neighbor": "Neighborhoods",
				"nav.keywords": "Narrow Search"
			 },
			 "es" : {
				"nav.matchCategory": "Categorías Relevantes",
				"nav.relevantCategory": "Categorías Relevantes",
				"nav.nearbyCity": "Ciudades o Pueblos Cercanos",
				"nav.neighbor": "Vecindario",
				"nav.keywords": "Palabras Claves"
			 }
		}
	};
	
	var $prevPopup = undefined,
		$clickedLink = undefined;
	
	$(document).bind( "ready", function() {
		//console.log("in list ready....");
		IMF.listpage.init();

		// check if there is Box Ads at right side
		if($("#_boxad_").length == 0)
			$("#map-expand").css({"margin-right":0});
		
		// set click event on the link of more of navigation groups
		$("a.more-link-right:visible", "#navBody").live("click", function(event) {
			IMF.listpage.getNavigationList($(this).data("navType"), event);
		});
		
		$("#see-more-boxads").click(function() {
			IMF.listpage.showMoreBoxAds();
		});

		// it should be a live method due to move&refresh feature
		$("#scrolling-list").live( "mouseout", function() {
			unhighlightIcon();
		});

		$(".mp4link").click(function(event){
			var $mp4Popup = $("<div id='mp4Popup'><div></div></div>"),
				html4Video = '<video height="350px" width="430px" controls="controls"' + 
							 'poster="' + $(this).data("mp4cover") + '" preload="none" '+ 
							 'src="' + $(this).data("mp4url") + '" tabindex="0">'+
    						 '</video>'; 

			// set styles for the popup
			$mp4Popup.css({display:"block", 
					  position:"absolute", 
					  top:event.pageY-100,
					  left:$("#listings-results").offset().left + 200,//event.pageX,
					  height: "350px", 
					  width: "430px",
					  border: "1px solid #CACACA",
					  "background-color": "#FFFFFF",
					  "z-index": 150})
			 .find("div")
			 .append(html4Video)
			 .end()
			 .append("<div class='popup-close' id='mp4-popup-close' style='top:-15px;right:-15px'></div>")
			 .appendTo("body")
			 .end();
			
			$mp4Popup
				.find("#mp4-popup-close")
			 	.click(function() {
					 $("#mp4Popup").remove();
			 	 });
			
			return false;
		});
		
		// BoxAds: video icons. Should be a live method
		$(".boxAd-media").live( "click", function() {
			openVideo($(this).data('listingId'),null,$(this).data('dispName').replace(/'/g,""),true, $(this).data('impId'));
		});

		// adjust length of listing name and enticer line in boxads. And also add handlers to deal with mouse over/out
		//$(".business-info:visible").not(":last")
		$(".business-info:visible")
		 .find("h4, h5").each(function() {
			var s = $(this).text();
			
			// store original enticer line if it is long so that it can be used in mouseenter handler
			if(this.nodeName == "H4" && s.length > 26) {
				$(this).data("full-enticer", s);
				$(this).text(s.substring(0, 26)+"...");
			}
			else if(this.nodeName == "H5" && s.length > 15) {
				$(this).data("full-dispName", s);
				$(this).text(s.substring(0, 15)+"...");
			}
		}).end()
		.mouseenter(function() {
			$(this)
			 .find("h4, h5").each( function() { 
				 if(this.nodeName == "H4")
				 	$(this).text($(this).data("full-enticer"));
				 else if(this.nodeName == "H5")
					$(this).text($(this).data("full-dispName"));
			 }).end()
			 .find("p:hidden, a:hidden").show();
		})
		.mouseleave(function() { 
			$(this)
			 .find("h4, h5").each( function() {
				var s = $(this).text();
	
				// rollback to short form if it is long
				if(this.nodeName == "H4" && s.length > 26)
					$(this).text(s.substring(0, 26)+"...");
				else if(this.nodeName == "H5" && s.length > 15)
					$(this).text(s.substring(0, 15)+"...");
			 }).end()
			 .find(".hiddenDiv").hide();
		});

		// added mouseover and mouseout events on listing boxes
		$(".listing.vertical").live( "mouseover mouseout", function(event) {
			var idx = $(this).data("boxIndex");
			
  			if (event.type == "mouseover") {
  				$(this).css({"background-color": "#FFFFBB"});
  				highlightIcon(idx);
  				highlightIndex = idx;
			} 
  			else {
  				$(this).css({"background-color": "#FFFFFF"});
  			}
		});

		// save & share link
		// in the case of Google Map, calling from infobox is the same as in listing box
		// and in infobox listingid and detailpageurl are added
		$(".save-share").live( "click", function() {
			var $topDiv = $(this).closest(".listing"), // the first div of the box
				listingId = $(this).data("listingid")||$topDiv.data("listingId"),
				isListOnly = $topDiv.is(".horizontal, .coupon") ? true:false;	// listings only page?

			$clickedLink = $(this);
			IMF.vars.listpage.$clickedLink = $clickedLink;
			
			IMF.listpage.getSaveShare($(this).offset(), listingId, isListOnly);
		});

		// more details link
		// in the case of coupon, the name is inside child div
		$(".more-details-link").live( "click", function() {
			var $topDiv = $(this).closest(".listing"), // the first div of the box
				listingId = $(this).data("listingid")||$topDiv.data("listingId"),
				// in the case of multi-tab box, the listing name is under the class of multiBoxContainer
				listingName = $topDiv.find("h5").data("dispname")||$topDiv.find("h5 div").text()||$topDiv.closest(".multiBoxContainer").find("h5 a").text(),
				// in the case of multi-tab box, it is defined the top div
				detailPageUrl = $(this).data("detailpageurl")||$topDiv.find("h5 a").attr("href")||$topDiv.data("detailpageurl"),
				isListOnly = $topDiv.is(".horizontal, .coupon") ? true:false;	// listings only page?

				//alert("listingId: " + listingId + ", listingName: " + listingName + ", detailPageUrl: " + detailPageUrl + ", isListOnly: " + isListOnly);
				
			$clickedLink = $(this);
			IMF.vars.listpage.$clickedLink = $clickedLink;
			
			if (detailPageUrl !== undefined && detailPageUrl.lastIndexOf("#coupon")!=-1)				
				detailPageUrl = detailPageUrl.replace("#coupon","");
			
			IMF.listpage.getMoreDetails($(this).offset(), {l:listingId, ln:listingName, d:detailPageUrl}, isListOnly);
		});
		
		// Active Directory -----------------------------------------------------------------------------------
		var $ab = $("#activeDirectoryTemplate"),
				abClicked = false;
		
		if($ab.length != 0) {
			var count = $ab.data("count"),
					searchType = $ab.data("searchType");
			
			if(count == 1) {
				$(".book-dir-link").click(function(){
					var url = "http://directory.mylocalypsearch.com/"+$ab.data("dircode")+"/data/directory.htm?initSearch="+$("#na").val();
					url = searchType == 1 ? url : url+"&searchType=business";
					
					window.open(url, "_blank");
				});
			} 
			else {
				var html = "<div>Which book would you like to view?</div>" + $ab.html();
				
				$(".book-dir-link").click(function(event){
					if(!abClicked) {
						abClicked = true;

						$blayer = $("<div class='dropdown'></div>")
			 				.css({position:"absolute",
			 					top: $(this).offset().top+18,
								left: $(this).offset().left-80,
								width: "215px",
								"z-index":"101",
							 	padding:"5px",
							 	border:"1px solid #999999"})
						 .append(html)
						 .append('<div class="popup-close"></div>')
						 .appendTo("body")
			 			 .find(".popup-close")
						 .click(function() { 
							 $(this).parent().remove(); abClicked = false; return false; 
							}).end();
					}
				});
			}			
		}
		// ------------------------------------------------------------------------------------------------------
		
		// get initial pin informations
		/* when all pins are loaded in a ajax way
		$.ajax({
			type: "GET",
			url: "/listItem.do",
			data: "op=getMapData&t="+(new Date()).getTime(),
			dataType:"json",
			success: function(mapData) {
				// loadMap is defined for each map type: bing map(bing_bs_v2.js) and google map(gmap_bs_i5.js)
				loadMap(mapData);
			},
			error: function() {}
		});
		*/
	});

	// main function for detail pages	
	IMF.listpage = function() {
		var init = function() {
			// if it is heading search, get navigation data using Ajax call
			if(IMF.vars.isHeadingSearch) {
				$.ajax({
	 				type:"GET",
	 				url: "/nav.do",
	 				data: "op=getAll&t="+(new Date()).getTime(),
	 				dataType: "json",
	 				success: function(navData) {
						// store result to use it for getting more result later
						IMF.vars.listpage.navData = navData;

						// if in listing page initial nav items are displayed, it should be skipped.
						var skipCnt = 0;
						$.each(navData, function(i, item) {
							// if it doesn't have any items, just return to skip it
							if(item.items.length == 0) {
								skipCnt++;
								return true;
							}
						});

						if(skipCnt == navData.length)
							$(".filter-unit.mt0").hide();
						
						// change the field of what: in FF it is not changed from header_v2
						// search-result-category is defined in NavigationGroup class
						$("#na").val($("#search-result-category").text()); // don't use .html()
	 				},
	 				error: function(xhr, status, e) { 
	 					//alert("Error: failed to get navigation groups:" + status +"-"+e); 
	 				}
				});
			}
			
			getAllMoreDetails();
		};

		var openedNavPopup = undefined,
			$prevMoreNavLink = undefined;
		
		var closePopup = function() {
			if($prevPopup !== undefined)
				$prevPopup.removeShadow().remove();
				
			if($prevMoreNavLink !== undefined)
				$prevMoreNavLink.show();
		};
		
		var showNavToPopup = function(navData, event) {
			$prevMoreNavLink = $(event.target); // the clicked link of more in navigation area
			$prevMoreNavLink.hide();
			
			/*
			var	$tmpl = $("#navTemplate2").clone(); // error ???
						$("#navTemplate").clone()	// ok ???
			 			 .find("a").remove().end()
						 .find("div.clear").remove().end()
						 .find("div:first").removeClass().addClass("dropdown misc-categories")
						 .append("<div id='nav-popup-close' class='close'></div>")
						 .attr("id", "nav-popup").end();
			
			$tmpl.find("h5")
				 .html(gVars.m[IMF.vars.locale][navData.type]);
			
			var $ul = $tmpl.find("ul"); 
			$.each(navData.items, function(i, item) {
				 $ul.append("<li><a href='"+item.url+"'>"+item.caption+" ("+item.count+")</a></li>");
			});
			*/ 
			var prevGrp = "",
				html = '<div id="nav-popup" class="dropdown misc-categories">' +
				  	   '<h5>'+IMF.getMessage(navData.type.replace(".", "-"))+'</h5>' +
				   	   '<ul class="left first">'+
					   ' <ul>';

			$.each(navData.items, function(i, item) {
				if(item.grpName !== undefined && prevGrp != item.grpName) {
					html +="</ul>";
					html +="<h6>" + item.grpName + "</h6><ul>"
					prevGrp = item.grpName;
				}
				html += "<li><a href='"+item.url+"'>"+item.caption+ (item.count>0?" ("+item.count+")":"") + "</a></li>";
				if((i+1)%25 == 0 && i != 0)
					html += "</ul></ul><ul class='left'><ul>";
			});
			
			html += ' </ul>'+
				  	'</ul>'+				
				    '<div id="nav-popup-close" class="popup-close"></div>'+
				    '</div>';

			//var $nav = $($tmpl.html());
			$prevPopup = $(html);

			// get object with returned html
			// var $prevPopup = $(navData);

			// set styles for the popup
			$prevPopup.css({display:"none", 
					  position:"absolute", 
					  top:event.pageY,
					  left:$("#search-results").offset().left+$("#search-results").width()})
				.appendTo("body")
				.css({width: $prevPopup.width()+20}) // to put close button to the top right
				.find("ul", ".dropdown ").not(".left").find("li:last").css({"margin-bottom":"10px"}).end().end()
				.end()
				.find("#nav-popup-close")
				.click(function() { IMF.listpage.closePopup(); })
				.end();

			// adjust the top of the popup
			var navTop = 0,
				diff = $(window).height() - (event.pageY+$prevPopup.height());

			if(diff >= 0)
				navTop = event.pageY; // the position where users clicked 
			else {
				var t = (event.pageY + diff)-30;
				if(t < 0)
					navTop = 10; // if the adjusted top is beyond the top of window, set it to 10
				else
					navTop = t;
			}
			
			// reset the top with adjusted top and make it visible
			// dropShadow changes the popup's zIndex so I changed it to have a zIndex in the options
			$prevPopup.css({top:navTop-10}).show()
				.dropShadow({ color: "#555", left: 8, top:8, blur:0, opacity: 0.6, "z-index": 200 });
		};

		var getNavigationList = function(type, event) {
			// close previous one
			closePopup();

			// call server to get a list of the navigation
			/*
			$.ajax({
				type: "GET",
				url: "/nav.do",
				data: "op=getOne&tp=" + type + "&t="+(new Date()).getTime(),
				dataType: "html",
				success: function(navData) {
					//showNavToPopup( $($tmpl.html()), type, event ); // in the case of json return
					showNavToPopup( navData, type, event );
				},
				error: function() {
					alert("Please reload the page.");
				}
			});
			*/
			// get one group of navigation from the stored variable
			$.each(IMF.vars.listpage.navData, function(i, data) {
				if(data.type == type) {
					showNavToPopup(data, event);
					return false;
				}
			});
		};
		
		var showMoreBoxAds = function() {
			/*
			if($("#more-ads-popup").length == 1)
				return;
			*/
			var $biz = $(".business-info:hidden").clone();
			
			$("#see-more-boxads").hide();
			
			$("<div id='more-ads-popup'></div>")
			 .css({position:"absolute", 
				   width: 300,
				   "z-index": 501,
				   "font-size": 11,
				   "background-color": "#FFFFFF",
				   top:$("#_boxad_").offset().top, 
				   left:$("#_boxad_").offset().left-310})
			 .appendTo("body")
			 .html(function() {
				 // create a wrapper div
				 var $h = $("<div></div>");
				 
				 $biz.each(function() {
					 $h.append($(this).find("p:hidden, a:hidden").removeClass("hideDiv").end()
					 	   			  .find("h4").css({"font-size": "11"}).end());
				 });
				 return $h.find("div:hidden").removeClass("hideDiv").end() // make the divs of business-info visible
				 		  .html();
			 })
			 .append('<div id="boxads-popup-close" class="popup-close"></div>')
			 .find("#boxads-popup-close")
			 .click(function() { $(this).parent().removeShadow().remove(); $("#see-more-boxads").show(); }).end()
			 .dropShadow({ color: "#555", left: 8, top:8, blur:0, opacity: 0.6, "z-index":500 });
		};

		
		// only for Chrome browser
		// save&share and more details link are called two times from Chrome client
		var isCalledByChrome = false;

		var getSaveShare = function(offset, listingId, isListOnly) {
			if(isCalledByChrome) {
				isCalledByChrome = false;
				return;
			}
			
			// check if it is called by Chrome client
			isCalledByChrome = /chrome|safari/.test(navigator.userAgent.toLowerCase());
			
			closePopup();
			
			$.ajax({
				type: "GET",
				data: "id=" + listingId + "&imp_id=" + IMF.vars.schemaImpId + "&lang=" + IMF.vars.lang +"&pg=L" + "&t="+(new Date()).getTime(),
				url: "/share.jsp",
				dataType: "html",
				success: function(html) {
					// in the case of being clicked from infobox.
					// in bing_bs_v2.js it is set to undefined 
					if(offset === undefined) {
						var $infobox = $("#IMF_infobox"); 
						offset = $infobox.offset();
						offset.top += $infobox.height() - 5;
						offset.left -= 20;
						IMF.vars.listpage.fromInfoBox = true;
					}				
					else {
						IMF.vars.listpage.fromInfoBox = false;						
						if(IMF.vars.mapType=='B') MapLIB.removeInfoBox();
					}

					// saved the current popup
					$prevPopup = $("<div id='save-share-popup'></div>")
						.css({position:"absolute",
						   	  top: offset.top+15,
							  left: isListOnly ? offset.left-150:offset.left,
							  "background-color": "#FFFFFF"})
						.append(html)		// insert the returned html to this popup
						.appendTo("body")	// append this popup to the body
			 			.find(".popup-close")
						.click(function() { $(this).parent().parent().removeShadow().remove(); return false; }).end();
					
					// if DW, show links
					if(IMF.vars.userImpId == '15' || IMF.vars.userImpId == '99') {
						$prevPopup.find("#links").show();
					}
					
					// if it is called from infobox, don't put shadow image because it makes infobox broken later
					// in this case isListOnly is undefined
					if(isListOnly !== undefined)
						$prevPopup.dropShadow({ color: "#555", left: 8, top:8, blur:0, opacity: 0.6, "z-index":100 }).end();
					else
						$prevPopup.css("z-index", "700");
				},
				error: function() { }
			});
		};
		
		// getting more details information and save it to IMF.vars.listpage		
		var getAllMoreDetails = function() {
			$.ajax({
				type: "GET",
				url: "/listItem.do",				
				data: "op=getAll&t="+(new Date()).getTime(),
				dataType:"json",
				success: function(data) {
					IMF.vars.listpage.moreDetails = data;
				},
				error: function() {}
			});
		};
		
		var getMoreDetails = function(offset, opts, isListOnly) {
			if(isCalledByChrome) {
				isCalledByChrome = false;
				return;
			}
			
			// check if it is called by Chrome client
			isCalledByChrome = /chrome|safari/.test(navigator.userAgent.toLowerCase());
			
			closePopup();
			
			// in the case of being clicked from infobox.
			// in bing_bs_v2.js it is set to undefined 
			if(offset === undefined) {
				var $infobox = $("#IMF_infobox"); 
				offset = $infobox.offset();
				offset.top += $infobox.height() - 5;
				offset.left += 100;
				IMF.vars.listpage.fromInfoBox = true;
			}
			else {
				IMF.vars.listpage.fromInfoBox = false;
				if(IMF.vars.mapType=='B') 
					MapLIB.removeInfoBox();
			}
						 
			$prevPopup = $("<div id='more-details-popup'></div>")
					 .css({position:"absolute",
						 top: offset.top+15,
						 left: isListOnly ? offset.left-10:offset.left,
						 width: 140,
						 "z-index":"101",
						 "background-color": "#FFFFFF"})
					 .append($("#moreDetailsTemplate").html())
					 .appendTo("body")
		 			 .find(".popup-close")
					 .click(function() { $(this).parent().parent().removeShadow().remove(); return false; }).end();

			$.each(IMF.vars.listpage.moreDetails, function() {
				if(this.listingId !== undefined && this.listingId == opts.l) {
					IMF.vars.media = {};
					
					if(this.details !== undefined && !this.details.hasVideo)
						$prevPopup.find(".md-video").remove(); 
					else {
						IMF.vars.media.video = {};
						var videoData = this.details.videoData.split("|");
						IMF.vars.media.video.listingId = opts.l, IMF.vars.media.video.listingName = opts.ln, 
						IMF.vars.media.video.catCode=videoData[0],// category code 
						IMF.vars.media.video.flag = videoData[1]; // mulit boolean
						IMF.vars.media.video.file = videoData[2] != null?videoData[2]:""; // video file url
					}

					if(!this.details.hasPhoto)
						$prevPopup.find(".md-photo").remove();
					else {
						IMF.vars.media.photo = {};
						IMF.vars.media.photo.listingId = opts.l, IMF.vars.media.photo.listingName = opts.ln, 
						IMF.vars.media.photo.catCode = this.details.photoData, // category code 
						IMF.vars.media.photo.flag = true;
					}

					//!this.details.hasMoreInfo ? $prevPopup.find(".md-moreinfo").remove() : $prevPopup.find(".md-moreinfo a").attr("href", opts.d+"#moreinfo");
					
					if(!this.details.hasMoreInfo)
						$prevPopup.find(".md-moreinfo").remove();
					else {
						IMF.vars.yellowad = {};
						var ydata = this.details.moreInfoData.split("|");
						
						IMF.vars.yellowad.viewType = ydata[0];
						IMF.vars.yellowad.listingId = opts.l;
						IMF.vars.yellowad.catCode = ydata[1];
					}
					
					!this.details.hasCoupon ? $prevPopup.find(".md-coupon").remove() : $prevPopup.find(".md-coupon a").attr("href", opts.d+"#coupon");
					!this.details.hasMenu ? $prevPopup.find(".md-menu").remove() : $prevPopup.find(".md-menu a").attr("href", opts.d+"#menu");
					!this.details.hasProfile ? $prevPopup.find(".md-profile").remove() : $prevPopup.find(".md-profile a").attr("href", opts.d);

					// if it is called from infobox, don't put shadow image because it makes infobox broken later
					if(isListOnly !== undefined)
						$prevPopup.dropShadow({ color: "#555", left: 8, top:8, blur:0, opacity: 0.6, "z-index":100 }).end();
					else
						$prevPopup.css("z-index", "700");
					
					return false;
				}
			});
		};
		
		var setScroll = function() {
			if(IMF.vars.listpage.$clickedLink !== undefined && IMF.vars.listpage.fromInfoBox == false) {
				var scrollingList = $("#scrolling-list");
				var scrollingListTop = $("#scrolling-list").offset().top;
				var scrollingListBottom = $("#scrolling-list").offset().top + $("#scrolling-list").height()-20;
				if (scrollingList!=null && scrollingList!='undefined' && scrollingList !='') {
					if (scrollingListTop <= $clickedLink.offset().top && scrollingListBottom > $clickedLink.offset().top) {
						$("#more-details-popup, #save-share-popup").css("display","");
						$("#save-share-popup_dropShadow").css("display","");
						$("#more-details-popup_dropShadow").css("display","");
						
						$("#more-details-popup, #save-share-popup").offset({top:$clickedLink.offset().top+15});
						$("#save-share-popup_dropShadow").offset({top:$clickedLink.offset().top+15+8});
						$("#more-details-popup_dropShadow").offset({top:$clickedLink.offset().top+15+8});
					}
					else {
						$("#more-details-popup, #save-share-popup").css("display","none");
						$("#save-share-popup_dropShadow").css("display","none");
						$("#more-details-popup_dropShadow").css("display","none");
					}
				}
			}
		};
		
		return {
			init: init,
			getNavigationList: getNavigationList,
			showMoreBoxAds: showMoreBoxAds,
			getSaveShare: getSaveShare,
			getAllMoreDetails: getAllMoreDetails,
			getMoreDetails: getMoreDetails,
			closePopup: closePopup,
			setScroll: setScroll
		}
	}();
})( jQuery );
