/*
 * Common
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
function activateCommon(){
	$('#userInfo').jqTransform({
		imgPath: '/img/new/formStyle/'
	});
	$('#loginWidget .loginControls').jqTransform({
		imgPath: '/img/new/formStyle/'
	});
	$("#editProfile").click(function(){
		window.location="http://profil.gsmservice.pl";
	});
	$("#logout").click(function(){
		window.location = "/logout.php";
	});
	$("#loginForm").submit(function(event){
		event.preventDefault();
		$("#alert #alertBoxBody").replaceWith(progressAlert(lang.pleaseWait));
		$("#alert").fadeIn("slow",function(){
			$.ajax({
				type: "POST",
				url: "/engine/login.ajax.php",
				data: $("#loginForm").serialize(),
				dataType: "xml",
				error: function() {
					$("#alert #alertBoxBody").fadeOut("fast",function(){
						$(this).replaceWith(errorAlert(lang.connectionError, 121, lang.close)).fadeIn("fast");
					});
				},
				success: function(xml){					
					$("#alert #alertBoxBody").fadeOut("fast",function(){
						if ($(xml).find("status").text() == "OK") {
							$(this).replaceWith(progressAlert(lang.loadingInProgress)).fadeIn("fast", function(){
								location.reload();
							});
						}
						else
							$(this).replaceWith(errorAlert($(xml).find("statusDescription").text(), $(xml).find("statusCode").text(), lang.close)).fadeIn("fast");
					});
				}
			});
		});
	});
	$("#registerBtn")
		.hover(
			function(){
				$(this).css("backgroundPosition","0 -56px");
			},
			function(){
				$(this).css("backgroundPosition","0 0");
			}
		)
		.mousedown(function(){
			$(this).css("backgroundPosition","0 -115px");
		})
		.mouseup(function(){
			$(this).css("backgroundPosition","0 -56px");
		});

	activateToolTip();

	$(".helpInfo DIV[id^=dot_]").click(function(){
		var bodyId = $(this).attr("id");
		$(".helpInfo DIV[id^=body_dot_]").hide();
		$(".helpInfo DIV#body_"+bodyId).show();
		$(".helpInfo DIV[id^=dot_]").removeClass("activeDot");
		$(this).addClass("activeDot");
	});
}

/*
 * Utils
*/
function strtr(tekst, tablica, zmienna2)
{
	if ((typeof(tablica)=="object") && (tablica.length))
	{
		for (i in tablica)
		{
			tekst = tekst.replace(RegExp(tablica[i][0], "g"), tablica[i][1])
		}
		return tekst
	}
	else
	{
		tablica2 = new Array();
		for(i = 0; i < tablica.length; i++)
			tablica2[i] = [tablica.substr(i,1), zmienna2.substr(i,1)]
		return strtr(tekst, tablica2)
	}
}

function smsCharCount(message) {
  var gsm7bitUnits = 0;
  var utf16codeUnits = 0;
    
  for (var i = 0, len = message.length; i < len; i++) {
    if (gsm7bitUnits != null) {
      if (gsm7bitChars.indexOf(message.charAt(i)) > -1) {
        gsm7bitUnits++;
      } else if (gsm7bitExChar.indexOf(message.charAt(i)) > -1) {
        gsm7bitUnits += 2;
      } else {
        gsm7bitUnits = null;
      }
    }
    utf16codeUnits += message.charCodeAt(i) < 0x10000 ? 1 : 2;  
  }
  return [gsm7bitUnits, utf16codeUnits];
}
(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
    if (arguments.length == 0) { //get
      if (target.selectionStart) { //DOM
        var pos = target.selectionStart;
        return pos > 0 ? pos : 0;
      }
      else if (target.createTextRange) { //IE
		target.focus();
		var range = document.selection.createRange();
		if (range == null)
			return '0';
		var re = target.createTextRange();
		var rc = re.duplicate();
		re.moveToBookmark(range.getBookmark());
		rc.setEndPoint('EndToStart', re);
		return rc.text.length;
      }
      else return 0;
    } //set
    if (target.setSelectionRange) //DOM
      target.setSelectionRange(pos, pos);
    else if (target.createTextRange) { //IE
      var range = target.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
})(jQuery)


function popUpList(content){
	var elem = $("<div class=\"popupList\" />");
	elem
		.append($("<img src=\"/img/gateway/main/addressBookList/addressBookElement1.png\" class=\"pulElement1\" alt=\"\" />"))
		.append($("<img src=\"/img/gateway/main/addressBookList/addressBookElement2.png\" class=\"pulElement2\" alt=\"\" />").click(function(){
			elem.fadeOut("fast", function(){
				$(this).remove();
			});
		}))
		.append($("<div class=\"pulTopOuter\"><div class=\"pulTopMiddle\"><div class=\"pulTopInner\">&nbsp;</div></div></div>"))
		.append($("<div class=\"pulMiddle\" />").html(content))
		.append($("<div class=\"pulBottomOuter\"><div class=\"pulBottomMiddle\"><div class=\"pulBottomInner\">&nbsp;</div></div></div>"))
	;
	return elem;
}
function openSender(event)
{
	var formSmsMsgType = $("INPUT[type=radio][name=smsMsgType]");
	var formSmsSender = $("INPUT[type=text][name=smsSender]");
		
	event.preventDefault();
	if ($("#selectSenderIcon").has($(".popupList")).length > 0) {
		$("#selectSenderIcon .popupList").fadeOut("fast", function(){
			$(this).remove();
		});
	}
	else {
			var elem = $("<div class=\"popupListLoading\" />");
		 elem
	 		.append($("<div class=\"text\" />").text(lang.pleaseWait))
	 		.append($("<div class=\"progressBar\" />").append($("<img src=\"/img/gateway/common/progress.gif\" alt=\"\" />")));

		$("#selectSenderIcon").append(popUpList(elem));
		$("#selectSenderIcon .popupList").fadeIn("fast", function(){
			$.ajax({
					type: "POST",
					url: "/engine/loadSenders.ajax.php",
					data: "",
					dataType: "xml",
					error: function() {
						$("#alert #alertBoxBody").replaceWith(errorAlert(lang.connectionError, 121, lang.close));
						$("#alert").fadeIn("slow");
						$("#selectSenderIcon .popupList").fadeOut("fast", function(){
							$(this).remove();
						});
					},
					success: function(xml){
						if ($(xml).find("status").text() == "OK") {
							var elem = $("<ul class=\"senderBody\" />");
							$(xml).find("senders").find("senderItem").each(function(){
								if ($(this).find("pl_allowed").text()==1)
									plImg = "<img src=\"/img/gateway/common/icons/pl.png\" alt=\"\" title=\"Aktywny do polskich sieci\" />";
								else
									plImg = "";
								elem.append($("<li class=\"clearfix\" />").html("<div class=\"senderName\">"+$(this).find("sender").text()+"</div><div class=\"senderAllowed\"><img src=\"/img/gateway/common/icons/world.png\" alt=\"\" title=\"Aktywny do zagranicznych sieci\" />"+plImg+"</div><div class=\"senderActions\">Wstaw</div>"));
							});
							elem.find("li").click(function(){
								if (formSmsMsgType.filter(":checked").val() == 3) {
									$("#alert #alertBoxBody").replaceWith(errorAlert(lang.senderDisabled, 0, lang.close));
									$("#alert").fadeIn("slow");
								}
								else {
									formSmsSender.val($(this).find(".senderName").text());
								}
								$("#selectSenderIcon .popupList").fadeOut("fast", function(){
									$(this).remove();
								});
							});
							$(".popupListLoading").replaceWith(elem);
						}else{
							$("#alert #alertBoxBody").replaceWith(errorAlert($(xml).find("statusDescription").text(), $(xml).find("statusCode").text(), lang.close));
							$("#alert").fadeIn("slow");
							$("#selectSenderIcon .popupList").fadeOut("fast", function(){
								$(this).remove();
							});
						}
					}
				});
		});
	}
}
function activateTabs(tab, url, script, callb){
	if(!tab.hasClass("activeTab"))
	{
		showProgressBar($("DIV#tabBody:visible"),$("DIV.tabBody.progress"),true);
		$.ajax({
			type: "POST",
			url: url,
			data: "activeTab=" + tab.attr("id"),
			error: function() {
				showProgressBar($(".mainbox #tabBody"),$("DIV.tabBody.progress"),false);
				$("#alert #alertBoxBody").replaceWith(errorAlert(lang.connectionError, 121, lang.close));
				$("#alert").fadeIn("slow");
			},
			success: function(xml){
				if ($(xml).find("status").text() == "OK") {
					var activate = true;
					if(!$.isFunction(window[callb]))
					{
						$.ajax({
							url: script,
							dataType: 'script',
							async: false,
							error: function(){
								showProgressBar($(".mainbox #tabBody"), $("DIV.tabBody.progress"), false);
								$("#alert #alertBoxBody").replaceWith(errorAlert(lang.connectionError, 121, lang.close));
								$("#alert").fadeIn("slow");
								activate = false;
							}
						});
					}
					if (activate) {
						$(".mainBoxTabs li").not(tab).fadeOut("slow",function(){$(this).removeClass("activeTab").fadeIn("fast")});
						tab.fadeOut("slow",function(){$(this).addClass("activeTab").fadeIn("fast")});

						$("#tabBody").replaceWith($(xml).find("tabContent").text());
						$(".mainbox #tabBody").hide();
						showProgressBar($(".mainbox #tabBody"), $("DIV.tabBody.progress"), false);
						$('#tabBody').jqTransform({
							imgPath: '/img/new/formStyle/'
						});
						eval(callb+'()');
					}
				}
				else {
					$("#alert #alertBoxBody").replaceWith(errorAlert($(xml).find("statusDescription").text(), $(xml).find("statusCode").text(), lang.close));
					$("#alert").fadeIn("slow");
					showProgressBar($(".mainbox #tabBody"), $("DIV.tabBody.progress"), false);
				}
			}
		});
	}
}
