/**
 * advance.js
 *
 * Contains common scripts for advance blog sites.
 * Requires jquery-1.2.6.js to be loaded first.
 *
 * Copyright (c) Advance Internet. All rights reserved.
 */

//------------------------------------------------------------------------------------
// Toprail login widget functions
//------------------------------------------------------------------------------------
/**
 * mtUpdateSignInWidget
 * @desc - Sets toprail signin widget correctly. Expects advBlogSettings JSON var (set in mashead).
 * @param u {user object} - optional, set up in mt.js.mtml
 */
mtUpdateSignInWidget = function (u) {
	var el = document.getElementById('signin-widget-content');
	var content = ''; var register_link;
	var user_pic = document.getElementById('signin-user-icon');
	var toprail_signin = document.getElementById('ToprailSignin');
	if (!el) return;
		if (u) {
			if (u && u.is_authenticated) {
            user = u;
            mtSaveUser();
			} else {
            // user really isn't logged in; so let's do this!
            return mtSignIn();
      }
   } else {
      u = mtGetUser();
   }
   if (u && u.name) {
      var url;
      if (u.is_authenticated) {
         if (u.is_author) {
            url = 'http://connect' + advBlogSettings.envPrefix + '.' + advBlogSettings.affiliateDomain + '/dashboard/' + encodeURIComponent(u.profile) + '/index.html';
				//url += '?static=' + encodeURIComponent( location.href );
         } else {
            url = u.url;
         }
		} else if (u.url) {
         url = u.url;
		} else {
         url = null;
		}
		var userName = u.name;
		if(userName.length > 20) {
			userName = userName.substr(0,16) + "...";
		}
      if (url)
         content += 'You are signed in as<br /> <span><a href="' + url + '" class="user">' + userName + '</a></span><br />';
      else
         content += 'You are signed in as<br /> <span class="user">' + userName + '</span><br />';
      if (u.is_author)
	 var signOutFunction = 'mtSignOutOnClick()';
	 if (document.location.href.match(/\/dashboard\/edit\.html/)) { signOutFunction = 'mtSignOutOnClick(\'http://signup' + advBlogSettings.envPrefix + '.' + advBlogSettings.affiliateDomain + '/sign-in/\')';  }
         content += '<a href="http://connect' + advBlogSettings.envPrefix + '.' + advBlogSettings.affiliateDomain + '/user/' + encodeURIComponent(u.profile) + '/index.html" title="View your profile">Profile page</a> | <a href="http://blog' + advBlogSettings.envPrefix + '.' + advBlogSettings.affiliateDomain + '/updates/2009/08/about_community_tools.html">Help</a> | <a href="javascript:void(0)" onclick="return ' + signOutFunction + '">Sign out</a>';
		var user_pic_url;
		var avatarPath = advBlogSettings.mediaUrl.replace(/([^\/])\/[^\/].+/, '$1');
    	if (u.userpic) { user_pic_url = avatarPath + '/' + u.userpic } else { user_pic_url = advBlogSettings.mediaUrl + '/img/user_default.png' }
    	user_pic.src = user_pic_url;
    	toprail_signin.setAttribute('class','logged_in');
		document.getElementById('logged_in_widget').style.display='block';
		document.getElementById('logged_out_widget').style.display='none';
	} else {
		function profileLink(profileMode) {
				theLink = signinSubDomain + advBlogSettings.envPrefix + '.' + advBlogSettings.affiliateDomain + '/' + profileMode + '/?return_to=' + encodeURIComponent(document.URL);
			return theLink;
		}
		document.getElementById('logged_out_widget').style.display='block';
		document.getElementById('logged_in_widget').style.display='none';
		document.getElementById('toprail-register-link').setAttribute('href',profileLink('register'));
		document.getElementById('toprail-login-register').setAttribute('href',profileLink('register'));
		document.getElementById('ForgotPassword').setAttribute('href',profileLink('remember'));
		//
		document.getElementById('ToprailSigninForm').action = mtRegisterCGIPath + mtCommunityScript;
		document.getElementById('affiliate').value = advAffiliate;
		document.getElementById('v').value = advVersion;
		//
		jQuery('#openIdLinks a').each(function () {
			var myClass = jQuery(this).attr('class');
			if (myClass != '') {
				this.href = profileLink('sign-in') + '&option=' + myClass;
				jQuery(this).removeClass(myClass);
			}
		});
   }
	el.innerHTML = content;
	document.getElementById('ToprailSignin').style.display='block';
};

/**
 * showLoginForm
 * @desc - Shows the selected li object and its corresponding form.
 * @param obj {object} - li object which should be shown.
 */
showLoginForm = function (obj) {
	jQuery("#SigninNav li").removeClass('selected');
	jQuery(obj).addClass('selected');
	var id = obj.id
	var rEx = /option/;
	jQuery("#SigninForms").children().hide();
	jQuery("#"+id.replace(rEx, 'with')).show();
};

/**
 * initSignIn
 * @desc - Initializes the signin dialog
 */
initSignIn = function() {
	if ((document.getElementById('SignInDialog') != null)) {
		jQuery("#SignInDialog").jqm({ overlay:30.01, modal:false });
	}
};


//------------------------------------------------------------------------------------
// Text blog entry functions
//------------------------------------------------------------------------------------
/**
 * initEntryCreatePreview
 * @desc - Assigns keyup functions to populate public text blog entry previewer.
 */
initEntryCreatePreview = function() {
   if(jQuery('#create-entry-form').size()) {
      jQuery('#create-entry-form #entry-title').keyup(function() {
         jQuery('#postPreviewTitle').html(jQuery('#entry-title').val());
      });
      jQuery('#create-entry-form #entry-body').keyup(function() {
         jQuery('#postPreviewText').html(jQuery('#entry-body').val().replace(/(\r\n|\n)/g,'<br />'));
      });
      jQuery('#create-entry-form #entry-tags').keyup(function() {
         jQuery('#postPreviewTags').html("<span>Story tags:</span> " + jQuery('#entry-tags').val().replace(/,/g,' | '));
      });
   }
};

/**
 * printLoad
 * @desc - populates the article from the opening doc
 */
printLoad = function () {
	var opener = window.opener.document;
	document.title = opener.title;

	var oContents = jQuery(jQuery("#ContentWell",opener).html()).contents();
	oContents.each( function() {
		if (this.nodeName != "#text") {
			if (this.id == "article") {
				jQuery(this).find("a").each(function() {
					var txt = jQuery(this).text();
					jQuery(this).replaceWith('<strong>'+ txt +'</strong>');
				});
				var t = jQuery(this).find("h5").text();
				var d = new Date(t.substr(0,t.length-2));
				jQuery("span#year").html(d.getFullYear());
				document.getElementById("PrintContainer").appendChild(this);
			}
		}
	});
	window.print();
};

//------------------------------------------------------------------------------------
// Moderation functions
//------------------------------------------------------------------------------------
/**
 * moderate
 * @desc - Creates and displays dialog for reporting questionable content. Iframe is populated by the plugin.
 * @param href {string} - value for the iframe src attribute.
 */
moderate = function (href) {
	var isIE6 = (jQuery.browser.name == 'msie' && jQuery.browser.versionNumber < 7)?true:false;

	/* create the containing element and position it */
	var overlay = document.createElement("div");
	overlay.setAttribute("id", "ModerateOverlay");
	overlay.setAttribute("class", "jqmWindow");
	//document.getElementById("PageContent").appendChild(overlay);
	document.body.appendChild(overlay);

	/* create the rounded corner box */
	var boxtop = document.createElement("div");
	(isIE6) ? boxtop.setAttribute("id", "BoxTopIE6") : boxtop.setAttribute("id", "BoxTop");
	var box = document.createElement("div");
	box.setAttribute("id", "Box");
	var boxbottom = document.createElement("div");
	boxbottom.setAttribute("id", "BoxBottom");
	overlay.appendChild(boxtop);
	overlay.appendChild(box);
	if (!isIE6) overlay.appendChild(boxbottom);

	/* create the close link */
	jQuery("#BoxTop,#BoxTopIE6").html('<a href="" title="Click to close" class="jqmClose" id="ModerateClose"><!-- --></a>');

	/* create the iframe for the moderation form */
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "ModerateIframe");
	(jQuery.browser.name == 'msie') ? iframe.setAttribute("frameBorder", "0") : iframe.setAttribute("frameborder", "0");
	iframe.setAttribute("src", href);
	iframe.setAttribute("scrolling", "no");
	box.appendChild(iframe);

	var destroyJQM = function(hash) {hash.o.remove();jQuery("#ModerateOverlay").remove();}; //clean up - removes moderate dialog when closed
	jQuery("#ModerateOverlay").center();
	jQuery("#ModerateOverlay").jqm({ overlay:30.01, modal:true, onHide: destroyJQM });
	jQuery("#ModerateOverlay").jqmShow();

	return false;
};

//------------------------------------------------------------------------------------
// Tab functions
//------------------------------------------------------------------------------------
/* Pages can support multiple instances of tabs.
 * Basic html form:
	<div class="mt_tabs">
		<ul>
			<li class=""><a href="#" class="first">Tab A</a></li>
			<li class=""><a href="#" class="">Tab B</a></li>
			<li class="on"><a href="#" class="last">Tab C</a></li>
		</ul>
	</div>
 * Assign "on" to the class of the default tab. First and last <li> tags
 * should contain "first" and "last" classes in their <a> tags.
 */
//------------------------------------------------------------------------------------
/**
 * resetTabs
 * @desc - Sets all <li> to "off" style.
 * @param ulObj {object} The ul object to set all tabs to the 'off' setting
 */
resetTabs = function (ulObj) {
	jQuery(ulObj).children().remove("li[class*='mt_tab_active_']");
	jQuery.each(jQuery(ulObj).children(), function(){
		var prevLi = jQuery(this).prev("li");
		var nextLi = jQuery(this).next("li");
		jQuery(this).removeClass();
		jQuery(this).children("a").removeClass();
		if (!prevLi.length) { jQuery(this).children("a").addClass("first"); }
		if (!nextLi.length) { jQuery(this).children("a").addClass("last"); }
	});
};
/**
 * setTab
 * @desc - Sets one <li> to "on" style.
 * @param liObj {object} The form object whose search values should be checked and sets default values to ''
 */
setTab = function (liObj) {
	var prevLi = jQuery(liObj).prev("li");
	var nextLi = jQuery(liObj).next("li");
	jQuery(liObj).addClass("mt_tab_active");
	if (prevLi.length) {
		jQuery(liObj).before('<li class="mt_tab_active_left" />');
		prevLi.children("a").addClass("before");
	} else {
		jQuery(liObj).before('<li class="mt_tab_active_first" />');
		jQuery(liObj).children("a").removeClass("first");
	}
	if (nextLi.length) {
		jQuery(liObj).after('<li class="mt_tab_active_right" />');
		nextLi.children("a").addClass("after");
	} else {
		jQuery(liObj).after('<li class="mt_tab_active_last" />');
		jQuery(liObj).children("a").removeClass("last");
	}
};
/**
 * initTabs
 * @desc - Sets the default "on" tabs in all tabsets on a page (can be called on ready() or within page).
 */
initTabs = function () {
	jQuery.each(jQuery(".mt_tabs ul").children(), function(){
		if (jQuery(this).hasClass("on")) {
			setTab(this);
		}
	});	
};
/**
 * initTabsWithClick
 * @desc - Sets the default "on" tab in specified tabset on a page and assign state change to click event (can be called on ready() or within page).
 * @param ulObj {object} The ul object to init and assign state change to click event
 */
initTabsWithClick = function (ulObj) {
	jQuery.each(jQuery(ulObj).children(), function(){
		if (jQuery(this).hasClass("on")) { setTab(this); }
		jQuery(this).click (function () {
			resetTabs(jQuery(this).parent());
			jQuery(this).addClass("on");
			setTab(jQuery(this));
		});
	});
};
//------------------------------------------------------------------------------------
// Ugly ad hack
//------------------------------------------------------------------------------------
/**
 * processAd
 * @desc - Hack to hide the containing div if the ad serves up 'empty.gif' (which means the ad space is empty).
 *         I know it's ugly, but until there is a new ad vendor...
 */
processAd = function (adId) {
	var ad = jQuery("#"+adId+" a");
	if (typeof ad == "object") {
		var re = new RegExp(/empty.gif/);
		var m = re.exec(ad.attr('href'));
		if (m != null) {
			jQuery("#"+adId).css({display:"none"});
		}
	}
};

//------------------------------------------------------------------------------------
// Miscellaneous functions
//------------------------------------------------------------------------------------
/**
 * setSelectYear - sets options for year of birth select field
 * @param id {string} The id of the select field to set
 */
setSelectYear = function (id) {
	var now = new Date();
	var start = now.getFullYear()-13;
	var end = now.getFullYear()-101;
	for (var x = start;x>end;x--) {
		jQuery("#"+id).append('<option value="'+x+'">'+x+'</option>');
	}
};

//------------------------------------------------------------------------------
/**
 * PageQuery
 * @desc - singleton class for the page query string
 * @properties - q_str {string} raw query string
 * 				  keyValuePairs {array}
 * @methods - getValue(key) returns the value of key arg
 * 			  getParameters() returns array of keys
 */
var PageQuery = new function () {
	var q = window.location.search;
	
	this.q_str = (q.length > 1) ? q.substring(1, q.length) : null;
	this.keyValuePairs = new Array();
	if (q) {
		for (var i=0; i < this.q_str.split("&").length; i++) {
			this.keyValuePairs[i] = this.q_str.split("&")[i];
		}
	}
	this.getValue = function(s) {
		for (var j=0; j < this.keyValuePairs.length; j++) {
		 if (this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	};
	this.getParameters = function() {
		var a = new Array(this.keyValuePairs.length);
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	};
};

//------------------------------------------------------------------------------------
/**
 * Stuff to execute upon page load
 */
function hide(element){ document.getElementById(element).style.display = 'none';}
var advBlogSettings = {relativeCgiPath:mtRelativeCGIPath,commScript:mtCommunityScript,version:advVersion,affiliate:advAffiliate,mediaUrl:mediaURL,envPrefix:advEnvPrefix,affiliateDomain:advDomain};

mtInitAttachEvents = function () {
	mtAttachEvent("usersignin", mtUpdateScores);
	try {
		if(useFrames) {
			mtAttachEvent("load", mtEntryOnLoad);
		}
	} catch(e) {
		// nothing
	}
	mtAttachEvent("unload", mtEntryOnUnload);
	mtAttachEvent('usersignin', mtUpdateSignInWidget);
	mtFetchRemoteUser();
};

jQuery().ready(function() {
	if (jQuery.browser.name == 'msie' && jQuery.browser.versionNumber < 7) {	 // add mouseover css for buttons in evil IE6
		try { 
			document.execCommand('BackgroundImageCache', false, true); 
		} catch(e) {}
		jQuery(".btn_signin").hover(
			function () { jQuery(this).addClass("btn_signin_mo"); },
			function () { jQuery(this).removeClass("btn_signin_mo"); }
		);
		jQuery(".btn_signup").hover(
			function () { jQuery(this).addClass("btn_signup_mo"); },
			function () { jQuery(this).removeClass("btn_signup_mo"); }
		);
		jQuery(".btn_save").hover(
			function () { jQuery(this).addClass("btn_save_mo"); },
			function () { jQuery(this).removeClass("btn_save_mo"); }
		);
		jQuery(".btn_search").hover(
			function () { jQuery(this).addClass("btn_search_mo"); },
			function () { jQuery(this).removeClass("btn_search_mo"); }
		);
		jQuery(".btn_write_post").hover(
			function () { jQuery(this).addClass("btn_write_post_mo"); },
			function () { jQuery(this).removeClass("btn_write_post_mo"); }
		);
		jQuery(".btn_submit_photos_2").hover(
			function () { jQuery(this).addClass("btn_submit_photos_2_mo"); },
			function () { jQuery(this).removeClass("btn_submit_photos_2_mo"); }
		);
		jQuery(".btn_submit_videos").hover(
			function () { jQuery(this).addClass("btn_submit_videos_mo"); },
			function () { jQuery(this).removeClass("btn_submit_videos_mo"); }
		);
		jQuery(".btn_submit_photos").hover(
			function () { jQuery(this).addClass("btn_submit_photos_mo"); },
			function () { jQuery(this).removeClass("btn_submit_photos_mo"); }
		);
		jQuery(".btn_preview").hover(
			function () { jQuery(this).addClass("btn_preview_mo"); },
			function () { jQuery(this).removeClass("btn_preview_mo"); }
		);
		jQuery(".btn_post").hover(
			function () { jQuery(this).addClass("btn_post_mo"); },
			function () { jQuery(this).removeClass("btn_post_mo"); }
		);
		jQuery(".btn_upload").hover(
			function () { jQuery(this).addClass("btn_upload_mo"); },
			function () { jQuery(this).removeClass("btn_upload_mo"); }
		);
		jQuery(".btn_next").hover(
			function () { jQuery(this).addClass("btn_next_mo"); },
			function () { jQuery(this).removeClass("btn_next_mo"); }
		);
		mtUpdateSignInWidget();
		mtInitAttachEvents();
	}

	jQuery(".print_window").click( function() {
		window.open(jQuery(this).attr('href'),'printWin','height=500,width=700,scrollbars=1,resizable=1,menubar=1');
		return false;
	});

	mtEntryOnLoad();
	initSignIn();
	
	try {
		if (isSSF) mtInitAttachEvents();
	} catch (e) {}
});
if ( jQuery.browser.name != 'msie' || (jQuery.browser.name == 'msie' && jQuery.browser.versionNumber >= 7)) {
	mtInitAttachEvents();
}
//------------------------------------------------------------------------------------
