﻿function MessageSender(messageSenderData) {
	if (typeof messageSenderData !== "object" || messageSenderData == null) throw "messageSenderData is null or not an object";
	this.maxSMSChars = messageSenderData.maxSMSChars;
	this.maxMMSChars = Number.MAX_VALUE;
	this.isSMSMessage = true;
	this.markedMMSImage; //MMS image from cellcom gallery that was selected for mms sending
	this.recipients = {};
	this.mmsNotValidRecipients = 0;
	this.isExtendedSmsControl = messageSenderData.isExtendedSmsControl;
	this.recipientsCounter = 0;
	
	this.toolTipTimeout = null;
	
	//tabs members
	this._totalTabs = 2;
	this._currTabInd = 2;
	this._areTabsFrozen = false;
	
	//strange behaviour mouseover images on IE
	this.imgGalOverStyle = "2px solid #540A47";
	this.imgGalOutStyle = "2px solid transparent";
	this.imgGalOverStyle_IE = "#540A47";
	this.imgGalOutStyle_IE = "transparent";
	
	this.maxTextGalleryLength = 10; //maximum number of char. for the gallery picture. if exceeded, ... is suffixed
	
	this.getMaxMessageChars = function() {
		return this.isSMSMessage? this.maxSMSChars : this.maxMMSChars;
	}
	
	this.updateNumberOfMessagesToSend = function() {
		messageSenderData.numberOfMessages.innerHTML = this.getNumberOfMessages(messageSenderData.message.value.length);
		//messageSenderData.numberOfCharacters.innerHTML = this.isSMSMessage? messageSenderData.message.value.length : "[text]";
		if (messageSenderData.message.value.length > 0 && this.isExtendedSmsControl) messageSenderData.messageErrors.style.display = "none";
	}
	
	this.getNumberOfMessages = function(currentChars) {
		if (currentChars == 0) return 0;
		return Math.ceil(currentChars/this.getMaxMessageChars());
		//return Math.ceil((currentChars + (messageSenderData.isAnonymousMessage.checked? 0 : messageSenderData.userName.length))/this.getMaxMessageChars()); NOTE: This line should be activated if we want to add user details to message chars count
	}

	this.addIconToMessage = function(iconString, hideIconsList) {
		messageSenderData.message.value += " " + iconString;
		this.highlightSMSPriceAndMessagesTableBackground();
		this.updateNumberOfMessagesToSend();
		if (hideIconsList) this.hideIconsList();
		messageSenderData.message.focus();
	}
	
	/*****
	showHideIconsList
	this will show or hide the emoticons layer	
	*****/
	this.showHideIconsList = function() {
	    this.removeHighlightMMSPriceAndMessagesTableBackground();
		if (messageSenderData.icons.style.display == "block") {
			this.hideIconsList();
			return;
		}
		// for some reasons, the layer is not displayed in the same way regarding the different browsers
		// this is why adjustment need to be done
		if (navigator.appName.toLowerCase().indexOf("explorer") > -1) 
		{
			messageSenderData.icons.style.marginTop = "-55px";
			messageSenderData.icons.style.marginRight = "0px";
			//in IE, the border property is required in order to display the black border
			messageSenderData.iconsActivator.border = "1";
			if ($.browser.version.substring(0,1) == "6")
			    messageSenderData.icons.style.left = "-175px";
			else
			{
			    messageSenderData.icons.style.left = "-159px";
			}
		} 
		else 
		{
			messageSenderData.icons.style.marginTop = "-49px";
            messageSenderData.icons.style.left = "-135px";			
		}
		messageSenderData.icons.style.display = "block";
		messageSenderData.iconsActivator.style.borderRight = "1px solid black";
		messageSenderData.iconsActivator.style.borderBottom = "1px solid black";
		messageSenderData.iconsActivator.style.borderLeft = "1px solid black";
		messageSenderData.iconsActivator.style.borderTop = "1px solid black";
	}
	
	/*****
	hideIconsList
	this will hide the emoticons layer	
	*****/
	this.hideIconsList = function() {
	    if (messageSenderData.icons == null)
	        return;
	        
	    messageSenderData.icons.style.display = "none";
	    
	    var border = "1";
	    //in IE6, transparent borders can NOT be applied if border value is not set to 0!
	    if ($.browser.msie && $.browser.version.substring(0, 1) == "6")
	        border = "0";    
	        
	    $("img.mainSmile").css("border-right", border + "px solid transparent");
        $("img.mainSmile").css("border-left", border + "px solid transparent");
        $("img.mainSmile").css("border-bottom", border + "px solid transparent");
        $("img.mainSmile").css("border-top", border + "px solid transparent");
        
		if ($.browser.msie) {
		 messageSenderData.iconsActivator.border = "0";
		}   
	}
	
	this.ajaxFileUpload = function() {
	    $(".addPicture").css("display", "none");
	    $(".picUploading").css("display", "block");
	    
//		$(messageSenderData.loadingImage)
//		.ajaxStart(function() {	$(this).show();	})
//		.ajaxComplete(function() { $(this).hide(); });
	
		/*
		prepareing ajax file upload
		url: the url of script file handling the uploaded files
        fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
		dataType: it support json, xml
		secureuri:use secure protocol
		success: call back function when the ajax complete
		error: callback function when the ajax failed
        */
		$.ajaxFileUpload({
			url: messageSenderData.fileUploadUrl,
			secureuri: messageSenderData.useSSL,
			fileElementId: messageSenderData.uploadFileID,
			dataType: 'json',
			controlId: messageSenderData.userControlID,
			uploadedImage: messageSenderData.uploadedImage,
			success: function (data, status) {
				if (typeof(data.error) != 'undefined') {
					if (data.error != '') {
						messageSenderData.uploadedError.innerHTML = data.error;
						messageSenderData.uploadedError.style.display = "block";
						messageSenderData.checkedImage.style.display = "none";
						messageSenderData.mmsFileToSend.value = "";
					} else {
						messageSenderData.uploadedImage.src = data.msg;
						messageSenderData.checkedImage.style.display = "block";
						messageSenderData.uploadedError.style.display = "none";
						messageSenderData.mmsGallery.style.display = "none";
						messageSenderData.mmsFileToSend.value = "custom";
						$(messageSenderData.mmsImageErrors).parent().parent().addClass("displayNone");
						var obj = messageSenderData.instanceName;
						eval(obj + ".doSetAllTabsDisabledExceptSelected()");
					}
				}
				$(".addPicture").css("display", "block");
	            $(".picUploading").css("display", "none");
			},
			error: function (data, status, e)
			{
				messageSenderData.uploadedError.innerHTML = messageSenderData.errorMessages.fileUploadGeneralError;
				messageSenderData.uploadedError.style.display = "block";
				messageSenderData.uploadedImage.style.display = "none";
				messageSenderData.mmsFileToSend.value = "";
				$("#mmsSelectedImageName").html("");
				$(".addPicture").css("display", "block");
	            $(".picUploading").css("display", "none");
			}
		});
		return false;
	}
	
	/*****
	buildIconsTable
	builds the images gallery	
	*****/
	this.buildIconsTable = function(icons) {
		if (typeof icons !== "object" || icons == null) return;
		var result = "";
		var txtTooltip = "";
		var displayText = "";
		for (var i = 0; i < icons.length; ++i) {
		    
		    if (icons[i].name.length > this.maxTextGalleryLength)
		    {
		        displayText = icons[i].name.substring(0, this.maxTextGalleryLength) + "...";
		        txtTooltip = icons[i].name;
		    }
		    else
		    {
		        displayText = icons[i].name;
		        txtTooltip = icons[i].name;
		    }
		    /*
		        mouseover mouseout: for some reasons, the call of a javascript method does not work with FF.
		        do NOT remove the logical here
		    */
			result += "<div class='itemContainer'><div class='unselectedGalleryImage' onmouseover=\"if(!$.browser.msie){this.style.border = " + messageSenderData.instanceName + ".imgGalOverStyle;}else{" + messageSenderData.instanceName + ".doImgGalleryOver(this, true);}\" onmouseout=\"if(!$.browser.msie){this.style.border = " + messageSenderData.instanceName + ".imgGalOutStyle;}else{" + messageSenderData.instanceName + ".doImgGalleryOver(this, false);}\"><table border='0' cellspacing='0' cellpadding='0' width='100%'><tr><td align='center' width='100%'><table border='0' cellspacing='5' cellpadding='0'><tr><td><img src=\"" + icons[i].url + "\" onclick=\"" + messageSenderData.instanceName + ".selectMMSImage('" + icons[i].url + "', '" + icons[i].id + "', '" + icons[i].name + "');" + messageSenderData.instanceName + ".doSetAllTabsDisabledExceptSelected();\" width='" + messageSenderData.MMSImageWidth + "' height='" + messageSenderData.MMSImageHeight + "'/></td></tr><tr><td class='rightAlign' title='" + txtTooltip + "'>" + displayText + "</td></tr></table></td></tr></table></div>";
			i++;
			if (i < icons.length) 
			{
			    if (icons[i].name.length > this.maxTextGalleryLength)
		        {
		            displayText = icons[i].name.substring(0, this.maxTextGalleryLength) + "...";
		            txtTooltip = icons[i].name;
		        }
		        else
		        {
		            displayText = icons[i].name;
		            txtTooltip = icons[i].name;
		        }
    			
			    result += "<div class='unselectedGalleryImage' onmouseover=\"if(!$.browser.msie){this.style.border = " + messageSenderData.instanceName + ".imgGalOverStyle;}else{" + messageSenderData.instanceName + ".doImgGalleryOver(this, true);}\" onmouseout=\"if(!$.browser.msie){this.style.border = " + messageSenderData.instanceName + ".imgGalOutStyle;}else{" + messageSenderData.instanceName + ".doImgGalleryOver(this, false);}\"><table border='0' cellspacing='0' cellpadding='0' width='100%'><tr><td align='center' width='100%'><table border='0' cellspacing='5' cellpadding='0'><tr><td><img src=\"" + icons[i].url + "\" onclick=\"" + messageSenderData.instanceName + ".selectMMSImage('" + icons[i].url + "', '" + icons[i].id + "', '" + icons[i].name + "');" + messageSenderData.instanceName + ".doSetAllTabsDisabledExceptSelected();\" width='" + messageSenderData.MMSImageWidth + "' height='" + messageSenderData.MMSImageHeight + "'/></td></tr><tr><td class='rightAlign' title='" + txtTooltip + "'>" + displayText + "</td></tr></table></td></tr></table></div>";
			}
			result += "</div>";
		}
		
		messageSenderData.mmsImages.innerHTML = result;
		if (typeof scrollableAPI !== "object" || scrollableAPI == null) {
			$("div.scrollable").scrollable({size:5, clickable: false, keyboard: false, disabledClassPrev: "disabledNavPrev", disabledClassNext: "disabledNavNext"});
			scrollableAPI = $("div.scrollable").scrollable({size:5, clickable: false, keyboard: false, disabledClassPrev: "disabledNavPrev", disabledClassNext: "disabledNavNext"});
		}
		
		this.adjustScroll();
		this.alignGalleryIconsRightWhenNoScroll();	
	}
	
	/*****
	alignGalleryIconsRightWhenNoScroll
	align all the icons in the gallery on the right of the gallery in case of no navigation arrows are not visible (less than 12 pictures)	
	*****/
	this.alignGalleryIconsRightWhenNoScroll = function()
	{
	    //there are problems in IE6 with the float property. this is fixed here
	    if (scrollableAPI.getPageAmount() == 1)
	    {
	        if (!($.browser.msie && $.browser.version.substring(0 ,1) == "6"))
	        {
	            $(".itemContainer").css("float", "right");
	            $(".items").css("right", "0px");
	        }
	        else
	        {
	            $(".items").css("left", "294px");
	            this.redefineItemContainerClassIE();
	        }
	    }
	    else
	    {
	        if (!($.browser.msie && $.browser.version.substring(0 ,1) == "6"))
	        {
	            $(".itemContainer").css("float", "left");
	            $(".items").css("left", "0px");
	        }
	        else
	        {
	            $(".items").css("left", "0px");
	            this.redefineItemContainerClassIE();
	        }
	    }
	}
	
	/*****
	adjustScroll
	two functions:
	1- adjust the pictures position in the gallery after a new gallery is loaded or tabs are switched
	    this adjustment is required in IE only. really strange behaviour which is fixed here
	2- calculate the visibility of the navigation arrows according the number of pages in the gallery
	*****/
	this.adjustScroll = function()
	{
	    
	    messageSenderData.mmsImages.style.left = "0px";
		scrollableAPI.begin();
	    if ($.browser.msie)
	    {
		    if ($.browser.version.substring(0 ,1) == "6")
            {
                this.redefineItemContainerClassIE();
            }
	        $(messageSenderData.GalScrollContainer).removeClass("GalScrollContainer");
            $(messageSenderData.GalScrollContainer).addClass("GalScrollContainer"); 
	    }     
	    if (scrollableAPI.getPageAmount() == 1)
        {
            $(messageSenderData.GalleryPrevArrow).addClass("disabledNavPrev");
            $(messageSenderData.GalleryNextArrow).addClass("disabledNavNext");
        }
        else if (scrollableAPI.getPageAmount() > 1)
        {
            $(messageSenderData.GalleryNextArrow).removeClass("disabledNavNext");
            $(messageSenderData.GalleryNextArrow).addClass("next");
        }
	}
	
	/*****
	redefineItemContainerClassIE
	used in IE6 only. re-initialise the content of a layer.
	this is the technics used when there is some layer strange behaviour in IE6
	*****/
	this.redefineItemContainerClassIE = function()
	{
	   $(messageSenderData.mmsImages).find(".itemContainer").each(function() 
	   {
	       $(this).html($(this).html());
	   }); 
	}
	
	/*****
	doImgGalleryOver
	used in IE only. 
	rollover function on images located into the gallery (add a frame)
	*****/
	this.doImgGalleryOver = function(obj, bOver)
	{
	   
	    if (bOver)
	        obj.style.borderColor = this.imgGalOverStyle_IE;
	    else
	    {
	        if ($.browser.version.substring(0, 1) == "6")
	        {
	            //IE6 only. don't change the pink value. this value is just for notification in IE6 for the chroma
    	        $(obj).css("border", "2px solid");
    	        $(obj).css("border-color", "pink");
    	        $(obj).css("filter", "chroma(color=pink)");
	        }
	        else
	        obj.style.borderColor = this.imgGalOutStyle_IE;
	    }
	        
	}
	
	this.getMMSImagesFromServer = function(categoryId) {
		var context = this;
		$.getJSON(location.href, {getMMSImagesFromServer: messageSenderData.userControlID, mmsImagesCategoryId: categoryId, action: "getMMSImages" }, function(data, textStatus) {
			if (typeof textStatus !== "string" || textStatus.toLowerCase() != "success") throw "התרחשה שגיאה כללית";
			context.buildIconsTable(data);
		});
	}
	
	/*****
	activateCategoryLink
	this makes the current category active
	*****/
	this.activateCategoryLink = function(categoryInd, categoryID)
	{
	   var lnkID;
	   var catInd;
	   var catID;
	   var onClickAttr;
	   var bSetSelected = false;
	   
	   //loop over all the categories and extract corresp. ID or index 
	   //then checks if current one and apply style accordingly 
	   $(messageSenderData.mmsGallery).find(".divCategories").each(function() 
	   {
           if (categoryInd != null)
           {
                lnkID = $(this).find("a")[0].id;
		        catInd = extractCategoryIndFromID(lnkID);
		        if (categoryInd == catInd)
		            bSetSelected = true;
		        else
		            bSetSelected = false;
           }
           else if (categoryID != null)
           {
                onClickAttr = $(this).find("a")[0].attributes["onclick"].nodeValue;
		        catID = extractCategoryIDFromAttr(onClickAttr);
		        if (categoryID == catID)
		            bSetSelected = true;
		        else
		            bSetSelected = false;
           } 
		   
		   if (bSetSelected)
		       $($(this).find("a")[0]).addClass("lnkSelectedCategory");
		   else
		       $($(this).find("a")[0]).removeClass("lnkSelectedCategory");
		}); 
	}
	
	/*****
	enableMMS
	this switches between SMS or MMS activation
	*****/
	this.enableMMS = function(enableMms) {
		if (typeof enableMms !== "boolean") return false;
		this.isSMSMessage = !enableMms;
		this.updateNumberOfMessagesToSend();
		
		if (enableMms) {
		    if ($.browser.msie)
		        $(messageSenderData.GalScrollContainer).css("visibility", "hidden");
		        
		    messageSenderData.mmsPart.style.display = "block";
		    $(".MMSSeparatorH").parent().css("display", "block");
		    
		    this.adjustScroll();
		    
			this.removeHighlightSMSPriceAndMessagesTableBackground();
			messageSenderData.smsPriceAndMessages.style.display = "none";
			messageSenderData.mmsPriceAndMessages.style.visibility = "visible";
			messageSenderData.oneMMSMessage.style.display = "block";
			$(messageSenderData.messageErrors).css("display", "none");
			
			if (this.mmsNotValidRecipients > 0) {
				messageSenderData.contactsErrors.style.display = "block";
				messageSenderData.contactsErrorsText.innerHTML = messageSenderData.errorMessages['recipientsContainsNotValidMMSPhones'];
			}
			
			this.highlightMMSPriceAndMessagesTableBackground();
			
			// in IE, this is the trick to use in order to make the gallery to be displayed. Really strange bug
			// the asynchroneous call is important here
			if ($.browser.msie)
			{
			    var ind = window.setTimeout(messageSenderData.instanceName + ".simulateClick(" + this._currTabInd + ")", 1);
			}
			
		} else {
		    messageSenderData.mmsPart.style.display = "none";
			messageSenderData.smsPriceAndMessages.style.display = "block";
			messageSenderData.mmsPriceAndMessages.style.visibility = "hidden";
			messageSenderData.contactsErrors.style.display = "none";
			messageSenderData.oneMMSMessage.style.display = "none";
			$(".MMSSeparatorH").parent().css("display", "none");
			$(messageSenderData.mmsImageErrors).parent().parent().addClass("displayNone");
			this.removeHighlightMMSPriceAndMessagesTableBackground();
		}
	} 
	
	/*****
	simulateClick
	called in the enableMMS function for IE only
	for some reasons, the images are not displayed. the only way to display them is to simulate a 
	click on the relevant tab
	*****/
	this.simulateClick = function(ind)
	{
	    var objTab = eval("messageSenderData.tdTabDef" + ind);
	    $(objTab).click();
	    $(messageSenderData.GalScrollContainer).css("visibility", "visible");
	}  
	
	/*****
	removeCheckedMMSImage
	makes the gallery enabled again after one image has been selected
	*****/
	this.removeCheckedMMSImage = function() {
		messageSenderData.uploadedImage.src = "";
		messageSenderData.checkedImage.style.display = "none";
		messageSenderData.uploadedError.style.display = "none";
		messageSenderData.mmsGallery.style.display = "block";
		messageSenderData.mmsFileToSend.value = "";
		$("#" + messageSenderData.uploadFileID).val("");
		$("#mmsSelectedImageName").html("");
		this.unmarkMMSImage();
		this.doUnfreezeTabs();
   
	    this.adjustScroll();
	    if ($.browser.msie && $.browser.version.substring(0, 1) == "6")
            this.alignGalleryIconsRightWhenNoScroll();
	}
	
	/*****
	selectMMSImage
	make one image selected
	*****/
	this.selectMMSImage = function(imageSrc, id, name) {
		messageSenderData.uploadedImage.src = imageSrc;
		messageSenderData.checkedImage.style.display = "block";
		messageSenderData.mmsGallery.style.display = "none";
		messageSenderData.mmsFileToSend.value = id;
		$(messageSenderData.mmsImageErrors).parent().parent().addClass("displayNone");
		if (typeof name !== "undefined") $("#mmsSelectedImageName").html(name);
	}
	
	this.markMMSImage = function(image) {
		this.unmarkMMSImage();
		this.markedMMSImage = image;
		$(image).parent().addClass("changeMMSImageBackground");
	}
	
	this.unmarkMMSImage = function() {
		if (typeof this.markedMMSImage !== "undefined") $(this.markedMMSImage).parent().removeClass("changeMMSImageBackground");
		this.markedMMSImage = undefined;
	}
	
	this.highlightSMSPriceAndMessagesTableBackground = function() {
		if (this.isExtendedSmsControl) $(messageSenderData.smsPriceAndMessages).addClass("BoxInfoHighlight");
	}
	
	this.removeHighlightSMSPriceAndMessagesTableBackground = function() {
		if (this.isExtendedSmsControl) $(messageSenderData.smsPriceAndMessages).removeClass("BoxInfoHighlight");
	}
	
	this.highlightMMSPriceAndMessagesTableBackground = function() {
		if (this.isExtendedSmsControl) $(messageSenderData.mmsPriceAndMessages).addClass("BoxInfoHighlight");
	}
	
	this.removeHighlightMMSPriceAndMessagesTableBackground = function() {
		if (this.isExtendedSmsControl) $(messageSenderData.mmsPriceAndMessages).removeClass("BoxInfoHighlight");
	}

	this.validateFormBeforeSend = function () {
	    var result = true;
	    if (this.isExtendedSmsControl) {
	        if (this.isSMSMessage) {
	            if (messageSenderData.message.value.length == 0) {
	                result = false;
	                messageSenderData.messageErrors.style.display = "block";
	            } else messageSenderData.messageErrors.style.display = "none";
	        } else {
	            if (messageSenderData.mmsFileToSend.value.length == 0) {
	                result = false;
	                $(messageSenderData.mmsImageErrors).parent().parent().removeClass("displayNone");
	            } else {
	                $(messageSenderData.mmsImageErrors).parent().parent().addClass("displayNone");
	            }
	        }
	        if (this.recipientsCounter == 0) {
	            result = false;
	            messageSenderData.contactsErrors.style.display = "block";
	            messageSenderData.contactsErrorsText.innerHTML = messageSenderData.errorMessages["contactsNotSelected"];
	        } else messageSenderData.contactsErrors.style.display = "none";
	    }

	    if (!this.validateTalkmanCustomer()) {
	        result = false;
	        if (messageSenderData.talkmanBalance <= 0) this.showUpperWarnings(messageSenderData.errorMessages.userWithoutBalance);
	        else this.showUpperWarnings(messageSenderData.errorMessages.userWithNotEnougthBalance);
	    } else if (typeof messageSenderData.userName === "string" && jQuery.trim(messageSenderData.userName).length > 0 && typeof messageSenderData.isLockedUser === "boolean" && messageSenderData.isLockedUser) {
	        result = false;
	        this.showUpperWarnings(messageSenderData.errorMessages.lockedUser);
	    }

	    messageSenderData.hidPhones.value = "";
	    if (typeof this.recipients === "object" && this.recipients != null) {
	        for (property in this.recipients) messageSenderData.hidPhones.value += property + ",";
	    }
	    return result;
	}
	
	this.preSaveUserData = function() {
		this.validateFormBeforeSend();
		$.post(location.href, {msgTxt: messageSenderData.message.value, msgContacts: messageSenderData.hidPhones.value, action: "preSaveUserData" }, function(data) {});
		return false;
	}
	
	this.createNewContactAndNormalizeUI = function(phone, firstName, secondName, buttonControl, firstNameWarningControl, resultControl) {
	    if ($(buttonControl).attr("class") == "AddToPhoneBookBtnDis")
	        return;
	        
		$(resultControl).html("");
		if (typeof firstName === "undefined" || jQuery.trim(firstName).length == 0 || jQuery.trim(firstName).toLowerCase() == messageSenderData.firstNameDefaultText.toLowerCase()) {
			$("#" + firstNameWarningControl.id + " .contactFirstNameWarning").html(messageSenderData.errorMessages.contactFirstNameWarning);
			return;
		}
		$("#" + firstNameWarningControl.id + " .contactFirstNameWarning").html("");
		if (typeof secondName === "undefined" || jQuery.trim(secondName).length == 0 || jQuery.trim(secondName).toLowerCase() == messageSenderData.secondNameDefaultText.toLowerCase()) secondName = "";
		this.createNewContact(phone, firstName, secondName, buttonControl, resultControl);
	}
	
	this.createNewContact = function(phone, firstName, secondName, buttonControl, resultControl) {
		$(buttonControl).removeClass("AddToPhoneBookBtn");
		$(buttonControl).addClass("AddToPhoneBookBtnDis");
		
		var inputTags = $(buttonControl).closest("table").find("input");
		inputTags.attr("disabled", "disabled");
		inputTags.css("background-color", "white");
		$.post(location.href, {contactPhoneNumber:phone, contactFirstName: firstName, contactSecondName: secondName, action: 'createNewContact' }, function(data) {
				if (typeof data.error !== "undefined") {
					$(resultControl).html(messageSenderData.errorMessages.newContactNotAdded);
					$(buttonControl).removeAttr("disabled");
					$(buttonControl).css("background-color", currBackground);
					inputTags.removeAttr("disabled", "disabled");
				} else {
					$(resultControl).html(messageSenderData.errorMessages.newContactAdded);
					/*inputTags.attr("readonly", "readonly");
					inputTags.attr("onfocus", "");
					inputTags.attr("onblur", "");*/
				}
			}, "json");
	}
	
	this.addRecipient = function(object) {
		if (this.isExtendedSmsControl) messageSenderData.contactsErrors.style.display = "none";
		if (object == null || typeof object !== "object") return;
		$("ul.holder span").remove();
		if (typeof object._params === "undefined" && typeof object._value !== "undefined") {
			this.recipients[object._value] = object._value;
			this.addRecipientsToCounter(1);
			if (!isCellularPhone(object._value) && this.isExtendedSmsControl) {
				this.mmsNotValidRecipients ++;
				if (!this.isSMSMessage) {
					messageSenderData.contactsErrors.style.display = "block";
					messageSenderData.contactsErrorsText.innerHTML = messageSenderData.errorMessages['mmsContainsNotValidPhone'].replace(/\{0\}/g, object._value);
				}
			}
		}
		else {
			var params = typeof object._params === "string"? eval('(' + object._params + ')') : object._params;
			if (params.type == "c") {
				this.recipients[params.value] = params.value;
				this.addRecipientsToCounter(1);
				if (!isCellularPhone(params.value) && this.isExtendedSmsControl) {
					this.mmsNotValidRecipients ++;
					if (!this.isSMSMessage) {
						messageSenderData.contactsErrors.style.display = "block";
						messageSenderData.contactsErrorsText.innerHTML = messageSenderData.errorMessages['mmsContactContainsNotValidPhone'].replace(/\{0\}/g, params.name);
					}
				}
			} else if (params.type == "g") {
				this.recipients["gid:" + params.id] = params.id;
				this.addRecipientsToCounter(params.contactsCount);
				if (!params.isAllContactsInGroupSupportMMSMessage  && this.isExtendedSmsControl) {
					this.mmsNotValidRecipients ++;
					if (!this.isSMSMessage) {
						messageSenderData.contactsErrors.style.display = "block";
						messageSenderData.contactsErrorsText.innerHTML = messageSenderData.errorMessages["mmsGroupContansNotValidPhones"];
					}
				}
			}
		}
		this.addClickEventToMainInput();
	}
	
	this.removeRecipient = function(object) {
		if (this.isExtendedSmsControl) messageSenderData.contactsErrors.style.display = "none";
		if (($(".holder li").length - 1) == 1) this.initAutoComplete(true);
		
		if (object == null || typeof object !== "object") return;
		if (typeof object._params === "undefined" && typeof object._value !== "undefined") {
			delete this.recipients[object._value];
			this.substractRecipientsFromCounter(1);
			if (!isCellularPhone(object._value) && this.isExtendedSmsControl) this.mmsNotValidRecipients --;
		} else {
			var params = typeof object._params === "string"? eval('(' + object._params + ')') : object._params;
			if (params.type == "c") {
				delete this.recipients[params.value];
				this.substractRecipientsFromCounter(1);
				if (!isCellularPhone(params.value) && this.isExtendedSmsControl) this.mmsNotValidRecipients --;
			} else if (params.type == "g") {
				delete this.recipients["gid:" + params.id];
				this.substractRecipientsFromCounter(params.contactsCount);
				if (!params.isAllContactsInGroupSupportMMSMessage && this.isExtendedSmsControl) this.mmsNotValidRecipients --;
			}
		}
	}
	
	this.addRecipientsToCounter = function(number) {
		this.recipientsCounter += number;
		if (this.isExtendedSmsControl) $("#" + messageSenderData.recipientsCounter).text(this.recipientsCounter);
	}
	
	this.substractRecipientsFromCounter = function(number) {
		this.recipientsCounter -= number;
		if (this.isExtendedSmsControl) $("#" + messageSenderData.recipientsCounter).text(this.recipientsCounter);
	}
	
	function isCellularPhone(phone) {
		return typeof phone === "string"? phone.match(/^(050|052|054|057|059)/) : false;
	}
	
	//tabs methods
	
	/*****
	doSwitchTab
	tabs toggle
	*****/
	this.doSwitchTab = function(obj)
    {
        if (this._areTabsFrozen)
            return;
        var tabInd  = obj.id.substr((obj.id.length - 1), 1);
        this.doSwitchTabByInd(tabInd);
    }
    
    /*****
	doSwitchTabByInd
	makes specific tab index active
	*****/
    this.doSwitchTabByInd = function(tabInd)
    {
        
        this.doSetAllTabContentsUnvisible();
        this.doSetTargetTabActive(tabInd);
        this.doTabContentVisible(tabInd);
        this._currTabInd = tabInd;
    }
    
    /*****
	doSetAllTabContentsUnvisible
	makes all tabs content hidden
	*****/
    this.doSetAllTabContentsUnvisible = function()
    {
        var obj;
        for (var i = 1; i <= this._totalTabs; i++)
        {
            obj = eval("messageSenderData.trTab" + i);
            obj.style.display = "none";
        }
    }
    
    /*****
	doTabContentVisible
	makes specific tab index visible
	*****/
    this.doTabContentVisible = function(tabInd)
    {
        var obj = eval("messageSenderData.trTab" + tabInd);
        obj.style.display = "block";
        
        if (tabInd == 2)
        {
            //bug in IE. For some reason, the div is always floatted left although the style specifies right
            this.adjustScroll();
            if ($.browser.msie && $.browser.version.substring(0, 1) == "6")
                this.alignGalleryIconsRightWhenNoScroll();
        }
    }
    
    /*****
	doSetTargetTabActive
	makes specific tab index active
	*****/
    this.doSetTargetTabActive = function(tabInd)
    {
        var sts;
        var obj;
        for (var i = 1; i <= this._totalTabs; i++)
        {
            if (tabInd == i)
                sts = "_Selected";
            else
                sts = "_Unselected";
            
            obj = eval("messageSenderData.imgTabRight" + i);    
            obj.src = this.getTabAttributeValueByStatus(obj.src, sts);
            obj = eval("messageSenderData.tdTabDef" + i);    
            obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
            obj = eval("messageSenderData.lblTabText" + i);
            obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
            obj = eval("messageSenderData.tdBotTab" + i); 
            obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
            obj = eval("messageSenderData.imgTabLeft" + i); 
            obj.src = this.getTabAttributeValueByStatus(obj.src, sts);
        }
    }
    
    /*****
	doSetAllTabsDisabledExceptSelected
	disactivates all tabs disabled except active one
	*****/
    this.doSetAllTabsDisabledExceptSelected = function()
    {
        var sts = "_Disabled";
        var obj;
        for (var i = 1; i <= this._totalTabs; i++)
        {
            if (this._currTabInd != i)
            {
                obj = eval("messageSenderData.tdTabDef" + i);    
                obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
                obj = eval("messageSenderData.lblTabText" + i);
                obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
            }
        }
        this._areTabsFrozen = true;
    }
    
    /*****
	getTabAttributeValueByStatus
	trick to get the target tab status (among three different statuses: selected, unselected, disabled)
	*****/
    this.getTabAttributeValueByStatus = function(val, sts)
    {
        return val.replace("_Selected", sts).replace("_Unselected", sts).replace("_Disabled", sts);
    }
    
    /*****
	doUnfreezeTabs
	unfreeze all the tabs
	*****/
    this.doUnfreezeTabs = function()
    {
        var sts = "_Unselected";
        var obj;
        for (var i = 1; i <= this._totalTabs; i++)
        {
            if (this._currTabInd != i)
            {
                obj = eval("messageSenderData.tdTabDef" + i);    
                obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
                obj = eval("messageSenderData.lblTabText" + i);
                obj.className = this.getTabAttributeValueByStatus(obj.className, sts);
            }
        }
        this._areTabsFrozen = false;
    }
    
    this.initAutoComplete = function(addDefaultText) {
		this.addClickEventToMainInput();
		/*if (addDefaultText) {
			var mainInput = $(".maininput");
			mainInput.val(messageSenderData.autoCompleteDefaultText);
			mainInput.addClass("extendedACWidth");
			mainInput.blur();
		}*/
		this.bindAutoCompleteEvents();
    }
    
    this.bindAutoCompleteEvents = function() {
        var currentContext = this;
		$(".maininput").focus(
				function() {
					var el = $(this);
					if (el.val() == messageSenderData.autoCompleteDefaultText) {
						el.removeClass("extendedACWidth");
						el.val('');
					}
					currentContext.hideIconsList();
					currentContext.removeHighlightMMSPriceAndMessagesTableBackground();
					if ($.browser.mozilla)
                    {
                        $("ul.holder").css("padding-bottom", "4px");
                    }
				}
		);
		$(".maininput").blur(
			function () {
				var el = $(this);
				if (el.val() == '' && $('.holder li').length == 1) {
					el.addClass("extendedACWidth");
					el.val(messageSenderData.autoCompleteDefaultText);
				}
			}
		);
		
    }
    
    this.addClickEventToMainInput = function() {
		var currentContext = this;
		$(".maininput").focus(function () { currentContext.removeHighlightSMSPriceAndMessagesTableBackground(); } );
    }
    
    this.showUpperWarnings = function(warningMessage) {
		var tbl = $("#tblUpperWarnings");
		tbl.removeClass("displayNone");
		tbl.find("td:last").html(warningMessage);
		$(".intro").css("margin-top", "3px");
    }
    
    this.hideUpperWarnings = function() {
		var tbl = $("#tblUpperWarnings");
		tbl.addClass("displayNone");
		tbl.find("td:last").html("");
		$(".intro").css("margin-top", "14px");
    }

    /* tooltip MMS
        temporarly disabled in the ascx code for the MMS page
     */
	this.showToolTip = function()
    {
        messageSenderData.tblToolTip.style.display = "block";  
        $(messageSenderData.tblToolTip).fadeIn(300);
    }
    
    this.hideButtonToolTip = function()
    {
        var toolTip = $(messageSenderData.tblToolTip); 
        if(toolTip.css('display') != 'none')
            this.hideButtonToolTipTimeOut();
    }
    
    this.focusToolTip = function()
    {
        if(this.toolTipTimeout != null)
        {
            clearTimeout(this.toolTipTimeout);   
            this.toolTipTimeout = null; 
        }
    }

    this.hideButtonToolTipTimeOut = function()
    {
        this.toolTipTimeout = setTimeout("$('.tblToolTipDisplayNone').fadeOut(500); this.toolTipTimeout = null", 1000);
    }

    /*****
	adjustLayers
	this function is called each time the page is loaded or postback and takes care of layers positioning
	and adjustments according the different browsers
	*****/
	this.adjustLayers = function()
    {
        if($.browser.msie)
        {
            $(messageSenderData.imgWrapper).addClass("IEAdjustWrapper");
            $(".messageCount").css("width", "384px");
            $(".imgFail").css("padding-top", "2px");
            $("ul.holder li.bit-input").css("margin-right", "2px");
            //$("ul.holder li.bit-input").css("cssText", "margin-right: 2px !important;");
            if ($.browser.version.substring(0, 1) == "6")
            {
                $(messageSenderData.GalleryPrevArrow).css("left", "-12px");
                $(".facebook-auto").css("left", "1px");
            }
           if (window.location.href.indexOf("msgContacts=") > -1 || ($(".failList").css("display") == "block"))
            {
                //this fixes the defect #50503 and #51137. Do not remove the asynchroneous call.
                setTimeout("$('.fcbkcontrol_input').css('position', 'relative');$('.fcbkcontrol_input').css('left', '0px');$('.userInput').removeClass('displayNone');", 1);
                //$('.fcbkcontainer div').removeClass('.fcbkcontrol_input').addClass('.fcbkcontrol_input');
            }
            else
                $('.userInput').removeClass('displayNone');
        }
        else
        {
            var context = this;
            $(messageSenderData.message).bind('keydown',function(e) {
                window.setTimeout(messageSenderData.instanceName + ".adjustInputTextArea(61, 371)", 1);
                //context.adjustInputTextArea();
            });
            $("ul.holder").css("padding-bottom", "4px"); //if this property is changed, report the change in the bindAutoCompleteEvents function too!
            $('.userInput').removeClass('displayNone');
        }
    }

    this.fbFocus = function () {
        //$(".maininput").focus();
        $("ul.holder li.bit-input").css("margin-right", "2px");
    }

    this.adjustSMSLayers = function () {
        if ($.browser.msie) {
            window.setTimeout(messageSenderData.instanceName + ".fbFocus()", 1);
        }
        else {
            //console.log($(messageSenderData.message).attr('scrollHeight'));
            var context = this;
            $(messageSenderData.message).bind('keydown', function (e) {
                window.setTimeout(messageSenderData.instanceName + ".adjustInputTextArea(45, 166)", 1);
                //context.adjustInputTextArea();
            });
        }
        $("#default_message").css("top", "4px");
    }
    
    this.adjustInputTextArea = function(defaultH, defaultW)
    {
        //console.log($(messageSenderData.message).attr('scrollHeight'));
        if ($(messageSenderData.message).attr("scrollHeight") == ("" + defaultH))
        {
            $(messageSenderData.message).css("padding-right", "10px");
            $(messageSenderData.message).css("width", defaultW + "px");
        }
        else
        {
            $(messageSenderData.message).css("padding-right", "0px");
            $(messageSenderData.message).css("width", (defaultW + 10) + "px");
        }
    }
    
    /* tootip SMS */
    
    this.focusToolTipSmall = function(sender)
    {
        //the tooltip will pop-up only if for unregistered users
        if (messageSenderData.userName != "")
            return;
            
        if(this.toolTipTimeout != null)
        clearTimeout(this.toolTipTimeout);
        
        var toolTip = $(sender).next();
        var pos = $(sender).offset();
        var bodyDir = $("body div:first").attr("dir");
        //alert(bodyDir);
        var delta = -20;
        if (bodyDir.toLowerCase() == "ltr")
            delta = -20;
        else
            delta = $(sender).width();
            
        var isIE6 = $.browser.msie && $.browser.version.substring(0 ,1) == "6" && navigator.userAgent.toLowerCase().indexOf('trident') == -1;
            
        var deltaIE = 0;
        var deltaIE6 = 0;
        
        if (isIE6 && bodyDir.toLowerCase() == "ltr")
	        deltaIE6 = -170;
	        
	    if ($.browser.msie && bodyDir.toLowerCase() != "ltr")
	        deltaIE = -10;
	        
	    //alert("pos.left: " + pos.left + "\nbodyDir: " + bodyDir.toLowerCase() + "\nmsie: " + $.browser.msie + "\nbrowser: " + navigator.userAgent + " - ver: " + $.browser.version + "\nIs IE6?: " + isIE6  + "\ndeltaIE: " + deltaIE + "\ndeltaIE6: " + deltaIE6);
            
        var left = (pos.left + delta + deltaIE + deltaIE6 + 5) + 'px';
        var top = (pos.top) + 'px';
        
        //alert("left = " + left + " top: " + top);

        toolTip.css({
            position: 'absolute',
            zIndex: 1000,
            left: left,
            top: top
            });
                
        toolTip.fadeIn(300);
    }
    
    this.hideButtonToolTipSMS = function(sender)
    {  
        var toolTip = $(sender).children('.buttonToolTipWrapperWT');
        if(toolTip.css('display') != 'none')
            this.hideButtonToolTipTimeOutSMS();
    }

    this.hideButtonToolTipTimeOutSMS = function()
    {
        this.toolTipTimeout = setTimeout("$('.buttonToolTipWrapperWT').fadeOut(500); this.toolTipTimeout = null", 1000);
    }

    this.asyncSendMessage = function () {
        /*$(messageSenderData.btnSubmit).attr("disabled", "disabled");
        $(messageSenderData.loadingImage).css("display", "block");*/
        //alert("IsAnonymous: " + $(".chkAnonymous input").is(':checked'));
        $(messageSenderData.btnSubmit).css("display", "none");
        $(".picUploading").css("display", "block");
        this.hideSendResults();
        this.hideUpperWarnings();
        var validationResult = this.validateFormBeforeSend();
        var context = this;
        var totalRecipients = 0;
        if (messageSenderData.hidPhones.value != null)
              totalRecipients = (messageSenderData.hidPhones.value.split(",").length - 1);
        if (typeof validationResult === "boolean" && validationResult) {
            $.post(location.href, { msgTxt: messageSenderData.message.value, msgContacts: messageSenderData.hidPhones.value, action: "asyncSendMessage", isAnonymous: $(".chkAnonymous input").is(':checked') }, function (data) {
                if (typeof data.error !== "undefined") {
                    context.showUpperWarnings(data.error);
                    context.generateReportScript(totalRecipients, "ERROR: " + data.error, false); 
                } else {
                    context.showSendResults(data.successContacts, data.notSuccessContacts, data.counterMessage);
                    context.resetControls();
                }
                /*$(messageSenderData.btnSubmit).removeAttr("disabled");
                $(messageSenderData.loadingImage).css("display", "none");*/
                $(messageSenderData.btnSubmit).css("display", "block");
                $(".picUploading").css("display", "none");
            }, "json");
        } else {
            //TODO: handle validation result failure for extended sms sender?
            /*$(messageSenderData.btnSubmit).removeAttr("disabled");
            $(messageSenderData.loadingImage).css("display", "none");*/
            $(messageSenderData.btnSubmit).css("display", "block");
            $(".picUploading").css("display", "none");
        }

        return false;
    }

    this.generateReportScript = function (TotalRecipients, Status, RunUnicaOnly) {
        var uni_EventName = "SendSMS";
        var uni_MessageType = this.isSMSMessage ? "SMS" : "MMS";
        var uni_TotalRecipients = TotalRecipients;
        var uni_IsAnonymous = $(".chkAnonymous input").is(':checked');
        var uni_Status = Status;
        var IsUnicaEnabled = messageSenderData.enableUnica;
        var IsGAEnabled = messageSenderData.enableAnalytics;
        var GACode = messageSenderData.gaCode;

        if (IsUnicaEnabled != "1" && IsGAEnabled != "1")
            return;

        if (IsUnicaEnabled == "1") {
            try {
                ntptEventTag("ev=" + uni_EventName + "&MessageType=" + uni_MessageType + "&TotalRecipients=" + uni_TotalRecipients + "&IsAnonymous=" + uni_IsAnonymous + "&Status=" + uni_Status);
            }
            catch (err) {
            }
        }
        if (IsGAEnabled == "1" && !RunUnicaOnly) {
            var url = location.href;
            if (url.indexOf("?") > -1)
                url = url + "&ev=" + uni_EventName + "&MessageType=" + uni_MessageType + "&TotalRecipients=" + uni_TotalRecipients + "&IsAnonymous=" + uni_IsAnonymous + "&Status=" + uni_Status;
            else
                url = url + "?ev=" + uni_EventName + "&MessageType=" + uni_MessageType + "&TotalRecipients=" + uni_TotalRecipients + "&IsAnonymous=" + uni_IsAnonymous + "&Status=" + uni_Status;

            if (pageTracker != null) {
                try {
                    pageTracker._trackPageview(url);
                }
                catch (err) {
                }
            }
            else {
                try {
                    var pageTracker = _gat._getTracker(GACode);
                    pageTracker._setDomainName(".cellcom.co.il");
                    pageTracker._trackPageview(url);
                }
                catch (err) {
                }
            }
        }

    }
    
    this.resetControls = function() {
		$(messageSenderData.message).val("");
		$(messageSenderData.hidPhones).val("");
		$(".holder .bit-box").remove();
		
		//miki
		$(".fcbkcontrol_input .selected").removeClass("selected");
		
		this.recipients = {};
		this.updateNumberOfMessagesToSend();
		this.initAutoComplete(true);
		this.bindAutoCompleteEvents();
		//Note: this is fix for ie browsers
		if ($.browser.msie) {
			$("#" + messageSenderData.autoComplete).removeClass("pnlAutoComplete");
			$("#" + messageSenderData.autoComplete).addClass("pnlAutoComplete");
		}
    }

    this.showSendResults = function (successText, notSuccessText, counterMessage) {
        $(".pnlSendResults").removeClass("displayNone");
        $(".pnlSendResultsEnv").removeClass("displayNone");
        if (typeof successText === "string" && successText.length > 0) {
            var element = $("#pnlSendResults_SuccessContacts");
            element.html(successText);
            element.parent().css("display", "block");
            //miki
            var counter = $(".SmallMessageSenderWP .introRegular");
            counter.text(counterMessage);
            //var randomnumber=Math.floor(Math.random()*101);
            //window.location.hash = randomnumber; //for browser history
        }
        if (typeof notSuccessText === "string" && notSuccessText.length > 0) {
            var element = $("#pnlSendResults_NotSuccessContacts");
            element.html(notSuccessText);
            element.parent().css("display", "block");
            if (typeof successText !== "string" || successText.length == 0) $("#NotSuccessCloseButton").css("display", "block");
        }

        var totalRecipients = 0;
        if (messageSenderData.hidPhones.value != null)
            totalRecipients = (messageSenderData.hidPhones.value.split(",").length - 1);
        var status = "SUCCESS";
        if (typeof notSuccessText === "string" && notSuccessText.length > 0) {
            if (typeof successText === "string" && successText.length > 0)
                status = "PARTLY FAILED";
            else
                status = "FAILED";
        }
        this.generateReportScript(totalRecipients, status, false);
    }
    
    this.hideSendResults = function() {
		$(".pnlSendResults").addClass("displayNone");
		$(".pnlSendResultsEnv").addClass("displayNone");
		var element = $("#pnlSendResults_SuccessContacts");
		element.html("");
		element.parent().css("display", "none");
		element = $("#pnlSendResults_NotSuccessContacts");
		element.html("");
		element.parent().css("display", "none");
		$("#NotSuccessCloseButton").css("display", "none");
    }
    
    this.validateTalkmanCustomer = function() {
		if (jQuery.trim(messageSenderData.userName).length == 0 || !messageSenderData.isTalkmanCustomer) return true;
		var currentMessagePrice = this.getMessagePrice() * this.getNumberOfMessages(messageSenderData.message.value.length) * this.recipientsCounter;
		return messageSenderData.talkmanBalance >= currentMessagePrice;
    }
    
    this.getMessagePrice = function() {
		return this.isSMSMessage? messageSenderData.smsPrice : messageSenderData.mmsPrice;
    }
    
    this.submitButtonEvents = function(reportToAnalytics) {
		var result = this.validateFormBeforeSend();
		if (result && reportToAnalytics && typeof pageTracker !== "undefined") {
			pageTracker._trackEvent('5 free sms', 'send_sms');
		}
		return result;
	}
}

function MessageSenderData() {
	this.message;					//html textarea that contains text message
	this.numberOfMessages;			//html tag that contains number of messages to be sent
	this.icons;						//html table that contains list of icons(smiles)
	this.iconsActivator;			//html image tag that show\hide this.icons
	this.loadingImage;				//html image tag that activated on file upload
	this.uploadFileID;				//id of	<input type="file"> element
	this.userControlID;				//clientID value of user control
	this.uploadedImage;				//html image tag that contains uploaded image
	this.uploadedError;				//html div tag that contains upload file error text
	this.mmsImages;					//html div tag that contains list of mms images
	this.mmsPart;					//html div tag that contains all MMS ui
	this.mmsGallery;				//html div tag that contains mms images gallery and upload image control
	this.mmsFileToSend;				//html <input type="hidden"> tag that contains "custom" string if user uploaded his file to server or image id in case of image gallery
	this.checkedImage;				//html div tag that contains uploaded/checked mms image and link to remove it
	this.instanceName;				//instance name of current MessageSender object
	this.smsPriceAndMessages;		//html table that contains table with sms price and placeholder for error messages
	this.numberOfCharacters;		//html span tag that contains number of characters in message tag
	this.uploadImageTab;			//html tag that contains tab of upload control
	this.uploadImageTabData;		//html tag that contains data with upload control
	this.mmsImagesTab;				//html tag that contains tab of mms images gallery
	this.mmsImagesTabData;			//htmlstag that contains data with mms images gallery
	this.mmsPriceAndMessages;		//html table that contains table with mms price and placeholder for error messages
	this.messageErrors;				//html tag that contains error message of message field validation
	this.btnSubmit;					//html submit form button that sends form to server
	this.contacts;					//html tag that contains list of contacts
	this.contactsErrors;			//html tag that contains error message of contacts field validation
	this.mmsImageErrors;			//html tag that contains error message of mms image field validation
	this.maxSMSChars;				//maximum chars in sms message
	this.fileUploadUrl;				//url of file upload
	this.useSSL;					//enable/disable ssl for ajax file upload
	this.phonesList;				//hidden field that contains list of phones/groups we will send message to
	this.recipientsCounter;			//html tag that contains counter of recipients number
	this.errorMessages = {};		//object that contains list of error messages
	this.contactsErrorsText;		//html tag that used as placeholder for contacts errors
	this.autoComplete;				//html tag that contains autocomplete control
}

function changeElementBackgroundColor(htmlElement, color) {
	if (typeof htmlElement === "object") htmlElement.style.backgroundColor = color;
}

function extractCategoryIndFromID(lnkID)
{
    return lnkID.split("Cat")[1];
}

function extractCategoryIDFromAttr(attr)
{
    return attr.split('getMMSImagesFromServer("')[1].split('")')[0];
}

function toggleImage(obj, mode)
{
    if (mode == "on")
        $($(obj).find("img")[0]).attr("src", $($(obj).find("img")[0]).attr("src").replace("_off", "_" + mode));
    else
        $($(obj).find("img")[0]).attr("src", $($(obj).find("img")[0]).attr("src").replace("_on", "_" + mode));
}

function clearAnonymousCheckbox() {
    $('.chkAnonymous input').attr('checked', false);
}
