var cur_domain = document.domain;

/**
 * Creates a popup with our framework
 * @param string path to script
 * @param string query string
 * @param mixed popup type "small" || "medium" || "large" || [width, height]
 * @param string header type "sm" || "norm" || false (to not use header / footer)
 * @param mixed window location [left, top] || "middle"
 * @param string security mode "plain" || "tls"
 * @return FALSE (for use in links)
 */
function popContent(src, query, p_type, header, p_loc, mode, contact_type)
{
	var p_width, p_height, p_left, p_top, settings;
	
	if (mode == "tls")
		var proto = "https";
	else
		var proto = "http";

	if (!contact_type)
		contact_type = '';

	if (isArray(p_type))
	{
		p_width = p_type[0];
		p_height = p_type[1];
	}
	else if (p_type == "sm")
	{
		p_width = 450;
		p_height = 355;
	}
	else if (p_type == "med")
	{
		p_width = 570;
		p_height = 515;
	}
	else
	{
		p_width = 800;
		p_height = 600;
		header = "med";
	}
	
	if (header == '')
		header = p_type;

	if (isArray(p_loc))
	{
		p_left = p_loc[0];
		p_top = p_loc[1];
	}
	else
	{
		var mid = calcMiddle(p_width, p_height);
		p_left = mid[0];
		p_top = mid[1];
	}
	
	query = BuildQueryString(query, '&');
	settings = "toolbar=no, location=no, resizable=yes, menubar=no, scrollbars=yes, width=" + p_width + ",height=" + p_height + ", left=" + p_left + ", top=" + p_top;
	win = window.open(proto + "://" + cur_domain + "/popup.php?page=" + src + "&header=" + header + "&contact_type=" + contact_type + query, "MNB_popf_content", settings);

	if (win)
		win.window.focus();

	return false;
}

/**
 * Generate a totally custom popup
 * @param string page to open
 * @param mixed request data "key=val&..." || ['key': 'val',...]
 * @param string popup window settings
 * @param string window name
 * @param [optional] array geo position / dimensions (if this is included
 * +do not include height / width, etc... in settings string.)
 */
function newPopup(src, request, settings, geo, name)
{
	var pos;
	var request_vals = '';

	if (!name || name == '')
		name = "MNB_pop_content";

	if (!settings || settings == '')
	{
		var settings = "toolbar=no, location=no, resizable=yes, menubar=no, scrollbars=yes";
	}

	if (geo['align'] == "middle")
	{
		var mid = calcMiddle(geo['width'], geo['height']);
		geo['left'] = mid[0];
		geo['top'] = mid[1];
	}

	if (geo['height'])
		settings += ", height=" + geo['height'] + ", width=" + geo['width'];
	
	if (geo['top'])
		settings += ", top=" + geo['top'] + ", left=" + geo['left'];

	src += BuildQueryString(request, '?');
	win = window.open(src, name, settings);
	
	if (win)
		win.window.focus();

	return false;
}

/**
 * Creates a preview popup
 * @param string location of preview document
 * @return false
 */
function popExample(pre_src)
{
	var mid = calcMiddle(800, 600);

	var settings = "toolbar=no, location=no, resizeable=yes, menubar=no, scrollbars=yes, ";
	settings += "height=600, width=800, top=" + mid[1] + ", left=" + mid[0];
	win = window.open(pre_src, "MNB_preview", settings);
	
	if (win)
		win.window.focus();

	return false;
}

/**
 * Open newsletter popup
 * @param int newsletter id
 * @return false (for use in links)
 */
function PopPreview(nl_id, as_id, uniq_id)
{
	if (nl_id)
		nl_id = "?nl_id=" + nl_id;
	else
		nl_id = '';
	
	if (as_id)
		as_id = "?as_id=" + as_id;
	else
		as_id = '';
	
	if (uniq_id)
		uniq_id = '?uniq_id=' + uniq_id;
	else
		uniq_id = '';

	newPopup("http://" + cur_domain + "/my/newsletters/preview.php" + nl_id + as_id + uniq_id, '', '', {"align": "middle", "height": 700, "width": 900}, "MNB_preview");
	
	return false;
}

/**
 * Creates a popup contact window.
 */
function popContact(type)
{
	if (!type || type == "contact")
		var page = "contact.php"
	else
		var page = "feedback.php"

	newPopup('http://' + cur_domain + '/my/help/' + page, '', '', {'align':'middle', 'height':275, 'width':400}, '');
}

/**
 * Creates a help system popup (or re-uses the current window)
 * @param string help topic
 * @param boolean new window or resize current
 * @return false (for use in links)
 */
function popHelpSys(topic, new_win)
{
	if (new_win == true)
		newPopup("http://help.mynewsletterbuilder.com/" + topic, '', '', {"align": "middle", "height": 600, "width": 900}, "MNB_help");
	else
	{
		window.resizeTo(900, 600);
		document.location.href = "http://help.mynewsletterbuilder.com/" + topic;
	}
	
	return false;
}

function PopHelp(topic, query)
{
	newPopup("http://" + cur_domain + "/pop_help.php?doc=" + topic, query, '', {"align": "middle", "height": 600, "width": 900}, "MNB_help");
	
	return false;
}

/**
 * Creates a preview popup
 * @param string location of preview document
 * @return false
 */
function PopVideo(src, width, height, auto, toc)
{
	if (!height)
		var height = 600;
	
	if (!width)
		var width = 800;

	if (!toc)
		var toc = 0;

	var mid = calcMiddle(width, height);
	var page_height = height + 100;
	var page_width = width + 40;
	var settings = "toolbar=no, location=no, resizeable=no, menubar=no, scrollbars=no, ";
	settings += "height=" + page_height + ", width=" + page_width + ", top=" + mid[1] + ", left=" + mid[0];
	win = window.open("http://" + cur_domain + "/video_player.php?src=" + src + "&auto=" + auto + "&h=" + height + "&w=" + width + "&t=" + toc, "MNB_video", settings);

	if (win)
		win.window.focus();

	return false;
}

/**
 * Creates a preview popup with a youtube video
 * @param id the youtube id
 * @param size small, regular, large, largest... should stick to regular.
 *   Sizes based on on youtube recommendations
 * @param cust_w if you want to override the width, must include cust_h also
 * @param cust_h if you want to override the height, must include cust_w also
 * @param hide_related set to 1 if you don't want to show related videos at the end
 */
function PopYoutube(id, size, cust_w, cust_h, hide_related)
{
	if (size == 'small')
	{
		width = 560;
		height = 340;
	}
	else if (size == 'regular')
	{
		width = 640;
		height = 385;
	}
	else if (size == 'large')
	{
		width = 853;
		height = 505;
	}
	else if (size == 'largest')
	{
		width = 1280;
		height = 745;
	}
	else
	{
		width = cust_w;
		height = cust_h;
	}
	
	var rel = "";
	if (hide_related == 1)
		rel = "&hide_rel=1";
	
	var mid = calcMiddle(width, height);
	var page_height = height + 100;
	var page_width = width + 40;
	var settings = "toolbar=no, location=no, resizeable=no, menubar=no, scrollbars=no, ";
	settings += "height=" + page_height + ", width=" + page_width + ", top=" + mid[1] + ", left=" + mid[0];
	win = window.open("http://" + cur_domain + "/video_player.php?youtube=" + id + "&w=" + width + "&h=" + height + rel, "MNB_video", settings);

	if (win)
		win.window.focus();

	return false;
}

/**
 * Builds a query string
 * @param mixed query string data "the string" || ['key': val,...]
 * @param prefix string '?' || '&'
 * @return string the query string
 */
function BuildQueryString(request, prefix)
{
	var query_str = prefix;

	if (isArray(request))
		for (var key in request)
		{
			if (query_str != "")
				query_str += "&";

			query_str += key + "=" + request[key];
		}
	else if (request != '')
		query_str += request;
	else
		query_str = '';

	return query_str;
}

//Clears the default username field value
function clearUsername(username)
{
	if (username.value == "username")
		username.value = '';
}

//Clears the default password field value
function clearPassword(password)
{
	if (password.value == '********')
	{
		password.value = '';
	}
}

//Clears the default email address field value
function clearEmail(email)
{
	if (email.value == "email address")
		email.value = '';
}

// Gets window centered on the screen
function calcMiddle(width, height)
{
	var mid = [];
	mid[0] = (screen.width - width) / 2;
	mid[1] = (screen.height - height) / 2;
	
	return mid;
}

// Toggle the visibility of a DOM element
function toggleVisibility(dom_elem)
{
	if (document.getElementById(dom_elem).style.visibility == "hidden")
		document.getElementById(dom_elem).style.visibility = "visible";
	else
		document.getElementById(dom_elem).style.visibility = "hidden";
	
}

/**
 *  Toggles the display attribute of the specified object
 *  @param string ID of object to toggle
 *  @return TRUE if displayed, FALSE if hidden
 */
function toggleDisplay(obj) {
	if(document.getElementById(obj).style.display == 'none' )
	{
		document.getElementById(obj).style.display = 'block';
		return true;
	}
	else
	{
		document.getElementById(obj).style.display = 'none';
		return false;
	}
}

// Make this DOM element visible
function visibleDisplay(dom_elem)
{
		document.getElementById(dom_elem).style.visibility = 'visible';	
}

// Make this DOM element hidden
function hiddenDisplay(dom_elem)
{
		document.getElementById(dom_elem).style.visibility = 'hidden';	
}

// Make this DOM element visible
function displayBlock(dom_elem)
{
		document.getElementById(dom_elem).style.display = "block";	
}

// Make this DOM element visible, inline
function displayInline(dom_elem)
{
		document.getElementById(dom_elem).style.display = "inline";	
}

// Make this DOM element hidden
function displayNone(dom_elem)
{
		document.getElementById(dom_elem).style.display = "none";	
}

//Code to ensure that users enter fully qualified URI's
function checkHTTP(what)
{
	a = what.value.trim()
	if(a != "")
	{
		if (a.search(/^\#/) != -1)	//anchor
			return;
		else if (a.search(/\@/) > 0 && (a.search(/mailto:/) < 0 && (a.search(/\//) < 0))) // mail
			what.value = "mailto:" + a
		else if(a.search(/:\/\//) <= 0 && a.search(/mailto:/) < 0)	// link
			what.value = "http://" + a;
		else
			return;						
	}
}

function testURL(what)
{
	checkHTTP(what);

	if(what.value != "")
		window.open(what.value);
}

// Override string trim only if necessary, also updating to the latest
// jQuery string trim
if(!String.prototype.trim){
	
	var trimLeft = /^\s+/,
		trimRight = /\s+$/;
	
	if ( !/\s/.test( "\xA0" ) ) {
		trimLeft = /^[\s\xA0]+/;
		trimRight = /[\s\xA0]+$/;
	}
	
	String.prototype.trim = function() {
		return this == null ?
			"" :
			this.toString().replace( trimLeft, "" ).replace( trimRight, "" );
	};
	
}

function isArray(obj)
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function jumpTo(id, isElem)
{
	if (isElem == true)
	{
		var elem = document.getElementById(id);
		var val = elem.options[elem.selectedIndex].value;
	}
	else
		var val = id;

	window.location.hash = val;	
}

function submitSearch()
{
	document.getElementById('search_button').disabled = true;
	return true;
}

//toggles 1 element enabled and another disabled, depending on which is currently enabled
//one or the other should be disabled in the first place
function toggleEnabled(ele1, ele2)
{
	if (document.getElementById(ele1).disabled == true)
	{
		document.getElementById(ele1).disabled = false;
		document.getElementById(ele2).disabled = true;
	}
	else
	{
		document.getElementById(ele1).disabled = true;
		document.getElementById(ele2).disabled = false;
	}
}

/**
 * Replaces the options of a select box
 * @param string element id
 * @param mixed options ['display', 'value', defaultSelected, selected]
 */
function ReplaceSelectOptions(id, options)
{
	var sel_obj = document.getElementById(id);
	
	if (!sel_obj)
		return;
	
	sel_obj.options.length = 0;
	
	var count = options.length;
	
	if (count == 0)
		sel_obj.options[0] = new Option("Select", '', true, true);
	else
		for (var i = 0; i < count; i++)
			sel_obj.options[i]=new Option(options[i][0], options[i][1], options[i][2], options[i][3])

	return;
}

/**
 *  Toggles display of an object AND updates the expander image
 *  @param string ID of the object to toggle.
 *  @param string ID of the image to update.
 */
function toggleExpander(obj, btn)
{
	if(toggleDisplay(obj))

		document[btn].src = "/images/info/toc_expanded.gif";
	else
		document[btn].src = "/images/info/toc_collapsed.gif";
}

/**
 * Allow only numeric input (should be called on keyup)
 * @param dom input object
 */
function ForceNumeric(elem)
{
	var val = elem.value;
	elem.value = val.replace(/\D/g, '');
}

/**
 * Get an associative array of query parameters
 * @param [string query var to check]
 * @return mixed ["key": "val", ...]
 * + string if val_var found
 * + FALSE if no query match
 */
function GetQueryVals(name)
{
	var query = window.location.search.substring(1);
	
	if (query == '')
		return false;

	var elems = new Array();
	var tmp = query.split('&');

	for (var i = 0; i < tmp.length; i++)
	{
		var pair = tmp[i].split('=');
		elems[pair[0]] = pair[1];
	}

	if (typeof name == 'string' && name != '')
		return (elems[name]) ? elems[name] : false;
	else
		return elems;
}

/**
 * On page Google Analytics tracking
 * @param [string target URI :: pathname]
 * @param [string target DOM element]
 */
function OnPageGat(uri, dom)
{
	if (cur_domain == "www.mynewsletterbuilder.com")
	{
		if (typeof uri == 'undefined' || uri == '')
			uri = document.location.pathname;
		
		if (typeof dom == 'string')
			uri += dom;

		var pageTracker = _gat._getTracker("UA-3177177-1");
		pageTracker._initData();
		pageTracker._trackPageview(uri);
	}
}

//confirm that user wanted to click the button
function confirmClick(msg) {
	if (msg == null)
		msg = "Are you sure?";
	var agree = confirm(msg);
	if (agree)
		return true;
	else
		return false;
}

//uses confirmClick and disables on true
function disableAfterConfirm(id, msg)
{
	if(confirmClick(msg))
	{
		$('#'+id).attr('disabled', true);
		return true;
	}
	else
		return false;
}

//disables button after submit
function disableAfterSubmit(id, form)
{
	if (form)
		document.forms[form].submit();
	else
		document.forms[0].submit();
	$('#'+id).attr('disabled', true);
	return true;
}

//set defaults on personalization pages
function setPersonalizeDefaults()
{
	if(confirmClick('Are you sure you want to Restore Defaults?  This will overwrite any custom content you already have.'))
	{
		$.ajax({
			type: "GET",
			url: "http://" + cur_domain + "/my/features/personalize/defaults.php",
			timeout: 10000,
			success: function(responseText){
				var res = eval("(" + responseText + ")");
				
				for (var i in res)
				{
					id = i.toLowerCase();
					if ($("#"+id).length > 0)
						$("#"+id).val(res[i]);
					var elem = tinyMCE.getInstanceById(id);
					if (typeof(elem) != "undefined")
						tinyMCE.getInstanceById(id).setContent(res[i]);
				}
			}
		});
	}
}

function AddStyleClass(elem, cls)
{
	$("#" + elem).addClass(cls);
}

function RemoveStyleClass(elem, cls)
{
	$("#" + elem).removeClass(cls);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function ChangeAutoNl(id)
{
	$.ajax({
			type: "POST",
			url: "http://" + cur_domain + "/my/query.php",
			timeout: 20000,
			data: "m=auto_nl&nl_id=" + id,
			success: ConfAutoNlChange
			});
}

function ConfAutoNlChange(success)
{
	if (success != 0)
		alert("Your welcome newsletter has been changed to " + success + ", and your settings have been saved.");
	else
		alert("Sorry, we could not complete your request.");	
}

function ToggleAcMenu(id)
{
	var opts = id.split("-");
	if ($("#"+opts[0]+"_item_"+opts[1]).css('display') == 'none')
	{
		$(".ac_menu_"+opts[0]).each(function(){
			if ($(this).css('display') != 'none')
				$(this).slideUp();
		});
		$("#"+opts[0]+"_item_"+opts[1]).slideDown();
	}
}

var ExtractSortable = function(node)
{	
	if ($(node).children('.sortable'))
	{
		data = $(node).children('.sortable');
		str = $(data).html();

		return (str) ? str : '';
	}
	else
		return $(node).html();
}

function AddFavorite(page)
{
	var default_name = "";
	if (page == "Subscriber_Categories") default_name = "My Subscribers -> Categories";
	else if (page == "Subscribers_Add") default_name = "My Subscribers -> Add";
	else if (page == "Subscribers_Update") default_name = "My Subscribers -> Update";
	else if (page == "Subscribers_Remove") default_name = "My Subscribers -> Remove";
	else if (page == "Subscribers_Prefs") default_name = "My Subscribers -> Preferences";
	else if (page == "Reports") default_name = "My Reports -> Newsletters";
	else if (page == "Reports_Autoseries") default_name = "My Reports -> Autoseries";
	else if (page == "Reports_Surveys") default_name = "My Reports -> Surveys";
	else if (page == "Reports_Activity") default_name = "My Reports -> Activity";
	else if (page == "Autoseries") default_name = "My Newsletters -> Autoseries";
	else if (page == "Autoseries_Edit") default_name = "Autoseries -> Edit "+ $("input[name=series_name]").val();
	else if (page == "Survey_List") default_name = "More Features -> Surveys";
	else if (page == "Survey_Report") default_name = "My Reports -> Survey: "+ $("#bookmark_name").val();
	else if (page == "Survey_Editor") default_name = "Surveys -> Edit "+ $("input[name=survey_name]").val();
	else if (page == "Newsstand") default_name = "More Features -> Publish-to-Web";
	else if (page == "Account_Summary") default_name = "My Account -> Summary";
	else if (page == "Account_Plans") default_name = "My Account -> Pricing Plans";
	else if (page == "Account_Billing") default_name = "My Account -> Billing";
	else if (page == "Settings") default_name = "Account Settings";
	else if (page == "Autoresponders") default_name = "More Features -> Autoresponders";
	else if (page == "Autoresponder_Edit") default_name = "Autoresponder -> Edit "+ $("input[name=title]").val();
	else if (page == "Media") default_name = "More Features -> Media";
	else if (page == "Features_Contact") default_name = "More Features -> Contact Data";
	else if (page == "Mission_Control") default_name = "Master Control Panel";
	else if (page == "Personalization") default_name = "Personalization Options";
	else if (page == "Signup_Builder") default_name = "More Features -> Signup Builder";
	else if (page == "Custom_Branding") default_name = "More Features -> Custom Branding";
	else if (page == "Subscription_System") default_name = "More Features -> Subscription System";
	else if (page == "Confirmation_System") default_name = "More Features -> Confirmation System";
	else if (page == "Forward_Manage") default_name = "More Features -> Forward to a Friend";
	else if (page == "Instant_Import") default_name = "My Newsletters -> Instant Import";
	
	var link = prompt("Adding this page to favorites.  Use the default name if one was provided, enter a custom name, or cancel this action.", default_name);
	if (jQuery.trim(link))
	{
		var proto = document.location.protocol + '//';
		var url = document.location.href;
		$.ajax({
				type: "POST",
				url: proto + cur_domain + "/my/account/home.php",
				timeout: 20000,
				data: {"m": "add_page", "link": link, "url": url},
				success: function(responseText) {
					if (responseText == "1")
						alert("This page has been added to your favorites.");
					else
						alert("Unable to add this page to favorites.  You may do so manually by copy/pasting the url into the My Favorites -> Add field on your login dashboard.");
				}
		});
	}
}
