var getScriptCache=[];
var getScriptTimer='';
$.getScript = function(url, cache, callback){ 
  if ($.inArray(url, getScriptCache) > -1 ) {if (cache) {callback(); return true;}}
  else getScriptCache.push(url);
  $.ajax({ type: "GET", url: url, success: function(){getScriptTimer=setTimeout(callback,100);}, dataType: "script", cache: cache}); 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'){	// 500 error
	   alert('Sorry, but there was an error with this page.\n Click "OK" to try again');
	   window.location = '/';
   }
   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></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(){
					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(){
		debugMsg('trace: init components');
		$().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);
			$("#appControlsMessage .messageHeadline").html(message);
			$("#appControlsMessage .messageDetail").html(detail);
		}).animate({top: "0px"},400);
		return true;
	};
	this.ensureDefault=function(setting, defaultValue) {var result = (setting == undefined) ? defaultValue : setting;
return result;};
	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('Nothing to Save'); inactive=true;}
		if (state == 'saveDone'){element.html('<strong class="iconCheck" />Save Complete'); inactive=true;}		
		if (state == 'dirty'){ element.html('<strong class="iconSave" />Save Changes'); }
		if (state == 'saving'){ element.html('<strong class="iconLoading" />Saving...'); }
		if (state == 'saveError'){ element.html('<strong class="iconError" />Error Saving'); }
		if (state == 'cleanUndo'){ element.html('Nothing to Undo'); inactive=true;}
		if (state == 'dirtyUndo'){ element.html('<strong class="iconBlueArrowLeft" />Undo Changes');}
		$(this).toggleClass('inactive',inactive);
	});
};


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;
}

var monthNames=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	