jQuery(document).ready(function() {
//	jQuery.noConflict();
	
	jQuery("ul.sf-menu").superfish();
	jQuery.getScript(gconfig.portalurl + "pamfaxuserinfo/" + (gconfig._id ? "?_id=" + gconfig._id : ""), function() {
		if(typeof pamfax_user_displayname != 'undefined' && (pamfax_user_displayname != "")) { 
			jQuery("#signlog").html("<a track='header/portal' href='" + gconfig.portalurl + "dashboard'>" + gtexts.ITEM_PORTAL + "</a>");
			if(gconfig.portalredirect) 
				document.location.href = gconfig.portalurl;
			else
			{
				setInterval(websiteping, 5 * 60 * 1000);
				if(typeof shopsiteping == "function")
					setInterval(shopsiteping, 5 * 60 * 1000);
			}
		}
	});
	try {
		jQuery('a[rel]').attr("rel", "prettyPhoto[" + jQuery(this).attr["rel"] + "]");
		jQuery("a[rel^='prettyPhoto'],a.lightbox,a[href$=\'.jpg\'],a[href$=\'.png\'],a[href$=\'.gif\']").prettyPhoto({theme: 'light_rounded'});
	} 
	catch(ex)
	{}
	jQuery("a[track],input[type='submit'][track],input[type='button'][track]").click( function(event) {
		if(OpenTrackedLink(jQuery(this)))
			event.preventDefault();
	});
	jQuery('.triplebullet,.whypamfaxbox').click( function() {window.location.href = gconfig.portalurl + 'PortalLogin/Register/?hideintro=1';} );
});

function websiteping()
{
	jQuery.get( "/" + site_language + "/?PING");
	jQuery.getScript(gconfig.portalurl + "pamfaxuserinfo/" + (gconfig._id ? "?_id=" + gconfig._id : ""));
}

var apicurrency = null;
/**
 * AJAX load rates for a given fax number.
 */
function pf_get_rate_for_number(frm)
{
	jQuery('#rates_table_loading').hide();
	jQuery('#rates_result').hide();
    var fax_number = jQuery('#fax_number').val();
    if('' == fax_number)
    {
        jQuery('#please_enter_fax_number').fadeIn();
        return;
    }
    jQuery('#please_enter_fax_number').hide();

	if(apicurrency == null)
	{
		jQuery.post('/api.php?function=Common/GetCurrentSettings', {'language_code' : site_language}, function(d) {
			apicurrency = Common.Currency.currency;
			GetPagePrice(fax_number);
		}, "script");
	}
	else
		GetPagePrice(fax_number);
}

function GetPagePrice(fax_number)
{
	Error = NumberInfo = null;
	var html= "";
    jQuery('#rates_table_loading').show();
	jQuery.post('/api.php?function=NumberInfo/GetPagePrice', {'faxnumber' : fax_number, 'apicurrency' : apicurrency, 'language_code' : site_language}, function(d) {
		if(Error && Error.result && Error.result.message)
			html = Error.result.message;
		else if(NumberInfo.result.code != "success")
			html = NumberInfo.result.message;
		else
		{
			info = "";
			if(NumberInfo.Price.number_type == "SLOW") // NumberInfo.Price.price_source had no output so the links were not generated, changed to number_type
				info = "<a href='/KB230'><b>Slow recipient</b></a>";
			else if(NumberInfo.Price.number_type == "SERVICES")
				info = "<a href='/KB230'><b>service number</b></a>";
			else if(NumberInfo.Price.number_type == "PAMFAX")
				info = "<a href='/KB5'><b>PamFax number (This fax is FREE!)</b></a>";
			else if(NumberInfo.Price.number_type == "FIXED") // Added this to remove the useless (FIXED) in output
				info = "landline";
			else if(NumberInfo.Price.number_type == "MOBILE") // Added this to remove the useless (FIXED) in output
				info = "mobile number";
			else
				info = NumberInfo.Price.number_type;
			cflag = "<span class='flag_standalone " + NumberInfo.Price.country_code + "' style='float:none; display:inline-block;margin-right: 0px;' title='" + NumberInfo.Price.country_code + "'/>&nbsp;</span>"; 

			html = "<div style='font-size: 16px; line-height: 24px; margin-left: 8px;'>Sending one page to a " + info + " in " + cflag + "(" + NumberInfo.Price.description + ")"; // NumberInfo.Price.formatted_number;
	/*		html += "<br/><br class='clearer'/>"; */
			if(NumberInfo.Price.number_type != "PAMFAX") // exchanged Price.price_source with Price.number_type to make this work
			{
				var ppp_pro = NumberInfo.Price.priceperpage_proplan;
				html += " will cost <b>" + apicurrency + " " + NumberInfo.Price.priceperpage + "</b>.<br/>Need to send more? Save with a <a href='../'>Pro Plan subscription</a> and pay only <b>" + apicurrency + " " + ppp_pro + "</b> per page!</div>"; // <img src='/shop/images/small/pamfax20-proplan.png' border=0 />
/*				html += "<td nowrap=\"nowrap\" style='width:300px; margin: 0px auto;' class='pagepriceinfo'>" + apicurrency + " " + (Math.round((NumberInfo.Price.priceperpage * 0.685) * 1000) / 1000) + " per page<br/><a href='/shop/pamfax_plans'><br/>Buy PamFax Plan incl. personal fax-in number now</a></td>"; // <img src='/shop/images/small/pamfax20-proplan.png' border=0 /> 
				html += "</tr></table>"; */
			}
			jQuery('#fax_number').val(NumberInfo.Price.number)
		}
		jQuery("#rates_result").html("<br/>" + html);
		jQuery('#rates_table_loading').hide();
		jQuery('#rates_result').fadeIn();
	}, "script");
}

var uicontainerid = 0;
function ShowFaxInInfo(title, countryprefix, countrycode, state)
{
	if(countrycode == "US" && !state)
	{
		state = jQuery("#statesdivUS select option[value='General']").val();
		if( !state || typeof(state)=='undefined' )
			state = jQuery("#statesdivUS select:first").val();
//			state = "General";
	}
	jQuery.post('/api.php?function=Shopping/ListFaxInAreacodes', {'country_code' : countrycode, 'state' : state}, function(d) {

		var html = "<p>" + _websiteStrings.TXT_NUMBER_INFO_1 + "</p>";

		if(Shopping["AreaCodes"].content.length == 0)
			html += _websiteStrings.ERR_NO_FAXIN_NUMBER_IN_COUNTRY;
		else
		{
			if(jQuery("#statesdiv" + countrycode).length > 0)
			{
				html += "<p><div style='width:40%;float:left'>" +_websiteStrings.TXT_STATE + "</div>"
				html += jQuery("#statesdiv" + countrycode).html().replace(/<select/i, "<select id=\"state_select\" onchange=\"jQuery('#message_container_" + uicontainerid + "').dialog('destroy'); ShowFaxInInfo('" + title + "', '" + countryprefix + "', '" + countrycode + "', this.value)\"");
				html += "</p><br class='clearer'/>";
			}
			if(Shopping["AreaCodes"].content.length  > 20)
			{
				html += "<div style='width:40%;float:left'>" + _websiteStrings.TXT_GROUP_SEARCH + "</div>";
				html += "<input id=\"inpacfilter\" onkeyup=\"inpacfilter_keyup('message_container_" + uicontainerid + "')\" type=\"text\" style=\"width: 200px\" />";
			}
			html += "<div style=\"height: 150px; overflow: auto; border: 1px solid gray; margin-top: 5px; margin-bottom: 5px; padding: 3px\">";
			for(k in Shopping["AreaCodes"].content)
			{
				ac = Shopping["AreaCodes"].content[k];
				html += "<div class=\"country_info_entry\" title=\""+_websiteStrings.TXT_CLICK_TO_CHECKOUT+"\" onclick=\"CheckOutFaxNumber('message_container_" + uicontainerid+"','"+countrycode+"',"+ac.id+",'"+state+"');\"><a>" + ac.city + "</a> (+" + countryprefix + " " + ac.areacode + "...)";
				if(ac.require_pi == 1)
					html += " *";
				html += "</div>";
			}
			html += "</div>";
			html += "<p>" +_websiteStrings.TXT_NUMBER_INFO_2 + "</p>";
		}
		var dialog_content   = jQuery('<div></div>').attr('id',"message_container_content").html(html);
		var dialog_container = jQuery('<div></div>').attr('id','message_container_' + uicontainerid);
		jQuery('body').append(dialog_container);
		dialog_container.attr('title', title);
		dialog_container.append(dialog_content);

		var buts={};
		buts[_websiteStrings.BTN_ABORT] = function(){jQuery(this).dialog('destroy');};

		jQuery("#message_container_" + uicontainerid).dialog({
			modal: true,
			width: 550,
			resizable: false,
			draggable: false,
			buttons: buts,
			closeOnEscape : true,
			open : function() {jQuery('#message_container_' + uicontainerid + ' #state_select').val(state);jQuery('#message_container_' + uicontainerid + ' #inpacfilter').focus();}
		});
//		jQuery(".ui-button-text:last").css("border", "1px solid red");
		jQuery(".ui-dialog-buttonpane").append("<a href=\"/shop/pamfax_professional_fax_plan\"><span class=\"signup_" + site_language + "\" style=\"float: right; margin-right: 10px;\" /></a>")
		uicontainerid ++;
	}, "script");

}

function CheckOutFaxNumber( dlg_id, countrycode, areacode, state )
{
	jQuery("#"+dlg_id).dialog('destroy');
	if( typeof(state) == 'undefined' || state == 'undefined' )
		location.href='/shop/?checkout=1&addtobasket=ProPlan12&countrycode='+countrycode+'&areacode='+areacode;
	else
		location.href='/shop/?checkout=1&addtobasket=ProPlan12&countrycode='+countrycode+'&areacode='+areacode+"&state="+state;
}

function inpacfilter_keyup(dlgid)
{
	jQuery('.country_info_entry').each( function(){
		if( jQuery(this).text().toLowerCase().indexOf(jQuery('#' + dlgid + ' #inpacfilter').val().toLowerCase()) > -1 )
			jQuery(this).show();
		else
			jQuery(this).hide();
	});
}

function OpenTrackedLink(link)
{
  try {
	if(link.attr("track") && link.attr("track") != "")
	{
		// SOLVED! tracking the click as a pageview, as events are not trackable in goals
		//pageTracker._trackPageview(link.attr("track"));
		var atrack = link.attr("track").split("/");
		if(atrack.length >= 2)
			_gaq.push(['_trackEvent', atrack[0], atrack[1]]);
	}

	if(link.attr("trackconv") && link.attr("trackconv") != "")
	{
		// also track a conversion:
		var img = new Image();
		img.onload = function(){return true;}
		img.src = "http://www.googleadservices.com/pagead/conversion/" + link.attr("trackconv") + (link.attr("trackconv").indexOf("?") == -1 ? "?" : "&") + "guid=ON&script=0";
	}

//	alert("track: " + link.attr("track") + " href: " + link.attr("href"));
	// let google some time and then forward to real url
	if( link.attr("href") )
	{
		setTimeout('document.location = "' + link.attr("href") + '"', 200)
		return true;
	}
	return false;
  }
  catch(err)
  {
//	  alert(err.message);
  }

  try {
	if( link.attr("href") )
	{
		document.location = link.attr("href");
		return true;
	}
  }
  catch(err)
  {
  }

  return false;
}

function ShowMessage(txt,type)
{
	var html = type == "error"?_websiteStrings.MSG_FORM_FAILURE +"<br>" :"";
	html += "<table><tr><td style='width:10%'></td><td><ul id='errorlist'>";
	if(txt instanceof Array)
	{
		for(var i in txt)
		{
			html += "<li>"+_websiteStrings[txt[i]]+"</li>";
		}
	}else
		html += "<li>"+txt+"</li>";
	html += "</ul></td></tr></table>";
	jQuery('#dlg').html(html);
	jQuery('#dlg').dialog('open');
}

function strip_tags(html)
{
	//PROCESS STRING
	if(arguments.length < 3) {
		html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
	} else {
		var allowed = arguments[1];
		var specified = eval("["+arguments[2]+"]");
		if(allowed){
			var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		} else{
			var regex='</?(' + specified.join('|') + ')\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		}
	}

	//CHANGE NAME TO CLEAN JUST BECAUSE 
	var clean_string = html;

	//RETURN THE CLEAN STRING
	return clean_string;
}

function PamFaxWebsite_toggleFlyout()
{
	var btn = jQuery("#signlog");
	var offset = btn.offset();
        if ($.browser.opera) { browseroffset = 10 }
        else if ($.browser.mozilla) { browseroffset = 9}
        else { browseroffset = 11 }
	var flyout = jQuery('#PamFaxWebsite_flyoutlayer');
	flyout.css("left", offset.left - flyout.outerWidth(true) + btn.outerWidth(true) + 10).css("top", offset.top + btn.outerHeight(true) + browseroffset);
    flyout.slideToggle('fast', function() { jQuery("#PamFaxWebsite_flyoutlayer [name='username']").focus(); } );
    var checker = jQuery('#PamFaxWebsite_arw').text();
    var flyoutarrow = (checker=='\u25Bc') ? '\u25B2' : '\u25Bc';
    jQuery('#PamFaxWebsite_arw').text(flyoutarrow);
}
function PamFaxWebsite_FlyoutSubmit()
{
	jQuery('#PamFaxWebsite_flyoutlayer .flyoutlogin').attr('disabled',"disabled");
	return true;
}
function PamFaxWebsite_RecoverPassword()
{
	var f = jQuery('#PamFaxWebsite_flyoutlayer form');
	var a = f.attr('action');
	f.attr('action',a.replace(/\/verify/i,"/RecoverPassFromWebsite")).submit();
	return true;
}
