
function ajaxError(){alert('Error loading from server.\n Click "OK" to try again'); window.location = '/';}

var cbeTmr=0;
var cbeRty=0;
var cbeCB=0;
function getScriptCB(callback){
	if (cbeCB==0){cbeCB=callback;}
	try{cbeCB();} 
	catch(e){if (cbeRty++ > 50){ajaxError(); cbeRty=0; return false;} debugMsg('Callback Error - retrying');	cbeTmr=setTimeout(callbackExec,100); return false;}
	cbeRty=0;
	cbeCB=0;
}
var getScriptData=[]; // url, callback, retryTimer=0, retries = 0, ready = false, pending=false, cache=false
// States: pending=true after ajax start, loaded=true after ajax done, ready=true after callback called without error
// Assume cache is always true?
function onScriptLoad(url){
	// find the loaded script
	var keyFound=false; var x=0; var thisScript={};
	$.each(getScriptData,function(i, val){if (val.url == url){keyFound = true; x=i; thisScript=val; return false;}});
	if (!keyFound) {alert('Unknown script was loaded');}
	getScriptData[x].loaded=true;
	getScriptData[x].pending=false;
	try{getScriptData[x].callback();}
	catch(e){
		if(thisScript.retries > 50) {ajaxError(); getScriptData[x].retries=0; return false;}
		getScriptData[x].retries++;
		debugMsg('Callback Error - retrying '+thisScript.url);	getScriptData[x].retryTimer=setTimeout(function(){onScriptLoad(thisScript.url);thisScript=null;},100); 
		return false;
	}
	getScriptData[x].ready=true;		
	return true;
}
$.getScript = function(url, cache, callback){ 
	var keyFound = false;	var x=0; var thisScript={};
	$.each(getScriptData,function(i, val){
			if (val.url == url){keyFound = true; x=i; thisScript=val; return false;}
	});
	if (!keyFound){
		thisScript={url:url, callback:callback, cache:cache, retries:0, ready:false, pending:false, loaded:false, retryTimer:0};
		getScriptData.push(thisScript);
		x=getScriptData.length-1;
	}
	if (thisScript.ready) {callback(); return true;} // callback previously called without error
	if (thisScript.loaded) {onScriptLoad(url); return true;}
	getScriptData[x].pending=true;
	$.ajax({ type: "GET", url: url, success: function(){onScriptLoad(url); return true;}, dataType: "script", cache: cache}); 
	return true;
}; 

function scriptsReady(){var ready=true;	$.each(getScriptData,function(i, val){if (val.ready==false){ready=false; return false;}}); return ready;}

var getCSSCache=[];
var getCSSTimer='';
$.getCSS = function(url){ 
  if ($.inArray(url, getCSSCache) > -1 ) return true;
  else getCSSCache.push(url);
  $('head').append('<link type="text/css" href="'+url+'"  rel="stylesheet" media="screen">');	return true;
}; 


$.postTIJSON = function(url, data, callback) {
  data.tg_format = 'json';
  $.post(url, data, callback, "json");
};

$.postTIManualJSON = function(url, data, callback) {
  data.format = 'json';
  $.post(url, data, callback);
};

$.postTIJSONSync = function(url, data, callback){
	data.tg_format = 'json';
  	$.ajax({
	  type: "POST",
  	  dataType: "json",
	  url: url,
	  data: data,
	  async: false,
	  success: callback
	});
};


$.getTIJSON = function(url, data, callback) {
  var RandomNumber=Math.floor(Math.random()*999999);
  data.random_num = RandomNumber;
  data.tg_format = 'json';
  $.getJSON(url, data, callback);
};

String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");};
String.prototype.ltrim = function() {return this.replace(/^\s+/,"");};
String.prototype.rtrim = function() {return this.replace(/\s+$/,"");};
String.prototype.startsWith = function(t, i) { 
	if (!i) { return (t == this.substring(0, t.length)); } 
	else { return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); } 
};

String.prototype.endsWith = function(t, i) {
	if (!i) { return (t == this.substring(this.length - t.length)); } 
	else { return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase()); } 
}; 


$(document).ajaxError(function(event, request, settings){
	if(request.status.toString()[0]=='3'){
	   window.location = '/';
   }
   if(request.status.toString()[0]=='5'){ajaxError();}
   return false;
});
var debugInit=false;	
function debugMsg(message){if(DebugOn){ 
	if (remoteDebug) $.postTIJSON("/report_error", {msg: message, tg_format: 'json'}, function(data){return true;} );
	if(hasFirebug) {try{console.log(message);} catch(e){} } else $('#debugMessage').show().append('<p>'+message+'</p>');}
}

var LMOS = new function(){
	this.SWFHideFuncs = []; 
	this.currentApp='';
	this.SWFHideDepth = 0;
	this.SWFHideKeys = [];
	this.SWFAutoHide = function(name,hide,show){
      var keyFound = false;
      $.each(LMOS.SWFHideFuncs,function(i, val){
          if (val.name == name){val.active = true; keyFound = true; return true;}
      });
      if (keyFound) return true;
      var newKey={name:name,hide:hide,show:show,active:true};
      LMOS.SWFHideFuncs.push(newKey); 
      return LMOS.SWFHideFuncs.length-1; 
  };
	this.SWFAutoHideCancel = function(name){
      var keyFound = false;
      var index=-1;
      $.each(LMOS.SWFHideFuncs,function(i, val){
          if (val.name == name){val.active = false; keyFound = true; return true;}
          index=i;
					return true;
      });
      if (keyFound) return true;
      else debugMsg('SWFAutoHideCancel error missing key');
			return true;
	};
	this.SWFHideKeys = [];
	this.SWFHide = function(key){
		for(var i = 0; i < LMOS.SWFHideFuncs.length; i++) {
        	if(LMOS.SWFHideFuncs[i].active){
              try {LMOS.SWFHideFuncs[i].hide(); }
              catch(e) {debugMsg(e);}
          }
		}
		var keyFound = false;
		$.each(LMOS.SWFHideKeys,function(i, val){
			if (val.key == key){ val.active = true; keyFound = true; return true;}
		});
		if (keyFound) return true;
		var newKey={key:key, active:true};
		LMOS.SWFHideKeys.push(newKey);
		return true;
	};
	this.SWFShow = function(key){
		var keyFound = false;
		$.each(LMOS.SWFHideKeys,function(i, val){
			if (val.key == key) val.active = false;
			if(val.active){ keyFound = true; return true;}
		});
		if(keyFound) return false;
		for(var i = 0; i < LMOS.SWFHideFuncs.length; i++) {
        	if(LMOS.SWFHideFuncs[i].active){
              try { LMOS.SWFHideFuncs[i].show(); }
              catch(e) {debugMsg(e);}
          }
		}
		return true;
	};
	this.skinChangeCallbackFuncs = []; 
	this.skinChangeCallback = function(callback){ LMOS.skinChangeCallbackFuncs.push(callback); return LMOS.skinChangeCallbackFuncs.length-1;};
	this.skinChange = function(){var t=setTimeout("LMOS.skinChangeDelayed();",500);};
	this.skinChangeDelayed = function(){
		for(var i = 0; i < LMOS.skinChangeCallbackFuncs.length; i++) {
        	try { LMOS.skinChangeCallbackFuncs[i](); }
        	catch(e) {debugMsg(e);}
		}
	};
	this.eventCallbackFuncs = [];
	this.addEventListener = function(eventId, callback){var listenerId=Math.floor(Math.random()*999999); LMOS.eventCallbackFuncs.push({eventId:eventId, callback:callback, listenerId:listenerId, active:true}); return listenerId;};
	this.eventTrigger = function(eventId,parameter){		
		for(var i = 0; i < LMOS.eventCallbackFuncs.length; i++) {
    	if (LMOS.eventCallbackFuncs[i].eventId != eventId || !LMOS.eventCallbackFuncs[i].active) continue;
			try { LMOS.eventCallbackFuncs[i].callback(parameter);}
    	catch(e) {debugMsg(e);}
		}
		return true;
	};
	this.removeEventListener = function(listenerId){
		for(var i = 0; i < LMOS.eventCallbackFuncs.length; i++) {
    	if (LMOS.eventCallbackFuncs[i].listenerId == listenerId) LMOS.eventCallbackFuncs[i].active=false;
		}
		return true;
	};

	
	this.browser=function(){
		var bType="unknown";
		if ($.browser.msie) bType = "IE";
		else if ($.browser.safari) bType = "Safari";
		else if ($.browser.mozilla) bType = "FF";
		else if ($.browser.opera) bType = "Opera";
		return {type: bType, version: $.browser.version};
	};
	this.busyTimeoutVar = 0;
	this.showBusy = function(){
		LMOS.SWFHide('busy');
		$('#LoadingOverlay').removeClass('hidden');
		$('#pageBusyIndicator').removeClass('hidden');
		clearTimeout(LMOS.busyTimeoutVar);
		LMOS.busyTimeoutVar=setTimeout("LMOS.busyTimeout()",30000);
	};
	this.busyTimeout=function(){LMOS.hideBusy(); debugMsg('Timeout waiting for system.'); return true;};
	this.hideBusy = function(){
		clearTimeout(LMOS.busyTimeoutVar);
		LMOS.SWFShow('busy');
		$('#pageBusyIndicator').addClass('hidden');
		$('#LoadingOverlay').addClass('hidden');
	};
	this.emptyFunction=function(){return true;};
	this.navUpdate=function(){
		$.getTIJSON("/main/nav_read",{}, function(data){
			$('#appNav').empty();
			siteApps=data.nav;
			var navHTML='';
			$.each(data.nav,function(i,app){
				navHTML='<li id="'+app.subtype+'" class="appTab mainNavLink" title="'+app.description+'"><a href="'+app.url+'" onclick="LMOS.changeURLApp(\''+app.subtype+'\'); return false;" >';
				if (UserIsEditor && (app.app_type=='StoryPage' || app.app_type=='CustomApp')) navHTML += '<strong id="edit_'+app.subtype+'" class="hidden navEditLink" title="Edit this page" />';
				navHTML +=	'<strong class="icon '+app.icon+'" />'+app.label;
			 	navHTML += '</a><span class="navLinkEnd" /></li>';
				$('#appNav').append(navHTML);
			});
			$('#appNav').append('<div class="spacer" />');
			$('.navEditLink').bind("click",function(){LMOS.editCurrentPage(); return false;});
			LMOS.eventTrigger('ChangeApp',{app:LMOS.currentURL.app});
			$('#edit_'+LMOS.currentApp).removeClass('hidden'); //Add edit icon if needed
		});
		return true;
	};	
	
	this.appClose=function(){return true;};
	this.appURLUpdated=function(){return true;};
	this.URLMonitorTimer = 0;
	this.initURLMonitor = function(){URLMonitorTimer = setInterval("LMOS.URLProcess();",300); return true;};
	this.currentURL = {app:"",paramA:"",paramB:""};
	this.currentAppData={};
	this.freezeTab = false;
	this.URLProcess = function(){
		var newURL = getURL();
		var oldURL=LMOS.currentURL;
		LMOS.currentURL=newURL;
		//if (newURL.app.length < 1) $('.appTab :first').click();
		if (oldURL.app != newURL.app){
			var newApp=newURL.app;
			var appURL = false;
			var siteAppEntry = $.grep(siteApps,function(app,i){return (app.subtype == newApp);});
			if (siteAppEntry.length > 0) {siteAppEntry=siteAppEntry[0]; appURL = siteAppEntry.ajax_url;}
			if(appURL){
				if (!LMOS.appClose()){LMOS.currentURL=oldURL; return false;}
				LMOS.appClose=LMOS.emptyFunction;
				LMOS.appURLUpdated=LMOS.emptyFunction;
				LMOS.showBusy();
				LMOS.currentApp=newURL.app;
				LMOS.currentAppData=siteAppEntry;
				LMOS.eventTrigger('ChangeApp',{app:newApp});
				$('.navEditLink').addClass('hidden');
				var RandomNumber=Math.floor(Math.random()*999999);
				if (LMOS.currentAppData.app_type != 'CustomApp') $('#appMain').load(appURL+'?'+RandomNumber, function(){
					LMOS.eventTrigger('AppLoaded',{app:LMOS.currentApp});
					if (LMOS.currentAppData.app_type == 'StoryPage') $('#edit_'+LMOS.currentApp).removeClass('hidden');
					LMOS.initComponents();
					return true;
				});
				else LMOS.customAppInit(appURL);
			}
			else $('.appTab :first').click();
		}
		else if(oldURL.paramA != newURL.paramA || oldURL.paramB != newURL.paramB){
			LMOS.appURLUpdated();
		}
		return true;
	};
	this.initApps = function(){
		if (deepLink.length > 0) window.location.hash=deepLink;
		$('.navEditLink').bind("click",function(){LMOS.editCurrentPage(); return false;});
		var URLParams=getURL();
		if (URLParams.app.length < 1) $('.appTab:first a').click();
		LMOS.initURLMonitor();
		LMOS.addEventListener('ChangeApp',LMOS.changeAppTab);
		return true;
	};
	this.changeURLApp=function(app){
		window.location.hash = '/'+app;
		return false;
	};
	this.changeURLParamA=function(paramA){
		window.location.hash = '/'+LMOS.currentURL.app+'/'+paramA;
		return false;
	};
	this.changeURLParamB=function(paramB){
		window.location.hash = '/'+LMOS.currentURL.app+'/'+LMOS.currentURL.paramA+'/'+paramB;
		return false;
	};
	this.changeURL=function(url){window.location.hash = '/'+url; return true;};
	this.changeAppTab=function(param){ $('#appNav .appTab').removeClass('activeTab');	$('#'+param.app).addClass('activeTab');	return true; };
	this.customAppInit=function(appURL){
		$('#edit_'+LMOS.currentApp).removeClass('hidden');
		LMOS.customAppState='123ef1345f13';
		LMOS.appURLUpdated=LMOS.customAppNewURL;
		LMOS.customAppNewURL();
	};
	this.customAppClose=function(){
		return true;
	};
	this.customAppState='';
	this.customAppNewURL=function(){
		var state = LMOS.currentURL.paramB;
		if (state != LMOS.customAppState){
			debugMsg('trace: state change');
			LMOS.customAppState = state;
			var RandomNumber=Math.floor(Math.random()*999999);
			var appURL = LMOS.currentAppData.ajax_url+'?'+RandomNumber;
			if (state=='edit'){
				appURL = '/custom/page_edit?page='+LMOS.currentAppData.subtype+'&random='+RandomNumber;
				$('#appMain').load(appURL, function(data){LMOS.hideBusy(); return true;});
			}
			else {
				$('#appMain').html($('#customPageContainerPrototype').clone().attr('id','customPageContainer').removeClass('hidden'));
				//$('#customPageContainerPrototype').clone().attr('id','customPageContainer').removeClass('hidden');
				$('#customPageContainer').load(appURL, function(data){LMOS.initComponents(); LMOS.hideBusy(); return true;});
			}
		}
		return true;
	};
	this.editCurrentPage=function(){LMOS.changeURLParamB('edit'); return true;};
	this.initSafeComponents=function(){
		// Replace elements with class-defined HTML snippets
			$('.buttonNormal').wrap('<span class="buttonA pageButton"></span>').after('<span />');
			$('.fancyTextInputLabel').click(function(){$(this).addClass('hidden').siblings('.fancyTextInput').focus();});
			$('.spinbox').each(function(){$(this).spinbox($(this).metadata());});			
			// Form submits with buttons
			// Attach handlers to events (form submit, etc)
			$('.submit').click(LMOS.formSubmitHandler);
	};
	this.initComponents=function(){
		$().ready(function(){
			// Replace elements with class-defined widgets
			$('.mediaWidget').mediaWidget({parent:LMOS.currentAppData.identifier});
			LMOS.initSafeComponents();
		});
		return true;
	};
	this.formSumbmitHandler=function(element){
		debugMsg(element);
	};
	this.password = "";
	this.passwordGetMsg = "";
	this.passwordGetSubmitCallback = function(){return true;};
	this.passwordGetCancelCallback = function(){return true;};
	this.passwordGet = function(){LMOS.hideBusy(); $("#PasswordDialog .dialog-message").html(LMOS.passwordGetMsg).removeClass("hidden"); $("#PasswordDialog").dialog("open"); return true;};
	this.passwordDialogOpen=function(){
		$("#PasswordDialog").bind("keypress", function(e) {if (e.keyCode == 13) LMOS.passwordDialogSubmit(); });
		$("#PasswordDialog").bind("keypress", function(e) {if (e.keyCode == 27) LMOS.passwordDialogCancel(); });
		$("#PasswordDialog").dialog("moveToTop");
		return true;												  
	};
	this.passwordDialogCancel=function(){LMOS.passwordDialogClose(); LMOS.passwordGetCancelCallback(); return false;};
	this.passwordDialogClose=function(){$("#PasswordDialog").dialog("close"); return true;};
	this.passwordDialogSubmit=function(){
		LMOS.password = $('input[name="DialogPassword"]').val();
		LMOS.passwordGetSubmitCallback();
		this.passwordDialogClose();
		return true;
	};
	//this.loginDialogCancel=function(){$("#loginDialog").dialog("close"); return true;};
	this.loginJoinAction = 'login';
	this.loginJoinSwitch = function(action){
		if (action == 'join'){
			$('#loginDialogLink').text('Create Account').attr('title','Create a new LiveMosaic Account');
			LMOS.loginJoinAction = 'join';
			$('#homeLoginLogin').addClass('hidden');
			$('#homeLoginJoin').removeClass('hidden');
		}
		if (action == 'login'){
			$('#loginDialogLink').text('Sign In').attr('title','Sign In with Your LiveMosaic Account');
			LMOS.loginJoinAction = 'login';
			$('#homeLoginLogin').removeClass('hidden');
			$('#homeLoginJoin').addClass('hidden');
		}
		return true;
	};
	this.loginSubmit=function(){
		var uName = $('#loginUserName').val();
		var rm = $('#loginRemember').attr('checked');
		if (LMOS.loginJoinAction == "login"){
			var pw = $('#loginLoginPassword').val();
			var loginPath = staticPaths.corpSite+'action/login?forward_to_site=True&forward_url='+LMOS.getLink()+'&login=login&auto_login=True&password='+pw+'&user_name='+uName+'&ti_max='+rm;
		}
		if (LMOS.loginJoinAction == "join"){
			/*user_name: $("#joinUserName ").val(), first_name: $("#joinFirstName").val(), last_name: $("#joinLastName").val(),
	     password: $("#joinPassword").val(), val_password: $("#joinPassword").val(), ti_max: $('#join_ti_max').val(), join: 'yes'
			*/
			pw = $('#loginJoinPassword').val();
			var fn = $('#loginJoinFirstName').val();
			var ln = $('#loginJoinLastName').val();
			loginPath = staticPaths.corpSite+'action/join?forward_to_site=True&forward_url='+LMOS.getLink()+'&join=yes&auto_join=True&password='+pw+'&val_password='+pw+'&user_name='+uName+'&first_name='+fn+'&last_name='+ln+'&ti_max='+rm;
			if (! $("#loginJoinAgree").attr("checked")) {alert("Please Agree LiveMosaic's Policies"); return false;}
		}
		$('#loginLink').attr('href',loginPath);
		//$("#loginDialog").dialog("close"); 
		return true;
	};
	/*this.loginDialogOpen=function(){
		LMOS.SWFHide('login');
		return true;
	};
	this.loginDialogClose=function(){
		LMOS.SWFShow('login');
		return true;
	};*/
	this.login=function(){LMOS.hideBusy(); LMOS.changeURLApp('home'); alert('Please sign in with a free LiveMosaic account to use this feature'); return true;};
	this.getLink=function(){
		var retLink=staticPaths.currentSite+'/link/'+LMOS.currentURL.app;
		if (LMOS.currentURL.paramA != "") retLink+= '/'+LMOS.currentURL.paramA;
		if (LMOS.currentURL.paramB != "") retLink+= '/'+LMOS.currentURL.paramB;
		return retLink;
	};
	this.statusMessage=function(statusClass,message,detail){	
		if (message==="") { 
			$("#messageIcon").removeClass();
			$("#appControlsMessage .messageHeadline").html('');
			$("#appControlsMessage .messageDetail").html('');
			$('#appControlsMessageContainer').addClass('hidden'); return true;
		}
		$('#appControlsMessageContainer').removeClass('hidden');
		$("#appControlsMessage").animate({top: "-40px"},200,function(){
			$("#messageIcon").removeClass().addClass(statusClass).addClass('icon');
			$("#appControlsMessage .messageHeadline").html(message);
			$("#appControlsMessage .messageDetail").html(detail);
		}).animate({top: "0px"},400);
		return true;
	};
	this.ensureDefault=function(setting, defaultValue) {return (setting == undefined) ? defaultValue : setting;};
	this.validateEmail=function(str){
		if ((str===null)||(str==="")) return false;
		var at="@"; var dot="."; var lat=str.indexOf(at); var lstr=str.length; var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1) return false;
		if (str.indexOf(at)==-1 || str.indexOf(at)===0 || str.indexOf(at)==lstr) return false;
		if (str.indexOf(dot)==-1 || str.indexOf(dot)===0 || str.indexOf(dot)==lstr) return false;
		if (str.indexOf(at,(lat+1))!=-1) return false;
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
		if (str.indexOf(dot,(lat+2))==-1) return false;
		if (str.indexOf(" ")!=-1) return false;
 		return true;
	};
	this.emailListProcess=function(emailList){
		var validate=true;
		var rtnList=emailList.split(/[\s,;\n]+/);
		if (rtnList[0].length < 1) return false;
		$.each(rtnList,function(i, val){
			if (!LMOS.validateEmail(val)) {validate=false; return false;}
		});
		if (!validate) return false;
		return rtnList;
	};
	this.wizardSteps=[];
	this.wizardMessage='';
	this.wizardNextURL='';
	this.wizardLastURL='';
	this.wizardNextOkay=function(){return true;}; 
	this.wizardCancelOkay=true; this.wizardCurrentStep=0;
	this.wizardActive=false;
	this.wizardTitle='';
	this.wizardUpdate=function(){
		if (LMOS.wizardCurrentStep == LMOS.wizardSteps.length) {
			if (LMOS.wizardNextOkay) $('#wizardDoneBtn').removeClass('inactive');
			else $('#wizardDoneBtn').addClass('inactive');
			$('#wizardDoneBtn').removeClass('hidden');
			//$('#wizardNextBtn').addClass('hidden');
		} 
		else{
			$('#wizardDoneBtn').addClass('hidden');
			$('#wizardNextBtn').removeClass('hidden');
			if (LMOS.wizardNextOkay) $('#wizardNextBtn').removeClass('inactive');
			else $('#wizardNextBtn').addClass('inactive');
		}
		if (LMOS.wizardCancelOkay){$('#wizardCancelBtn').removeClass('hidden').removeClass('inactive');}
		$('#wizardDialog').dialog('option','title',LMOS.wizardTitle+' Step '+LMOS.wizardCurrentStep+" of "+parseInt(LMOS.wizardSteps.length,0));
		$('#wizardMessage').html(LMOS.wizardMessage);
		return true;
	};
	this.wizardStart=function(){
		$('#wizardDialog').dialog('open');
		LMOS.wizardActive=true;
		LMOS.wizardLoadStep(1);
		return true;
	};
	
	this.wizardLoadStep=function(step){
		if (step > LMOS.wizardSteps.length) {LMOS.wizardCancel(); return false;}
		var curStep=LMOS.wizardSteps[step-1];
		LMOS.wizardMessage=curStep.message;
		LMOS.changeURL(curStep.URL);
		LMOS.wizardCurrentStep=step;
		LMOS.wizardUpdate();
		LMOS.wizardNextOkay=curStep.checkExit;
		return true;
	};
	this.wizardCancel=function(){
		$('#wizardDialog').dialog('close');
		return true;
	};
	this.wizardNext=function(){
		if (LMOS.wizardNextOkay()) LMOS.wizardLoadStep(parseInt(LMOS.wizardCurrentStep+1,0));
		return true;
	};
	
	this.wizardDone=function(){
		$('#wizardDialog').dialog('close');
		return true;
	};
	this.hoverShow=function(element){
		$(element).find(".hs").removeClass('hidden');
	};
	this.hoverHide=function(element){
		$(element).find(".hs").addClass('hidden');
	};
	this.contentInviteLink="";
	this.contentInviteTemplate="";
	this.contentInvitePassword="";
	this.contentInviteTitle="";
	this.contentInviteDialogOpen=function(){
    return true;
	};
	this.contentInvite=function(){$('#contentInviteDialog').dialog('open'); return true;};
	this.contentInviteClose=function(){
      LMOS.contentInviteLink="";
      LMOS.contentInviteTemplate="";
      LMOS.contentInvitePassword="";
      LMOS.contentInviteTitle="";
      $('#contentInviteList').val("");
      $('#contentInviteDialog .dialog-message').hide();
      $('#contentInviteDialog').dialog('close');
      return true;
	};
	this.contentInviteDialogSubmitBtnClick=function(){
    var emailList=LMOS.contentInviteDialogValidate();
    if (!emailList) { return false;}
    var inviteParams={invite_list:JSON.stringify(emailList),invite_title: LMOS.contentInviteTitle, invite_link:LMOS.contentInviteLink, invite_template:LMOS.contentInviteTemplate};
    if (LMOS.contentInvitePassword.length > 0) inviteParams.invite_password = LMOS.contentInvitePassword;
    $.postTIJSON('/main/content_invite',inviteParams,function(data){
      if (data.status=='success'){
          $('#contentInviteDialog .dialog-message').show().html('Success! Closing In 3 seconds...');
          var t=setTimeout(LMOS.contentInviteClose,3000);
      }
      else $('#contentInviteDialog .dialog-message').show().html('Error: '+data.msg);
      return true;
    });
    return true;
  };
  this.contentInviteDialogCancelBtnClick=function(){LMOS.contentInviteClose(); return true;};
  this.contentInviteDialogValidate=function(){
    var inviteList=$('#contentInviteList').val();
    inviteList=LMOS.emailListProcess(inviteList);
    if (!inviteList) {
      $('#contentInviteList').css("background-color","#f88").click(function(){$(this).css("background-color","#fff");});
      $('#contentInviteDialog .dialog-message').show().html('Invalid Email Address');
      return false;
    }
    return inviteList;
  };
  this.contactOwnerContainer="";
  this.contactOwner=function(container){
    var msg=$(container).val();
    if (msg.length < 1) {$(container).css("background-color","#f88").click(function(){$(this).css("background-color","#fff");});
      $(container).siblings('.message').show().html('Please Type a Message.');
      return false;
    }
    LMOS.contactOwnerContainer=container;
    $.postTIJSON('/main/contact_owner',{message:msg},function(data){
      if (data.status=='success'){
          $(LMOS.contactOwnerContainer).siblings('.message').slideDown().html('Message sent successfully!');
          var t=setTimeout("$(LMOS.contactOwnerContainer).val('').siblings('.message').slideUp().html('');",5000);
      }
      else alert('Error - message could not be sent.');
      return true;
    });
    return true;
  };
	// Converts checkboxes to Cool On/Off switches. Stores checkbox values to return later.
	this.fancySwitchInit=function(){
		$('input.switch:disabled:checked').addClass('hidden').after('<span class="fancySwitch on disabled hoverFade50" title="Always Enabled" />');
		$('input.switch:not(:disabled):checked').addClass('hidden').after('<span class="fancySwitch on" />');
		$('input.switch:disabled:not(:checked)').addClass('hidden').after('<span class="fancySwitch off disabled hoverFade50" title="Always Disabled" />');
		$('input.switch:not(:disabled):not(:checked)').addClass('hidden').after('<span class="fancySwitch off" />');
		$('.fancySwitch:not(.disabled)').click(function(){$(this).toggleClass('on').toggleClass('off').prev('input').attr('checked',$(this).hasClass('on')); return true;});
		return true;
	};
};

function getURL(){
	var URLParams = {app:"",paramA:"", paramB:""};	
	var hash=$.url.attr("anchor");
	if (hash != null){
		var hashArray=hash.split("/");
		if (hashArray.length > 1) URLParams.app=hashArray[1];
		if (hashArray.length > 2) URLParams.paramA=hashArray[2];
		if (hashArray.length > 3) URLParams.paramB=hashArray[3];
	}
	return URLParams;
}

/*LMOS.changeAppTab = function(){
	LMUploadInitPending = false;
	if (LMUploadLoaded) LMUpload.hideAddButton();
	$("*").slider("destroy");
};*/

function checkURL(URL){
	var validURL= true;
	$.ajax({url:URL,type:'HEAD',error:function(){validURL=false;},async:false});
	return validURL;
}
var formBusy=false;
function InitFormEnhancements(){
	formBusy=false;
	$('.FormSubmitButton').click(function(){
		if (formBusy) return false;
		formBusy=true;
		$(this).parents('form').submit();
		return true;
	});
	return true;
}

var LMUploadInitPending;
function loadUploader(callbackFn){
	LMUploadInitPending = true;
	if (typeof callbackFn != "function") {debugMsg('Uploader: no callback function'); return false;}
	if (!LMUploadLoaded){
		$.getScript(staticPaths.js+'js/swfupload/swfupload.js', true, function(){
			$.getScript(staticPaths.js+'tungsten-upload.js', true, function(){
				LMUpload.init();
				LMUploadLoaded = true;
				try{callbackFn();} catch(e){debugMsg(e);}
				if(!LMUploadInitPending) LMUpload.hideAddButton();
			});
		});
		return true;
	}
	else try{callbackFn();} catch(e){debugMsg(e);}
	return true;
}


// This function takes a help element as its input and loads help on it
function OpenHelp(HelpDiv){		
		// Modal Dialog box should already be opened by the time this is called
		// Change the Help Button
		ModalDialogSetHelpButton(HelpDiv,"close");
		// Display the help background
		$(HelpDiv).show();
		ModalDialogMessage("Displaying Help");
		$("a.HelpQuestion").click(function() {	
			$('.selected').removeClass('selected');
			$(this).addClass('selected');
			var question=$(".selected:first").text();
			var answer=$(".selected ~ div:first").html();
			var completeAnswer='<div id="HelpAnswerHeading">'+question+'</div>';
			completeAnswer+=answer;
			$("#HelpAnswer").html(completeAnswer);
		});
}

function CloseHelp(HelpDiv){
	// Change the button
	ModalDialogSetHelpButton(HelpDiv,"open");
	$(HelpDiv).hide();
	ModalDialogMessage("Ready");
}

function ShowHideIDs(IDList){
	var x=0;
	for (x in IDList.hide){	$(IDList.hide[x]).hide();}
	for (x in IDList.show){	$(IDList.show[x]).show();}
}

function createCookie(name,value,days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// Takes a date in 2008-12-29 format and returns 12/29/08 format
function fmtDate(srcDate){
	var dateParts = srcDate.split("-");
	var dateYear = dateParts[0].split("").slice(2,4).join("");
	var dateMonth = dateParts[1];
	var dateDay = dateParts[2];	
	var formattedDate = dateMonth+"/"+dateDay+"/"+dateYear;
	return formattedDate;
}

function runOnUnload(f){ runOnUnload.funcs.push(f);}
runOnUnload.funcs = []; // The array of functions to call before the document unloads
runOnUnload.run = function() {
	for(var i = 0; i < runOnUnload.funcs.length; i++) {
        try { runOnUnload.funcs[i](); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
}};

// This function makes the standard array sort work on functions (such as the story list) and adds sort order selection
function SortHelper(sortKey, direction){
	var thisMethod = function(a, b){
		var aKey = a[sortKey];
		var bKey = b[sortKey];
		// special handing of stories that were published prior to the availability of the "published" parameter
		if (sortKey == "published" & aKey === null) aKey = a.created;
		if (sortKey == "published" & bKey === null) bKey = b.created;
		if (direction.toLowerCase() == "up"){
			if (aKey>bKey) return 1;
			if (bKey>aKey) return -1;
		}else{
			if (aKey>bKey) return -1;
			if (bKey>aKey) return 1;
		}
		return 0;
	};
	return thisMethod;
}

jQuery.fn.replaceWith = function(replacement){
	return this.each (function(){
    element = $(this);
    $(this).after(replacement).next().html(element.html());
    for (var i = 0; i < this.attributes.length; i++) {
      element.next().attr(this.attributes[i].nodeName, this.attributes[i].nodeValue);
    }
    element.remove();
	});
};

jQuery.fn.ajaxBusy = function(state){
	return this.each (function(){
    var element = $(this);
    if (state == 'show') element.append('<img class="ajaxBusy" src="'+staticPaths.image+'ajax-loader.gif" alt="busy" />');
		else element.children('.ajaxBusy').remove();
	});
};

/* Apply to any LM button with the standard <span><a /><span /></span> structure.*/
jQuery.fn.infoButton = function(state){
	return this.each (function(){
    var element = $(this).children('a');
		var inactive=false;
    if (state == 'clean' || state == ''){ element.html('Unchanged'); inactive=true;}
		if (state == 'saveDone'){element.html('<strong class="iconCheck icon" />Save Complete'); inactive=true;}		
		if (state == 'dirty'){ element.html('<strong class="iconSave icon" />Save Changes'); }
		if (state == 'saving'){ element.html('<strong class="iconLoading" />Saving'); }
		if (state == 'saveError'){ element.html('<strong class="iconError icon" />Error Saving'); }
		if (state == 'cleanUndo'){ element.html('Nothing to Undo'); inactive=true;}
		if (state == 'dirtyUndo'){ element.html('<strong class="iconBlueArrowLeft icon" />Undo Changes');}
		$(this).toggleClass('inactive',inactive);
	});
};

jQuery.fn.customInfoButton = function(icon, msg){
	return this.each (function(){
    var element = $(this).children('a');
    if (icon != '' && icon != 'iconLoading') icon+=' icon';
		var html='<strong class="'+icon+'" />'+msg;
		element.html(html);
	});
};

jQuery.fn.errorHighlight = function(){
	return this.each (function(){
		$(this).css("background-color","#f88").click(function(){$(this).css("background-color","#fff");});
	});
};

//$(".fancyInput").fancyInput();

jQuery.fn.fancySelect = function(){
	return this.each (function(config){
		var id=$(this).attr('id');
		var oVal=$(this).val();
		if (id == '') {id='sel_'+Math.floor(Math.random()*999999); $(this).attr('id',id);} 
		$(this).hide();
		if ($('#fs_'+id).length > 0) $('#fs_'+id).remove();
		var defs = {cssClass: '', label: ''};
		var opts = $.extend({}, defs, config);
		opts = $.metadata ? $.extend({}, opts, $(this).metadata()) : opts;
		var fs = $('#fancySelectPrototype').clone().attr('id','fs_'+id).insertBefore(this).attr('class',opts.cssClass+' fancySelect');
		var fsOC = fs.find('.fsOptions .last');
		var fsLT = fs.find('.fsLabelText').html(opts.label);
		if (opts.label.length == 0){
			fs.find('.fsDivider').addClass('hidden');
			fs.find('.fsLabel').addClass('noLabel');
		}
		else{
			var fsLTW = fsLT.outerWidth(true)+fs.find('.fsDivider').outerWidth(true);
			fs.find('.fsLabel').css('width',fsLTW);
		}
		fs.find('.fsSrcId').val(id);
		var selOpts=$(this).children('option');
		var optMaxW = 0; var optMaxTW = 0;
		var cTxt=''; var mOTxt='';
		var flM = false;
		fs.find('.fsOptions').show();
		var fsCT = fs.find('.fsCurrentText');
		selOpts.each(function(i,opt){
			var oId=$(opt).attr('id');
			if ($(opt).disabled || $(opt).hasClass('hidden')) return true;
			if ($(opt).val()==oVal || $(opt).hasClass('label')){ 
				cTxt=$(opt).html();
				fsCT.html(cTxt);
				fs.find('.fsCurrentVal').val($(opt).val());
				if ($(opt).hasClass('label')){ fsCT.addClass('fixedLabel'); flM = true; return true;}
			}
			var fsOpt = $('#fsOptionPrototype').clone().attr('id','fsopt_'+$(opt).val()).insertBefore(fsOC).removeClass('hidden');
			var fsOptText = fsOpt.find('.fsText').html($(opt).html());
			fsOpt.find('.fsVal').val($(opt).val());
			if (fsOptText.outerWidth(false) > optMaxW){
				optMaxW =  fsOptText.outerWidth(false);
				optMaxTW = fsOptText.width();
				mOTxt = fsOptText.html();
			}
			fsOpt.click(function(){
				var fsSel=$(this).parents('.fsSelect');
				if (!fsCT.hasClass('fixedLabel'))	fsCT.html($(this).find('.fsText').html());
				var origId = fsSel.find('.fsSrcId').val();
				var val = $(this).find('.fsVal').val();
				fsSel.find('.fsCurrentVal').val(val);
				$('#'+origId).val(val).trigger('change');
				fsSel.find('.fsOptions').slideUp(100,function(){$(this).css('display','');});
			});
			return true;
		});
		var fsc=fs.find('.fsCurrent');
		var fscPad=parseInt(fsc.css('padding-right'),0);
		var fsTO = $('#fsOptionPrototype').clone().attr('id','fs_temp').insertBefore(fsOC).removeClass('hidden');
		var fsTOT = fsTO.find('.fsText').html(mOTxt);
		if (!flM){				
			fsCT.html(mOTxt);
			var fontRatio = fsCT.width() / fsTOT.width();
			fsCT.html(cTxt);
			optMaxW = parseInt(optMaxW*fontRatio,0);
			fsCT.css('width',optMaxW);
			optMaxW = fs.find('.fsArrow').outerWidth(true) + fsCT.outerWidth(true);
		}
		else{
			optMaxW = Math.max(fs.find('.fsArrow').outerWidth(true) + fsCT.outerWidth(true), fsTOT.outerWidth(true));
		}
		fsTO.remove();
		fs.find('.fsOptions').css({display:'', width:optMaxW}).find('.fsOption').css('width',optMaxW-fscPad);//.find('.fsText').css('width',optMaxTW);
		fsc.css('width',optMaxW);
		
		$(this).change(function(){
			var id=$(this).attr('id');
			var val=$(this).val();
			var fsCV = $('#fs_'+id).find('.fsCurrentVal').val();
			if (fsCV == val) return;
			$('#fs_'+id).find('input[value='+val+']').parent().click();
		});
	});
};


function tagListRead(callbackFn){
	$.getTIJSON('/main/tag_list_read',{},callbackFn);
	return true;
}

function formToObj(fs){
	var retData={};
	$('#'+fs+' :input').each(function(val,i){
			var name=$(this).attr('name');
			var value=$(this).val();
			retData[name]=value;
		});
	return retData;
}

Number.prototype.ordinal = function () {
	return this + ((this % 10 == 1 && this % 100 != 11) ? 'st' :(this % 10 == 2 && this % 100 != 12) ? 'nd' :(this % 10 == 3 && this % 100 != 13) ? 'rd' : 'th');
};

var monthNames=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	