/* DEFINE VARS */
page = new Object();
page['modules'] = new Object();
page['modules']['search'] = new Object();

function generateID() {
	var curdate = new Date()
	var seconds = curdate.getSeconds();
	var milliseconds = curdate.getTime();
	id = "id" + Math.floor(Math.random()*Math.floor(milliseconds/seconds));
	return id;
}

function add_overlay() {
	$("<div class='overlay'></div>").css({"background-image":"url(/assets/images/backgrounds/overlay_bg_blk.png)",width:$(document).width(),height:$(document).height()}).appendTo("body");
	$("div.overlay").bind("click", function () {remove_overlay();});
	//console.log(arguments);
	if(arguments.length != 0) {
		$.ajax({
			type: "GET",
			url: "/modules/" + arguments[0]['method'] + ".php",
			data: {
				_file : arguments[0]['file'],
				_function : arguments[0]['function'],
				dataType: "jsonp",
				jsonp: "jsonp_callback"
			},
			success: function(data){
				$("body").append($("<div class='modual-holder'></div>"));
				data = eval(data);
				$("div.modual-holder").append(unescape(data.data));
				setPos($("div.modual-holder"));
				$(window).bind("scroll", function () {setPos($("div.modual-holder"));});
			}
		});
	}
}

function remove_overlay() {
    $("div.overlay,div.modual-holder").remove();
}
function getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
}

function getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

function setPos(elm) {
    $elm = $(elm);
    /*var pagesize = [];
    pagesize.push($(window).width());
    pagesize.push($(window).height());*/
    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScrollTop();
    var newLeft = arrayPageScroll[0] + (arrayPageSize[0] - $elm.width())/2;
    var newTop = arrayPageScroll[1] + (arrayPageSize[1]-$elm.height())/2;
    if(newLeft < 0) {
        newLeft = 0;
    }
    if(newTop < 0) {
        newTop = 0;
    }
    var style = {position:"absolute", left: newLeft, top: newTop, display:"none"};
    $elm.css(style).fadeIn();
}


function changeActiveBasedOnIndex(srcList,dstList) {
	baseIndex = 0;
	if(arguments.length > 2) {
		baseIndex = arguments[2]; 
	}
	$("a", srcList).bind("mouseover",function () {
		thisIndex = $("a", srcList).index(this) + baseIndex;
		$("li", dstList).removeClass("active").eq(thisIndex).addClass("active");
	});
}

function jumpToAnchor(anchor) {
    if($(anchor).size() != 0) {
        newPos = $(anchor).offset().top;
        document.documentElement.scrollTop = newPos;
        document.body.scrollTop = newPos;
    }
}

function setUpColumnHeights() {
		tmp = {};
		baseHeight = 0;
		$("div[@id*=col_]").not($("div.channel")).each(function () {
				// Find which elm is taller
				currObjName = $(this).attr("id");
				tmp[currObjName] = {};
				tmp[currObjName]['height'] = $(this).outerHeight();
				if(tmp[currObjName]['height'] > baseHeight) {
						baseHeight = tmp[currObjName]['height'];
				}
		});
		$("div[@id*=col_]").not($("div.channel")).each(function () {
				currOuterHeight = $(this).outerHeight();
				if($(this).outerHeight() < baseHeight) {
						$currDivEnd = $(this).find("div[@id*=panel]").not("div.channel").eq($("#col_1").find("div[@id*=panel]").not("div.channel").size() - 1).find("div.end");
						newHeight = baseHeight - currOuterHeight;
						if(newHeight < 0) {
								newHeight = 0;
						}
						$currDivEnd.css({'margin-top':newHeight});
				}
		});
}

function popupWin(aUrl,aName,properties) {
		window.open(aUrl,aName,properties);
}

function getIDFromURL(url) {
		id = url;
		id = id.split("_");
		id = id[id.length-1];
		id = id.split("/");
		id = id[0];
		return id;
}

if(!Array.indexOf){
		Array.prototype.indexOf = function(obj){
				for(var i=0; i<this.length; i++){
						if(this[i]==obj){
								return i;
						}
				}
				return -1;
		}
}

plurals = {};
plurals['articles'] = 'article';
plurals['galleries'] = 'gallery';
plurals['videos'] = 'video';

function setUpTags() {
	$("div.tags a.more-tags").bind("click", function () {
		contentID = getIDFromURL(location.href);
		contentType = 'video';
		switch($("body").attr("id")) {
				case 'videos':
						contentType = 'video';
				break;
				case 'gallery':
						contentType = 'gallery';
				break;
				case 'article':
						contentType = 'article';
				break;
				case 'showcase':
						//contentType = 'article';
						contentType = plurals[$("ul.tabs a.active").parents("li").attr("className")];
				break;
		}
		$.ajax({
				type: "GET",
				url: "/modules/fetch_module.php",
				data: {
						_file : "tags",
						_function : "item_tags",
						content_type : contentType,
						content_id: contentID,
						'close-tags': 1,
						limit : 500,
						offset : 0,
						dataType: "jsonp",
						jsonp: "jsonp_callback"
				},
				success: function(data){
						data = eval(data);
						if(!$("body").attr("id") == 'showcase') {
							parent = $("div.active div.tags").parent();
						} else {
							parent = $("div.tags").parent();
						}
						$("div.tags", parent).remove();
						if($("h1", parent).size() != 0) {
								$("h1", parent).after($(unescape(data.data)));
						} else {
								parent.prepend($(unescape(data.data)));
						}
						setUpTags();
				}
		});
		return false;
	});
	$("div.tags a.close-tags").bind("click", function () {
		contentID = getIDFromURL(location.href);
		contentType = 'video';
		switch($("body").attr("id")) {
				case 'videos':
						contentType = 'video';
				break;
				case 'gallery':
						contentType = 'gallery';
				break;
				case 'article':
						contentType = 'article';
				break;
				case 'showcase':
						contentType = plurals[$("ul.tabs a.active").parents("li").attr("className")];
				break;
		}
		$.ajax({
				type: "GET",
				url: "/modules/fetch_module.php",
				data: {
						_file : "tags",
						_function : "item_tags",
						content_type : contentType,
						content_id: contentID,
						limit : 10,
						offset : 0,
						dataType: "jsonp",
						jsonp: "jsonp_callback"
				},
				success: function(data){
						data = eval(data);
						parent = $("div.tags").parent();
						$("div.tags", parent).remove();
						if($("h1", parent).size() != 0) {
								$("h1", parent).after($(unescape(data.data)));
						} else {
								parent.prepend($(unescape(data.data)));
						}
						setUpTags();
				}
		});
		return false;
	});
}

function addPaginationLinks() {
	// The cursor object has all things to do with pagination
	var cursor = webSearch.cursor;
	var curPage = cursor.currentPageIndex; // check what page the app is on
	$('#googleNav').remove();
	$('div.search_results div.clear').after($("<div id='googleNav'><span class='googleLabel'>Page: </span></div>"));
	if (curPage > 0) {
		var link_href = 'javascript:webSearch.gotoPage('+(curPage-1)+');';
		$('#googleNav').append('<a class="googleLink" href="' + link_href + '" >Back</a>');
	} else {
		$('#googleNav').append('<span class="googleDisabled" href="' + link_href + '" >Back</span>');
	}
	for (var i = 0; i < cursor.pages.length; i++) {
		var page = cursor.pages[i];
		if (curPage == i) { // if we are on the curPage, then don't make a link
			$('#googleNav').append('<span class="googleCurrent" >' + page.label + '</span>');
		} else {
			// If we aren't on the current page, then we want a link to this page.
			// So we create a link that calls the gotoPage() method on the searcher.
			var link_href = 'javascript:webSearch.gotoPage('+i+');';
			$('#googleNav').append('<a class="googleLink" href="' + link_href + '" >' + page.label + '</a>');
		}
	}
	if (curPage < cursor.pages.length-1) {
		var link_href = 'javascript:webSearch.gotoPage('+(curPage+1)+');';
		$('#googleNav').append('<a class="googleLink" href="' + link_href + '" >Next</a>');
	} else {
		$('#googleNav').append('<span class="googleDisabled" href="' + link_href + '" >Next</span>');
	}
}

function googleSearchComplete() {
/*//console.log(webSearch.results.length);
	var searchResultEntry = $('<div class="clear">&nbsp;</div><div class="googleResults"></div>');
	for (var index=0; index < webSearch.results.length; index++) {
		//searchResultEntry += '<div class="googleResult" >';
		for (key in webSearch.results[index]) {
			//searchResultEntry += '<div class="googleResult_' + key + '">' + webSearch.results[index][key] + "</div>\n";
			
		}
		$('div.googleResults', searchResultEntry).append($(webSearch.results[index].html));
		//searchResultEntry += '</div>';
//		$('#search_results').append(searchResultEntry);
	}
	console.log(searchResultEntry);
	$("div.search_results").append($(searchResultEntry));
	addPaginationLinks();*/
	$("div.search_results #googleNav, div.search_results div.clear, div.search_results div.googleResults, div.search_results h4").remove();
	var searchResultEntry = $('<div class="googleResults">&nbsp;</div>');
	for (var index=0; index < webSearch.results.length; index++) {
		/*for (key in webSearch.results[index]) {
			console.log("<div class='googleResult_" + key + "'>" + webSearch.results[index][key] + "</div>");
			$('div.googleResults', searchResultEntry).append($("<div class='googleResult_" + key + "'>" + webSearch.results[index][key] + "</div>"));
		}*/
		searchResultEntry.append(webSearch.results[index].html);
	}
	$("div.search_results div.content").append("<h4>More Results</h4><div class='clear'>&nbsp;</div>").append(searchResultEntry);
	$("a.gs-title").each(function() {
		href = $(this).attr("href");
		href = href.substring(30);
		$(this).attr("href", href).attr("target", "_self");
	});
	addPaginationLinks();
}

function googleSearchLoadComplete() {
//	searchControl = new google.search.SearchControl();
	webSearch = new google.search.WebSearch();
	webSearch.setSiteRestriction('www.accesshollywood.com');
	webSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
	webSearch.execute(page['modules']['search']['term']);
	webSearch.setSearchCompleteCallback(this, googleSearchComplete, null);
//	searchControl.addSearcher(webSearch);
	googleSearchIsLoaded = true;
}

function clearSearchResults() {
	$('div.search_results').remove();
	//$('#search_term').attr("value","search");
	switch($("body").attr("id")) {
		case 'showcase':
			if($("#container_video_player").size() != 0 && $("ul.tabs li.videos a.active").size() != 0 && parseFloat($("#container_video_player").css("width")) == 1) {
				embeddedPlayerManager.getPlayer().unHidePlayer();
				embeddedPlayerManager.getPlayer().play();
			}
		break;
		case 'showcasesettaborder':
			if($("#container_video_player").size() != 0 && $("ul.tabs li.videos a.active").size() != 0 && parseFloat($("#container_video_player").css("width")) == 1) {
				embeddedPlayerManager.getPlayer().unHidePlayer();
				embeddedPlayerManager.getPlayer().play();
			}
		break;
		default:
			if(parseFloat($("#container_video_player").css("width")) == 1) {
				embeddedPlayerManager.getPlayer().unHidePlayer();
				embeddedPlayerManager.getPlayer().play();
			}
		break;
	}
}

function updateSearchResults(data) {
	if (typeof(googleSearchIsLoaded) == 'undefined') {
		google.load("search", "1", {"callback" : googleSearchLoadComplete});
	}
	data = eval(data);
	clearSearchResults();
	$("body").prepend($(unescape(data.data)));
	if($("#container_video_player").size() != 0 && parseFloat($("#container_video_player").css("width")) != 1) {
		embeddedPlayerManager.getPlayer().pause();
		embeddedPlayerManager.getPlayer().hidePlayer();
	}
	$('div.search_results')
		.css('left',$('#content').offset().left)
		.css('top',$('li#search').offset().top + $('li#search').height() + 3)
		.fadeIn();
	$('div.column').slice(0,$('div.search_results div.column').size()-1).addClass('divider');
	$("div.search_results div.header a").bind("click", function () { clearSearchResults(); });
	currHeight = 0;
	$("div.search_results div.column").each(function (i) {
		if($(this).height() > currHeight) {
			currHeight = $(this).height();
		}
	}).css("height",currHeight);
}

function getSearchResults() {
	page['modules']['search']['term'] = $('#search_term').attr('value');
	$.ajax({
		type: "GET",
		url: "/modules/fetch_module.php",
		data: {
			_file : "search",
			_function : "search_results",
			search: page['modules']['search']['term'],
			dataType: "jsonp",
			jsonp: "jsonp_callback"
		},
		success: function(data){
			updateSearchResults(data);
		}
	});
}

function setUpSearch() {
	var timer = 0;
	$('#search_term').click(function() {
		$(this).val('');
	})
	.keyup(function(e) {
		if (timer != 0) {
			clearTimeout(timer);
		}
		timer = setTimeout(getSearchResults,500);
	});
	$("li#search form").unbind().bind("submit", function () {
		getSearchResults();
        return false;
    });
}

function showProblemElms() {
	switch($("body").attr("id")) {
		case 'showcase':
			if($("#container_video_player").size() != 0 && $("ul.tabs li.videos a.active").size() != 0 && parseFloat($("#container_video_player").css("width")) == 1) {
			embeddedPlayerManager.getPlayer().unHidePlayer();
			embeddedPlayerManager.getPlayer().play();
		}
		break;
		case 'showcasesettaborder':
			if($("#container_video_player").size() != 0 && $("ul.tabs li.videos a.active").size() != 0 && parseFloat($("#container_video_player").css("width")) == 1) {
				embeddedPlayerManager.getPlayer().unHidePlayer();
				embeddedPlayerManager.getPlayer().play();
			}
		break;
		default:
			if(parseFloat($("#container_video_player").css("width")) == 1) {
				embeddedPlayerManager.getPlayer().unHidePlayer();
				embeddedPlayerManager.getPlayer().play();
			}
		break;
	}
}

function hideProblemElms() {
	switch($("body").attr("id")) {
		case 'home':
		case 'article':
			$("div#header970 div#ad").height($("div#header970 div#ad").height());
			$("div#header970 div#ad div").hide();
			if($("#container_video_player").size() != 0 && parseFloat($("#container_video_player").css("width")) != 1) {
                embeddedPlayerManager.getPlayer().pause();
				embeddedPlayerManager.getPlayer().hidePlayer();
            }
		break;
		default:
			if($("#container_video_player").size() != 0 && parseFloat($("#container_video_player").css("width")) != 1) {
                embeddedPlayerManager.getPlayer().pause();
				embeddedPlayerManager.getPlayer().hidePlayer();
            }
		break;
	}
}

function isNumeric(input) {
   return (input - 0) == input && input.length > 0;
}


$(function() {
	// 2009-06-25 AML - Redirect site to wap site if iphone client is detected
	if (cbs.indexOf('iphone') != -1) {
		window.location = 'http://wap.accesshollywood.com';
	}
	
	$("div.promote_21 a").attr("href","javascript:popupWin('http://special.accesshollywood.com/where-to-watch/','popup','width=440,height=315')");
	
	$('.module').bind("mouseover", function() {
		var moduleName = $(this).attr('class');
		moduleName = moduleName.slice(7); // skip 'module ' in class for modules
		$.cookie('moduleName', moduleName);
	});
	
	if($.browser.msie) {
		$("img[@src*=png]").css("behavior", "url(/assets/css/iepngfix.htc)");
		$("div.freshbuzz div.sponsorship img").width("71");
		$("div.oscars div.sponsorship img").width("58");
		$("div.rising-star div.sponsorship img").width("94");
		$("div.fashion-moments div.sponsorship img").width("51");
		$("div.platinum-moments div.sponsorship img").width("132");
		$("div.glam-slam div.sponsorship img").width("124");
		$("div.jewels-of-the-red-carpet div.sponsorship img").width("118");
		$("div.sundance div.sponsorship img").width("100");
	}
	
	if($("body").attr("id") != "showcase") {
		setUpColumnHeights();
	}
	
	if($("body").attr("id") != "video") {
		$.cookie('videosPlayed', null);
	}
	
	setUpTags();
	
	setUpSearch();
	
	// RAILS CODE
	if((typeof(railAdBg)!='undefined')&&(railAdBg)) {
		// site specific custom background code.
		$('body').css({'background-image':'url('+railAdBg+')','background-position':'top center'})
	}
	if((typeof(railAdBgColor)!='undefined')&&(railAdBgColor)) {
		// site specific custom background color code.
		$('body').css({'background-color':railAdBgColor});
	}
	if((typeof(railAdBgRepeat)!='undefined')&&(railAdBgRepeat)) {
		// site specific custom background repeat code.
		$('body').css({'background-repeat':railAdBgRepeat});
	}
	if((typeof(railAdBgClickthru)!='undefined')&&(railAdBgClickthru)) {
		// site specific custom background click event code.
		switch($("body")[0].id) {
			case 'showcase':
				elm = '#container'
			break;
			default:
				elm = 'body';
			break;
		}
		$(elm).click(function (e) { evt = e || window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // Safari bug
		targ = targ.parentNode;
		if (targ.id == 'home' || targ.id == 'container') {
			window.open(railAdBgClickthru);
		}});
		//$('#'+$('body').attr('id')).bind('click',function () { window.open(railAdBgClickthru); });
		$('body').bind('mouseenter',function () { $(this).css('cursor','pointer'); });
		$('body').bind('mouseleave',function () { $(this).css('cursor','default'); });
	}
	
	$("#header970 a[@href*=facebook.com],#header970 a[@href*=twitter.com], #header a[@href*=facebook.com], #header a[@href*=twitter.com]").attr("target", "_blank");
	
	if(typeof fbc_init != "undefined") {
		fbc_init();
	}

	$("a[@href=/bookmark-access]").bind("click", function () {
		title = "AccessHollywood.com!";
		url = "http://www.accesshollywood.com/";
		if (window.external && window.external.AddFavorite) {
			window.external.AddFavorite(url,title);
		} else if (window.sidebar && window.sidebar.addPanel) {
			window.sidebar.addPanel(title,url,'');
		}
		return false;
	});
});