
// funckija proverava da li je polje u formi prazno
function emptyValidation(field, msg) {
		if ((field.value==null) || (field.value=="")) {
			alert(msg);
			return false;
		} else {
			return true;
		}
}

// Changes:  Sandeep V. Tamhankar (stamhankar@hotmail.com)
/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  */
// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com 
function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */
	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		alert("Email adresa je neispravna")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    alert("Email adresa je neispravna")
	    return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Email adresa je neispravna")
			return false
		    }
	    }
	    return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Email adresa je neispravna")
	    return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>4) {
	   // the address must end in a two, three or four letter word.
	   alert("Email adresa je neispravna")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="Email adresa je neispravna"
	   alert(errStr)
	   return false
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

// funkcija broji i ogranicava broj karaktera u textarea tagu
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // ako je tekst suvise dugacak, skrati ga
		field.value = field.value.substring(0, maxlimit);
	// inace, apdejtuj brojac preostalih znakova
	else
		//countfield.value = maxlimit - field.value.length;
		countfield.innerHTML = maxlimit - field.value.length;
}


// funkcija brise textarea i resetuje broj preostalih karaktera 
function resetTextCounter(field, countfield, maxlimit) {
	field.value = '';
	countfield.innerHTML = maxlimit;
	field.focus();
}

// postavlja status true/false svim checkboxovima
function setAllCheckBoxes(FormName, FieldName, CheckValue) {
	
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

// funkcija prikazuje zadati DIV
function showDiv(div_id) {
	document.getElementById(div_id).style.display='block';
}

// funkcija sakriva zadati DIV
function hideDiv(div_id) {
	document.getElementById(div_id).style.display='none';
}

// proverava da li su popunjeta sva polja u formi
function validateAddGroup(form) {
	
	with (form) {		
		if (emptyValidation(naziv,'Morate uneti naziv grupe') == false) {naziv.focus(); return false;}
		if (emptyValidation(opis,'Morate uneti opis grupe') == false) {opis.focus(); return false;}
	}
}

// proverava da li su popunjeta sva polja u formi
function validateAddContact(form) {
	
	with (form) {		
		if (emptyValidation(kontakt_tel,'Morate uneti broj mobilnog telefona') == false) {kontakt_tel.focus(); return false;}
		if (checkMobilePhone(kontakt_tel.value,'Neispravan format broja mobilnog telefona.') == false) {kontakt_tel.focus(); return false;}
		//if (emptyValidation(kontakt_naziv,'Morate uneti naziv kontakta') == false) {kontakt_naziv.focus(); return false;}
	}
}

// provera da li su pravilno popunjena polja u formi
function validateChangeData(form) {
	
	with (form) {
		if (emptyValidation(client_old_pass,'Morate uneti trenutnu šifru') == false) {client_old_pass.focus(); return false;}
		if (emailCheck(client_email.value)==false) {client_email.focus(); return false;}
		if (client_new_pass.value != "") {if (client_new_pass.value != client_new_pass2.value) {alert('Nova šifra i potvrda nove šifre se ne slažu'); return false;}}
		
	}
}

// proverava da tekst u poruci ne sadrzi zabranjene znakove (nasa slova pre svega)
function checkSmsMessage(teststr,msg) {
	// Poruka moze da sadrzi sve znakove osim nasih slova (latinice sa kvakama i cirilice) - uzasno je, znam :-)
	var regex_test = /^[A-Za-z0-9 \s-_\+\\\/\{\}\(\)\[\]\=\!\@\#\$\%\^\&\*\~\`\"\'\:\;\.\,\<\>\?\|]+$/
	
	if (teststr.search(regex_test) == -1) {
		alert(msg);
		return false;
	} else {
		return true;
	}	
}

// proverava formu za slanje SMS-a na grupe
function validateSendSms(form) {
		
	with(form) {		
		if (emptyValidation(sms_poruka,'Poruka je prazna') == false) {sms_poruka.focus();return false;}	
		if (checkSmsMessage(sms_poruka.value,'Poruka sadrži nedozvoljene znakove. SMS poruka ne sme sadržati naša slova.') == false) {sms_poruka.focus(); return false;}
		
		if (vreme_slanja[1].checked == true) { // Ako je chekirano da se sms salje kasnije, mora biti odabran datum slanja
			if (emptyValidation(sms_datum,'Morate odabrati datum slanja') == false) {return false;}	
		}
	}
	
	var j=0;
	var k=0;
	for (var i = 0; i < document.getElementsByName('groups[]').length; i++) {

		if (document.getElementsByName('groups[]')[i].checked == true) {
			j++;
			k = k + parseInt(document.getElementsByName('group_contacts[]')[i].value,10);
		}
	}
	if (j == 0) {alert('Morate odabrati bar jednu grupu za slanje SMS-a'); return false;}
	if (k > document.sms_form['kredit'].value) {alert('Nemate dovoljno kredita'); return false;}
	
	return confirm('Poslaćete SMS na selektovane grupe');
}

// proverava formu za slanje SMS-a na pojedince
function validateSendSmsSingle(form) {
		
	with(form) {		
		if (emptyValidation(sms_poruka,'Poruka je prazna') == false) {sms_poruka.focus();return false;}	
		if (checkSmsMessage(sms_poruka.value,'Poruka sadrži nedozvoljene znakove. SMS poruka ne sme sadržati naša slova.') == false) {sms_poruka.focus(); return false;}
		
		if (vreme_slanja[1].checked == true) { // Ako je chekirano da se sms salje kasnije, mora biti odabran datum slanja
			if (emptyValidation(sms_datum,'Morate odabrati datum slanja') == false) {return false;}	
		}
	}
	
	var j=0;
	for (var i = 0; i < document.getElementsByName('contacts[]').length; i++) {
		if (document.getElementsByName('contacts[]')[i].checked == true) {
			j++;
		}
	}
	if (j == 0) {alert('Morate odabrati bar jedan kontakt za slanje SMS-a'); return false;}
	if (j > document.sms_single_form['kredit'].value) {alert('Nemate dovoljno kredita'); return false;}
	
	return confirm('Poslaćete SMS selektovanim kontaktima');
}

// funkcija proverava da li je ispravan format broja mobilnog telefona 
function checkMobilePhone(phone_number, msg) {
	// broj mora pocinjati sa 6 (381 se dodaje kasnije na pocetak broja)
	var regex_phone = /^6\d{6,10}$/
	
	if (phone_number.search(regex_phone) == -1) {
		alert(msg);
		return false;
	} else {
		return true;
	}
	
}

// Sabmituje zadatu formu
function submitForm(form, msg) {
	
	var answer = confirm(msg);
	
	if (answer) {	
		with (form) {	
			switch(name) {
				case "groups_form":	
					action = "del_group.php";
					break;
				case "contacts_form":	
					action = "del_contact.php";
					break;
				case "sms_form":
					action = "send_sms.php";
					break;
				case "bulk_form":
					action = "del_outbox.php";
					break;	
				case "target_form":
					action = "del_target.php";
					break;		
				default:	
					action = "";
					break;
			}

			submit(); // submit form
		}
		return true;
	} else {
		return false;
	}
}

function showPopupWindow() {
	
	var arrayPageSize = getPageSize();

	document.getElementById('div_adduserbg_holder').style.width = arrayPageSize[0]+"px";
	document.getElementById('div_adduserbg_holder').style.height = arrayPageSize[1]+"px";
			
	showDiv('div_adduserbg_holder');
	showDiv('div_adduserbg');
}

function hidePopupWindow() {
	
	hideDiv('div_adduserbg');
	hideDiv('div_adduserbg_holder');
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function loadContactsList(txt, xml) {
   document.getElementById("adr_contacts_list").innerHTML = txt;
}

function getContacts(group, name) {
	document.getElementById("group_name_display").innerHTML = name;
	AjaxFunction("get_contacts.php", "group="+escape(group), loadContactsList);
}

function loadOutboxTargetList(txt, xml) {
   document.getElementById("outbox_target_list").innerHTML = txt;
}

function getOutboxTarget(bulk) {
	AjaxFunction("get_outbox_target.php", "bulk="+escape(bulk), loadOutboxTargetList);
}

function loadExportFile(txt, xml) {
   document.getElementById("adr_contacts_list").innerHTML = txt;
}

function exportContacts(FormName, FieldName) {
	if(!document.forms[FormName])
		return;	
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;		
	var checkedText = '';		
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes) {
		checkedText = checkedText+'contacts['+objCheckBoxes.value+']='+objCheckBoxes.checked+'&';
	} else {
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++) {
			checkedText = checkedText+'contacts['+objCheckBoxes[i].value+']='+objCheckBoxes[i].checked+'&';
		}
	}
	window.open("export_contact.php?"+checkedText+'l=1','izvoz','status=0,width=200,height=200');	
	// AjaxFunction("export_contact.php", checkedText, loadExportFile);
}

function exportGroups(FormName, FieldName) {
	if(!document.forms[FormName])
		return;	
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;		
	var checkedText = '';		
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes) {
		checkedText = checkedText+'groups['+objCheckBoxes.value+']='+objCheckBoxes.checked+'&';
	} else {
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++) {
			checkedText = checkedText+'groups['+objCheckBoxes[i].value+']='+objCheckBoxes[i].checked+'&';
		}
	}
	window.open("export_group.php?"+checkedText+'l=1','izvoz','status=0,width=200,height=200');	
}

// Glavna AJAX funkcija
var AjaxFunction = function() 
{
   // Returns an XMLHttpRequest Object (or error)
   var getHTTPHandler = function()
   {
      var xmlHttp;
      try
      {
         xmlHttp = new XMLHttpRequest;
         getHTTPHandler = function()
         {
           return new XMLHttpRequest;
         };
      }
      catch(e)
      {
         var msxml = ["MSXML2.XMLHTTP.3.0",
                      "MSXML2.XMLHTTP",
                      "Microsoft.XMLHTTP"];

         for (var i=0, len = msxml.length; i < len; ++i)
         {
            try
            {
               xmlHttp = new ActiveXObject(msxml[i]);
               getHTTPHandler = function()
               {
                  return new ActiveXObject(msxml[i]);
               };

               break;
            }
            catch(e)
            {
               alert('ERROR: AJAX not supported...');
            }
         }
      }
      return xmlHttp;
   };

   // Start communication using AJAX
   return function(file, params, cFunction)
   {
      var onReadyStateChange = function(xmlHttp)
      {
         if (xmlHttp.readyState == 4)
         {
            if(xmlHttp.status == 200 && xmlHttp.statusText.substring(0,2) == "OK")
               return onComplete(xmlHttp.responseText, xmlHttp.responseXML);
            
            if (xmlHttp.status == 0)
               return alert("AjaxFunction Warning: xmlHttp status is '0'");

            return alert("AjaxFunction Warning: xmlHttp status is '" + xmlHttp.status + "'");
         }
         
         return true;
      };

      var xmlHttp = getHTTPHandler();
      if (xmlHttp)
      {
         var onComplete = cFunction;

         // Check if we are ready to do a new request
         if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
         {
            xmlHttp.open('POST', file, true);
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            xmlHttp.onreadystatechange = function()
            {
               onReadyStateChange(xmlHttp);
            };

            xmlHttp.send(params);
         }
      }
   };
}();
