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);
	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 = "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);
	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);
	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;
}

/**
 * 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);
}

String.prototype.trim = function()
{
  var x = this;
  x = x.replace(/^\s*(.*)/, "$1");
  x = x.replace(/(.*?)\s*$/, "$1");
  return x;
}

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";
}

/**
 *  Parses a list of checkboxes from a specified form
 *  @return array of values of selected items
 */
function getCheckboxValues(form, id)
{
	if (!id)
		return false;

	var vals = new Array();

	if (!form)
		form = 0;

	var checks = document.forms[form][id];

	for (var i = 0; i < checks.length; i++)
		if (checks[i].checked)
			vals[vals.length] = checks[i].value;
	
	return vals;
}

/**
 * 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.");	
}