/************************************************************************
 *	Home Page Header JavaScript
 ************************************************************************/

// Copyright statement will remain when we compress / minify
var Copyright = '## Copyright (c) 2008-2010 LinkTix, Inc. All rights reserved. ##';

var linktixUrl = 'http://www.facebook.com/add.php?api_key=7d26b0c073285b6b0e3ad808c5ae01ee&app_ref=dotCom';
var ltHostUrl  = '/linktix/';
var isFBConnect = (location.search.indexOf('isfbc=1') > 0);
var hintText, sportsLinks={list:null, pointer:0}, concertLinks={list:null, pointer:0}, theaterLinks={list:null, pointer:0};
var ltURL = null, currTab = null;

$(document).ready( function() {
	// Check for a deep link request
	var deepLink = location.search.match(/page=([a-zA-Z0-9_\/%]+)/);

	// Remember the hint text and set it incase the page is refreshed
	hintText = ($("#sQuery").length) ? $("#sQuery").get(0).defaultValue : '';
	$("#sQuery").val(hintText);

	// Create the URL object used to load different modules
	var urlMatch = location.href.match(/^(https?:\/\/)([^\/]+)(\/[^\?]*)(.*)$/i);
	if (urlMatch && urlMatch.length >= 4) {
		ltURL = {
			protocol:	urlMatch[1],
			server:		urlMatch[2],
			module:		urlMatch[3],
			queryStr:	(urlMatch.length == 5) ? cleanUrl(urlMatch[4]) : ''
		};
	}

	// To resize Facebook iFrame based on contents
	setTimeout(keepFrameSize, 100);

	$('img').supersleight();

	if (deepLink) {
		pageLoad(null, '/linktix/v3/'+ deepLink[1] +'.html'+ location.search);
		return;
	}

	processLinkStatus();

	window.isLtLoading=1;
	setTimeout(hideLoading, 100);
});

// Function to keep the iFrame height consistent with the height of the content
function keepFrameSize() {
	var tabFrameObj = $('#frameContainer');
	var tabFrameHeight = tabFrameObj.height();
	var docHeight = 0;

	try {
		docHeight = (window && window.frames && frames['tabFrame'] && frames['tabFrame'].document && frames['tabFrame'].document.body) 
					? (frames['tabFrame'].document.body.clientHeight - 30)
					: null;
	}
	catch(e){ }

	// Resize only if necessary (when document is too tall or too short)
	if (docHeight && (docHeight > tabFrameHeight || (tabFrameHeight-docHeight) > 20)) {
		var newHeight = parseInt(docHeight)+30;
		if (newHeight < 500) newHeight = 500;

		tabFrameObj.css({ height: newHeight +'px' });
		$('#tabFrame').css({ height: newHeight +'px' });
	}

	// Check every second
	setTimeout(keepFrameSize, 1000);
}

// Show the contact-us pop-up overlay
function popContactUs() {
	var html = '<div id="formBox"><b class="appTitle">Contact LinkTix</b><br><br><br>'
				+'<form id="contactUsForm" method="post" action="javascript:sendMail()">'
				+'<input type="hidden" name="attn" value="Contact from LinkTix.com" />'
				+'Name: <br><input type="text" name="visitor" size="35" /><br><br>'
				+'Email Address:<br><input type="text" name="visitormail" size="35" /><br><br><br>'
				+'Message:<br><textarea name="notes" rows="4" cols="40"></textarea><br>'
				+'<center><input class="inputbutton" type="submit" value="Send" /></center></form><br><br><br><br></div>';

	$.facebox.settings.boxWidth = 350;
	$.facebox( html );
}

// Submit the e-mail via Ajax / PHP
function sendMail() {
	var postData = $("#contactUsForm").serialize() +"&done=true";
	if (postData.search(/=&/) > 0) {
		alert("Please fill out all fields");
		return;
	}

	$.ajax({
		type: "POST",
		url: "send.php",
		data: postData,
		success: function(str, postStatus) {
			if (postStatus == "success") {
				$("#formBox").hide();
				$.facebox.reveal('<br><br><br><p align="center" class="basic-heading"><b>Thank You!</b></p><br><br><br>');
				setTimeout( $.facebox.close, 2000 );
			}
			else {
				alert("Error: "+ str, "Unable to send e-mail");
			}
		},
		error: function(xhr, postStatus, theError) {
			alert("Error ("+ ((theError) ? theError : xhr.status)  +") : "+ ((xhr && xhr.statusText) ? xhr.statusText : "Error"),
					"Unable to send e-mail");
		}
	});
}

// Launch the search module based on the query
function launchSearch() {
	var inBox = $("#ssQery");
	var qStr = inBox.val();
	if (qStr == hintText) {
		qStr=''
	}
	location.href = ltHostUrl +'main.html?'+ (isFBConnect ? 'isfbc=1' : 'isfb=0') +'&menu=none&page=search&'+ ((qStr) ? ('q='+ qStr) : 'defQuery=&advSearch=Y');
}

// Launch the search module with a popular event
function launchPopularEvent(pid) {
	location.href = ltHostUrl +'main.html?isfb=0&menu=none&page=search&pid='+ pid;
}


// Reset all tabs to unselected
function resetTabs() {
	$('#navlist li a').removeClass("current");
}

// Set a specific tab
function setTab(newLink) {
	// Avoid re-setting the current tab
	if (currTab != newLink) {
		resetTabs();

		if (newLink) {
			newLink.addClass("current");
			currTab = newLink;
		}
	}
}

// Called by the tabs
function pageLoad(newLink, tabModule, keepTabs, loadText) {

	if (!keepTabs)
		setTab(newLink);

	// Load the tab contents
	if (ltURL) {
		showLoading(loadText);
		var newURL = ltURL.protocol + ltURL.server + tabModule
                + ((ltURL.queryStr.charAt(0)=='?' && tabModule.indexOf('?') > 0) ? ltURL.queryStr.replace(/^\?/,'&') : ltURL.queryStr);

		newURL += ((newURL.indexOf('?') > 0) ? '&' : '?') + (isFBConnect ? 'isfbc=1' : 'isfb=0') + '&dc=' + (new Date()).getTime();

		var tFrame = frames['tabFrame'];
		if (tFrame && tFrame.location) {
			tFrame.location.href = "about:blank";
			setTimeout(function() { tFrame.location.href = newURL; }, 100);
		}
		else
			tFrame.src = newURL;
	}

	// Scroll to top of page. Mobile browsers may not support this because of the UI placement of the Search Query box
	if (!isMobile())
		$("#sQuery").focus().blur();  // Scroll to top is performed by forcing focus on the Search Query box
}

// Submit the event search
function submitSearch(loadText, usePid, caller) {
	var inputVal = $("#sQuery").val();
	if (inputVal == hintText)
		inputVal='';

	if (!usePid && (!inputVal || inputVal.search(/[a-zA-Z0-9]/) < 0)) {
		// When the query is blank or invalid, we call Advanced Search
		$("#sQuery").val('');
		pageLoad(null, '/linktix/v3/ltEventSearch.html?advSearch=Y&defQuery=');
		return;
	}
	resetTabs();

	var url = $("#search_form").attr('action');
	if (url)
		$("#search_form").attr('action', url + (isFBConnect ? '?isfbc=1' : '?isfb=0') + (usePid ? ('&pid='+ usePid) : ''))

	// Submit
	$("#query").val( caller ? $(caller).text() : inputVal );
	showLoading(loadText ? loadText : 'Searching events...');
	$("#btnSubmit").trigger("click");
	$("#sQuery").val('');
	restoreHint($("#sQuery"));
}

// Show the "Loading..." display while loading the next page
function showLoading(msg) {
	var iFrameDoc = frames["tabFrame"].document;
	if (!iFrameDoc || window.isLtLoading) return;

	var mainDivs = iFrameDoc.getElementsByTagName('div');
	if (mainDivs) {
		if (mainDivs.length)
		mainDivs[0].style.display = "none";

		if (frames["tabFrame"].ltDialog)
			frames["tabFrame"].ltDialog.hideDialog();  // Hide any dialogs

		// Ensures that the UI does go white before the loading message appears
		setTimeout(function() {
			$("#loadingMsg").text( (msg) ? msg : 'Loading...' );
			$("#loadingDiv").css({ left: '510px' });
		}, 100);

		// Scroll to top of page. Mobile browsers may not support this because of the UI placement of the Search Query box
		if (!isMobile())
			$("#sQuery").focus().blur(); // Scroll to top is performed by forcing focus on the Search Query box

		window.isLtLoading = true;
	}
}

// Try to Hide the Loading display when the frame has content
function hideLoading() {
	var iFrameDoc = frames["tabFrame"].document;
	if (!iFrameDoc || !window.isLtLoading) {
		isLtLoading=false;
		return;
	}

	$("#loadingDiv").css({ left: '-640px' });
	isLtLoading=false;
}

// Clean the Query String URL to remove one-time use parameters and avoid having these perpetuate when loading the next pages
function cleanUrl(qstr) {
	return qstr.replace(/page=[^&]+&?/,'')
				.replace(/evid=[^&]+&?/,'')
				.replace(/type=[^&]+&?/,'')
				.replace(/msgid=[^&]+&?/,'');
}

// Submit on Enter key
function checkEnter(evt){
	if (!evt) evt = window.event;

	if ((evt.which || evt.keyCode) == 13)
	{
		var inBox = $("#sQuery");
		var qStr = inBox.val();
		if (!qStr || qStr == hintText)
			restoreHint(inBox.get(0));
		else
			submitSearch();
		return false;
	}
}

// Remove the hint so that users can type
function removeHint(obj) {
	var inBox = $(obj);
	if (inBox.val() == hintText)
		inBox
			.css({color: '#333' })
			.val('');
}

// Restore the hint so that users can type
function restoreHint(obj) {
	var inBox = $(obj);
	if (!inBox.val())
		inBox
			.css({color: '#999' })
			.val(hintText);

	obj.blur();
}

// Populate the URL of links with descriptive text for the status bar
function processLinkStatus() {
	setTimeout(function() {
		if (!$.browser.webkit) {
			$("a").each( function() { 
				var o = this;
				if (o.href == 'javascript://') {
					var ot=$(this).text();
					if (!ot)
						ot = o.title;
			
					if (ot)
						o.href = 'javascript://   '+ $.trim(ot);
				}
			});
		}
	}, 100);
}

// Launches the main FB Connect site
function launchSite(isAuto) {
	var qs = location.search;
	if (qs) {
		qs = qs.replace(/\?isfb=0/,'?isfbc=1'); // Flag Facebook Connect
		if (qs != '?')
			qs += '&';
	}
	else
		qs = '?';

	// Once we are in FB Connect mode, we disable most of the UI and load the LinkTix FB Connect version in an iFrame
	if (isFBConnect) {
		qs = qs.replace(/&menu\=[^&]+&/,'&').replace(/&page\=[^&]+&/,'&');
		//setTimeout(function() { frames['mainFrame'].location.href = '/linktix/head.html'+ qs }, 1000);
		alert(qs);
	}
	// Show the "Connect with Facebook" button before lauching the App in FB Connect mode
	else if (isAuto) {
		$("#loginBox").show();
		$("#loginInst").fadeIn();
	}
	// We are ready to launch the FB Connect version of LinkTix. We do this via a redirect
	else if (window.api) {
		$("#loginBox").hide();
		$("#loginInst").hide();
		qs = qs.replace(/&menu\=[^&]+&/,'&').replace(/&page\=[^&]+&/,'&');
		location.href = '/linktix/main.html'+ qs +'fb_sig_api_key='+ fbApiKey +'&fb_uid='+ api.get_session().uid;
	}
}

// Start processing the Facebook Engine
function startFB(fbApiKey) {
	var fFrame = frames['fbcFrame'];
	if (fFrame && fFrame.location)
		fFrame.location.href = "fbConnect.htm?fb_sig_api_key="+ fbApiKey;
	else
		fFrame.src = "fbConnect.htm?fb_sig_api_key="+ fbApiKey;
}

// Once Connected, change the top-right UI to the "connected" mode
function fbConnected() {
	var fFrame = frames['fbcFrame'];
	if (fFrame && fFrame.location)
		fFrame.location.href = "fbConnected.htm?fb_sig_api_key="+ fbApiKey;
	else
		fFrame.src = "fbConnected.htm?fb_sig_api_key="+ fbApiKey;
}

// Load the FB Connect Launcher
function fbLauncher(skipPage) {
	var fFrame = frames['fbcFrame'];
	if (fFrame && fFrame.location)
		fFrame.$("#loginBox").hide();

	if (!skipPage)
		pageLoad(null, "/linktix/website/v3/homepage/fbConnectLauncher.htm?fb_sig_api_key="+ fbApiKey);
}

// Get the Ticket Contacts using the standard ltHead.jsp call via Ajax
function getTNcontacts( ) {
	if (window.updateTNcontacts) {
		$.get('/linktix/v3/ltHead.html?isfb=0', function(data) {
			var found = data.match(/<a id\=.mytnLink. .+>([^<]+)<\/a>/i);
			if (found && found.length > 1)
				window.updateTNcontacts(found[1]);
		});
	}
}

// Supersleight jQuery Plugin for Transparent PNGs in IE6 (by Drew McLellan)
// http://allinthehead.com/retro/338/supersleight-jquery-plugin
jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: 'images/shim.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
					self.css('position', 'relative');
				};
			});
		};
	});
};

