/***********************************************
* Scripting for popup
************************************************/

  function launchPopup(url, name, width, height, resizable, scrollbars, toolbar, location) {
    popup_window = window.open(url, "name", 'width='+width+',height='+height+',resizable='+resizable+',scrollbars='+scrollbars+',toolbar='+toolbar+',location='+location+'');
    popup_window.focus;
  }


/***********************************************
* Scripting for search
************************************************/

  function findArticles() {

	  searchKeyword = trim(document.headerSearchForm['eceExpr'].value);
	  if (document.headerSearchForm['eceExpr'].value == 'Search') {
		  document.headerSearchForm['eceExpr'].value = '';
		  document.headerSearchForm['eceMode'].value = '';
	  }
	  if (searchKeyword == '' || searchKeyword == '*') {
		  document.headerSearchForm.submit();
		  return true;
	  } else
	  if (checkSearchQuery(searchKeyword)) {
		  return true;
	  } else {
		  alert('Please enter a valid search query.');
		  return false;
	  }
  }

  function findArticlesRefineSearch(modus) {

	  refinement = trim(document.normalSearchForm['eceExpr'].value);
	  if (refinement == '' || refinement == '*' || !checkSearchQuery(refinement)) {
	  	if(modus=='refine') {
			alert('Please enter a valid refinement.');
		} else {
			alert('Please enter a valid search query.');
		}
		document.normalSearchForm['eceExpr'].focus();
		document.normalSearchForm['eceExpr'].value = "";
		return false;
	  } else {
	  	/* if(document.normalSearchForm['eceExpr'].value) {
		  	if(refinement.charAt(0) == '+' || refinement.charAt(0) == '-') {
		  		document.normalSearchForm['eceExpr'].value += " " + refinement;
		  	} else {
		  		document.normalSearchForm['eceExpr'].value += " +" + refinement;
			}		  		
		} else { */
		  	document.normalSearchForm['eceExpr'].value = refinement;
		//}
		document.normalSearchForm.action="/search/index.jsp";
		document.normalSearchForm.submit();
		return true;
	  }
  }

  function validateNewSearchBottom() {

	  searchQuery = trim(document.newSearchBottom['eceExpr'].value);

	  if (searchQuery == '' || searchQuery == '*' || !checkSearchQuery(searchQuery)) {
		  alert('Please enter a valid search query.');
		  document.newSearchBottom['eceExpr'].focus();
		  document.newSearchBottom['eceExpr'].value = "";
		  return false;
	  }

	  if (document.newSearchBottom['dateRange'][2].checked) {
		  fromDay = trim(document.newSearchBottom['last30daysFromDay'].value);
		  fromMonth = trim(document.newSearchBottom['last30daysFromMonth'].value);
		  fromYear = trim(document.newSearchBottom['last30daysFromYear'].value);
		  toDay = trim(document.newSearchBottom['todayToDay'].value);
		  toMonth = trim(document.newSearchBottom['todayToMonth'].value);
		  toYear = trim(document.newSearchBottom['todayToYear'].value);
	  }

	  if (document.newSearchBottom['dateRange'][1].checked) {
		  fromDay = trim(document.newSearchBottom['last7daysFromDay'].value);
		  fromMonth = trim(document.newSearchBottom['last7daysFromMonth'].value);
		  fromYear = trim(document.newSearchBottom['last7daysFromYear'].value);
		  toDay = trim(document.newSearchBottom['todayToDay'].value);
		  toMonth = trim(document.newSearchBottom['todayToMonth'].value);
		  toYear = trim(document.newSearchBottom['todayToYear'].value);
	  }

	  if (document.newSearchBottom['dateRange'][0].checked) {
		  fromDay = trim(document.newSearchBottom['todayToDay'].value);
		  fromMonth = trim(document.newSearchBottom['todayToMonth'].value);
		  fromYear = trim(document.newSearchBottom['todayToYear'].value);
		  toDay = trim(document.newSearchBottom['todayToDay'].value);
		  toMonth = trim(document.newSearchBottom['todayToMonth'].value);
		  toYear = trim(document.newSearchBottom['todayToYear'].value);
	  }

	  if (fromDay != '' &&  fromMonth != '' && fromYear != '') {
		  document.newSearchBottom['eceFromDay'].value = fromDay;
		  document.newSearchBottom['eceFromMonth'].value = fromMonth;
		  document.newSearchBottom['eceFromYear'].value = fromYear;
		  document.newSearchBottom['eceFromDate'].value = "true";
	  }
	  if (toDay != '' && toMonth != '' && toYear != '') {
		  document.newSearchBottom['eceToDay'].value = toDay;
		  document.newSearchBottom['eceToMonth'].value = toMonth;
		  document.newSearchBottom['eceToYear'].value = toYear;
		  document.newSearchBottom['eceToDate'].value = "true";
	  }
	  if (document.newSearchBottom['dateRange'][0].checked ||
		  document.newSearchBottom['dateRange'][1].checked ||
		  document.newSearchBottom['dateRange'][2].checked) {

		  document.newSearchBottom.submit();
		  return true;

	  }
	  else
	  {
		  return false;
	  }
  }

  function validateAdvancedSearch(modus) {
		
	  searchQuery = trim(document.advancedsearch['refineExpr'].value);

	  if (searchQuery == '' || searchQuery == '*' || !checkSearchQuery(searchQuery)) {
		if(modus=='refine') {
			alert('Please enter a valid refinement.');
		} else {
			alert('Please enter a valid search query.');
		}
		
		document.advancedsearch['refineExpr'].focus();
		document.advancedsearch['refineExpr'].value = "";
		return false;
	  }
	  if(modus=='refine') {
	  	if(searchQuery.charAt(0) == '+' || searchQuery.charAt(0) == '-') {
	      		document.advancedsearch['eceExpr'].value += " " + document.advancedsearch['refineExpr'].value;
	  	} else {
	  		document.advancedsearch['eceExpr'].value += " +" + document.advancedsearch['refineExpr'].value;
	  	}
	  } else {
	  	document.advancedsearch['eceExpr'].value = document.advancedsearch['refineExpr'].value;
	  }	  

	if (document.advancedsearch['dateRange'][4].checked) {
		fromDay = trim(document.advancedsearch['fromDay'].value);
		fromMonth = trim(document.advancedsearch['fromMonth'].value);
		fromYear = trim(document.advancedsearch['fromYear'].value);
		toDay = trim(document.advancedsearch['toDay'].value);
		toMonth = trim(document.advancedsearch['toMonth'].value);
		toYear = trim(document.advancedsearch['toYear'].value);
		isValid = checkDate(fromMonth, fromDay, fromYear, toMonth, toDay, toYear);
	  }
	  
	  if (document.advancedsearch['dateRange'][3].checked) {
		  fromDay = trim(document.advancedsearch['allFromDay'].value);
		  fromMonth = trim(document.advancedsearch['allFromMonth'].value);
		  fromYear = trim(document.advancedsearch['allFromYear'].value);
		  toDay = trim(document.advancedsearch['todayToDay'].value);
		  toMonth = trim(document.advancedsearch['todayToMonth'].value);
		  toYear = trim(document.advancedsearch['todayToYear'].value);
	  }

	  if (document.advancedsearch['dateRange'][2].checked) {
		  fromDay = trim(document.advancedsearch['last30daysFromDay'].value);
		  fromMonth = trim(document.advancedsearch['last30daysFromMonth'].value);
		  fromYear = trim(document.advancedsearch['last30daysFromYear'].value);
		  toDay = trim(document.advancedsearch['todayToDay'].value);
		  toMonth = trim(document.advancedsearch['todayToMonth'].value);
		  toYear = trim(document.advancedsearch['todayToYear'].value);
	  }

	  if (document.advancedsearch['dateRange'][1].checked) {
		  fromDay = trim(document.advancedsearch['last7daysFromDay'].value);
		  fromMonth = trim(document.advancedsearch['last7daysFromMonth'].value);
		  fromYear = trim(document.advancedsearch['last7daysFromYear'].value);
		  toDay = trim(document.advancedsearch['todayToDay'].value);
		  toMonth = trim(document.advancedsearch['todayToMonth'].value);
		  toYear = trim(document.advancedsearch['todayToYear'].value);
	  }

	  if (document.advancedsearch['dateRange'][0].checked) {
		  fromDay = trim(document.advancedsearch['todayFromDay'].value);
		  fromMonth = trim(document.advancedsearch['todayFromMonth'].value);
		  fromYear = trim(document.advancedsearch['todayFromYear'].value);
		  toDay = trim(document.advancedsearch['todayToDay'].value);
		  toMonth = trim(document.advancedsearch['todayToMonth'].value);
		  toYear = trim(document.advancedsearch['todayToYear'].value);
	  }

	  if (fromDay != '' &&  fromMonth != '' && fromYear != '') {
		  document.advancedsearch['eceFromDay'].value = fromDay;
		  document.advancedsearch['eceFromMonth'].value = fromMonth;
		  document.advancedsearch['eceFromYear'].value = fromYear;
		  document.advancedsearch['eceFromDate'].value = "true";
	  }
	  if (toDay != '' && toMonth != '' && toYear != '') {
		  document.advancedsearch['eceToDay'].value = toDay;
		  document.advancedsearch['eceToMonth'].value = toMonth;
		  document.advancedsearch['eceToYear'].value = toYear;
		  document.advancedsearch['eceToDate'].value = "true";
	  }
	  if (document.advancedsearch['dateRange'][0].checked ||
		  document.advancedsearch['dateRange'][1].checked ||
		  document.advancedsearch['dateRange'][2].checked ||
		  document.advancedsearch['dateRange'][3].checked ||
		  (document.advancedsearch['dateRange'][4].checked && isValid)) {

		  document.advancedsearch.submit();
		  return true;

	  }
	  else
	  {
		  return false;
	  }
  }

  function checkDate(fMonth, fDay, fYear, tMonth, tDay, tYear) {
	  if(!(fMonth && fDay && fYear && tMonth && tDay && tYear)) {
		  alert( 'Please specify all parts of the from and to-date.' );
		  return false;
	  }
	  var fromDate = new Date();
	  fromDate.setFullYear(fYear, fMonth, fDay );
	  var toDate = new Date();
	  toDate.setFullYear(tYear, tMonth, tDay );

	  if (fromDate.getTime() > toDate.getTime() ) {
		alert( 'Please specify the From-date before the To-date.' );
		return false;
	  } else {
	  return true;
	  }
  }

  function trim(sString) {
	  while (sString.substring(0, 1) == ' ') {
		  sString = sString.substring(1, sString.length);
	  }
	  while (sString.substring(sString.length - 1, sString.length) == ' ') {
		  sString = sString.substring(0, sString.length - 1);
	  }
	  return sString;
  }

  function checkSearchQuery(string) {

	  return string.search(/[\|&;\$%@<>\(\)\n\r,\\]/) == -1;
  }


/***********************************************
* Scripting for poll
************************************************/

  /**
    * Shows a element
    */
  function show(pElementName, pDisplay) {
    //alert('show(' + pElementName + ', '+ pDisplay + ')');
    var voted = document.getElementById(pElementName);
    voted.style.display = pDisplay;
  }
  
  /**
    * Hides an element
    */
  function hide(pElementName) {
    //alert('hide(' + pElementName + ')');
    var voted = document.getElementById(pElementName);
    voted.style.display = "none";
  }
  
  /**
    * Changes two element at once, switching states between them.
    */
  function change(pHideElementName, pShowElementName) {
    //alert('change(' + pHideElementName + ', '+ pShowElementName + ')');
    hide(pHideElementName);
    show(pShowElementName, 'block');
  }

  /**
    * Checkes state
    */
  function mentometerState(pollId) {
    //alert('mentometerState(' + pollId + ')');
    var cookies = document.cookie;
    var pos = cookies.indexOf('mentometer=');
    if (pos != -1) {
      var start = pos + 11;
      var end = cookies.indexOf(';', start);
      if (end == -1) {
        end = cookies.length;
      }
      var value = cookies.substring(start, end);
      value = unescape(value);
      var mentometerIds = value.split('M');
      for (var i = 0; i < mentometerIds.length; i++) {
        if (mentometerIds[i] == pollId) {
          change('vote-' + pollId, 'voted-' + pollId);
          return;
        }
      }
      change('voted-' + pollId, 'vote-' + pollId);
    }
    else {
      change('voted-' + pollId, 'vote-' + pollId);
    }
  }

  /**
    * Calculates the size of one individual width
    */
  function size(pTotalVotes, pVotes, pSize) {
    return Math.round((pSize * percent(pTotalVotes, pVotes)) / 100);
  }
  
  /**
    * Calculates the percentage value of a set
    * of votes represents...
    */
  function percent(pTotalVotes, pVotes) {
    var result = 0;
    if (pTotalVotes > 0) {
      result = (pVotes * 100) / pTotalVotes;
    }
    return Math.round(result);
  }
  
  /**
    * Read's a cookie
    */
  function readCookie(pCookieName) {
    var cookieName = pCookieName + '='
    var cookies = document.cookie;
    var pos = cookies.indexOf(cookieName);
    if (pos != -1) {
      var start = pos + cookieName.length;
      var end = cookies.indexOf(';', start);
      if (end == -1) {
        end = cookies.length;
      }
      return unescape(cookies.substring(start, end));
    }
  }
  /**
    * Set a cookie
    */
	function setCookie(pName, pValue, expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate() + expiredays)
	document.cookie = pName + '=' + escape(pValue) +
	((expiredays==null) ? "" : ";expires=" + exdate)
  }
  function getCookie(c_name){
			if (document.cookie.length>0){
				c_start=document.cookie.indexOf(c_name + "=")
				if (c_start!=-1){ 
					c_start=c_start + c_name.length+1 
					c_end=document.cookie.indexOf(";",c_start)
					if (c_end==-1) c_end=document.cookie.length
						return unescape(document.cookie.substring(c_start,c_end))
				}
			}
			return null
		}
  
  /**
    * Reads one individual poll cookie
    */
  function readPollCookie(pollId) {
    var pollCookie = readCookie('pollCache');
    if (pollCookie == null) {
      return null;
    }
    var pollCacheCookies = pollCookie.split(';');
    for (var i = 0; i < pollCacheCookies.length; i++) {
      var pollCookie = pollCacheCookies[i];
      if (pollCookie.indexOf(pollId) != -1) {
        return pollCookie;
      }
    }
  }
  
  /**
    * An array of poll cookie id's
    */
  function readPollCookieIds() {
    var pollCookie = readCookie('pollCache');
    if (pollCookie == null) {
      return null;
    }
    var pollCacheCookies = pollCookie.split(';');
    var result = new Array(pollCacheCookies.length);
    for (var i = 0; i < pollCacheCookies.length; i++) {
      var hepp = pollCacheCookies[i].split(':')
      result[i] = hepp[0];
    }
    return result;
  }
  
  /**
    * Set's a poll cookie
    */
  function setPollCookie(pollId, vote) {
    var values = '';
    var pollCookieIds = readPollCookieIds();
    if (pollCookieIds != null) {
      for (var i = 0; i < pollCookieIds.length; i++) {
        values += readPollCookie(pollCookieIds[i]) + ';';
      }
    }
    values += 'pollId-' + pollId + ':' + timestamp + ':' + vote;
    //alert(values);
    setCookie('pollCache', values);
  }

/***********************************************
* Scripting for upload your photo
************************************************/
function checkrequired(which)
{
	var pass=true;
	if (document.images)
	{
		for (i=0;i<which.length;i++)
		{
			var tempobj=which.elements[i];
			if(tempobj.id.indexOf("required")>-1 )
			{
				if (((tempobj.type=="text" ||tempobj.type=="textarea" || tempobj.type == "file") &&
					tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s" && tempobj.selectedIndex==0))
				{ 
					pass=false;
					break;
				}
	        }
	    }
	}
	if (!pass)
	{
		
		alert("The field "+tempobj.name+" is required.");
		setTimeout("focusElement('serviceform', '" + tempobj.id + "')", 0);
		return false;
	}
	else
	{
		return true;
	}
}

function checkValidDates(which)
{
	var pass=true;
	if (document.images)
	{
		for (i=0;i<which.length;i++)
		{
			var tempobj=which.elements[i];
			if(tempobj.id.indexOf("validate")>-1 )
			{
				if (tempobj.type=="text" && !checkDate1(tempobj))
				{ 
					pass=false;
					setTimeout("focusElement('serviceform', '" + tempobj.name + "')", 0);
					break;
				}
	        }
	    }
	}
	return pass;
	
}

function checkDate1(fld) {
    var mo, day, yr;
    var entry = fld.value;
    var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
    var valid = (reLong.test(entry)) || (reShort.test(entry));
    if (valid) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        day = parseInt(entry.substring(0, delim1), 10);
        mo = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = parseInt(entry.substring(delim2+1), 10);
        // handle two-digit year
        if (yr < 100) {
            var today = new Date();
            // get current century floor (e.g., 2000)
            var currCent = parseInt(today.getFullYear() / 100) * 100;
            // two digits up to this year + 15 expands to current century
            var threshold = (today.getFullYear() + 15) - currCent;
            if (yr > threshold) {
                yr += currCent - 100;
            } else {
                yr += currCent;
            }
        }
        var testDate = new Date(yr, mo-1, day);
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    // fill field with database-friendly format
                    if (mo <= 9) 
                    {
                    	moStr = "0" + mo;
                    }
                    else
                    {
                    	moStr = mo;
                    }
                    if (day <= 9) 
                    {
                    	dayStr = "0" + day;
                    }
                    else
                    {
                    	dayStr = day;
                    }
                    fld.value = dayStr + "/" + moStr + "/" + yr;
                    return true;
                } else {
                    alert("There is a problem with the year entry.");
                }
            } else {
                alert("There is a problem with the month entry.");
            }
        } else {
            alert("There is a problem with the date entry.");
        }
    } else {
        alert("Incorrect date format. Enter as dd/mm/yyyy.");
    }
    return false;
}

function checkValidEmail(which)
{
	var pass=true;
	if (document.images)
	{
		for (i=0;i<which.length;i++)
		{
			var tempobj=which.elements[i];
			if(tempobj.id.indexOf("valiemail")>-1 )
			{
				if (tempobj.type=="text" && !checkEmail(tempobj))
				{ 
					pass=false;
					break;
				}
	        }
	    }
	}
	return pass;
	
}

function checkEmail(elem)
{
	var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        alert("Verify the e-mail address format.");
        setTimeout("focusElement('serviceform', '" + elem.name + "')", 0);
        return false;
    } else {
        return true;
    }
}

function checkValidFile(which)
{
	var pass=true;
	if (document.images)
	{
		for (i=0;i<which.length;i++)
		{
			var tempobj=which.elements[i];
			if(tempobj.id.indexOf("valifile")>-1 )
			{
				if (tempobj.type=="file" && !checkFile(tempobj))
				{ 
					pass=false;
					break;
				}
	        }
	    }
	}
	return pass;
	
}

function checkFile(elem)
{
	var fld = elem.value.toLowerCase();
	var re = /(\.png|\.gif|\.jpg|\.jpeg)$/;
	if(!fld.match(re))
	{
		alert("Invalid image file type.\n\rOnly .jpg, .jpeg, .gif and .png are allowed.");
		setTimeout("focusElement('serviceform', '" + elem.name + "')", 0);
		return false;
	}
	return true;
}

function checkValidLength(which, maxLengthText, maxLengthTextarea)
{
	var pass=true;
	if (document.images)
	{
		for (i=0;i<which.length;i++)
		{
			var tempobj=which.elements[i];
			if(tempobj.id.indexOf("valilength")>-1 )
			{
				if (tempobj.type=="text" && !checkLength(tempobj, maxLengthText))
				{ 
					pass=false;
					break;
				}
				if (tempobj.type=="textarea" && !checkLength(tempobj, maxLengthTextarea))
				{ 
					pass=false;
					break;
				}
	        }
	    }
	}
	return pass;
	
}

function checkLength(elem, maxLengthAllowed)
{
	var fieldLength = elem.value.length;
	if(fieldLength > maxLengthAllowed)
	{
		alert("Maximum length ("+maxLengthAllowed+") of field " + elem.name + " exceeded.");
		setTimeout("focusElement('serviceform', '" + elem.name + "')", 0);
		return false;
	}
	return true;
}

function focusElement(formName, elemName) {
    var elem = document.forms[formName].elements[elemName];
    elem.focus();
    elem.select();
}



/**
 * Check valid Phone number
 */

function checkValidPhone(which) {
	var pass=true;
	if (document.images) { 	    
		// Select the phone field
		for (i=0; i<which.elements.length; i++) {
			var tempobj = which.elements[i];
			if(tempobj.id.indexOf("valiphone") > -1 ) {
				var strippedNumber = tempobj.value.replace(/[\(\)\.\-\ ]/g, '');				
				// Check the actual characters
				if (!checkPhoneCharacters(strippedNumber)) {
					alert("The phone number can only contain numbers. \nMake sure you include an area code.");
					setTimeout("focusElement('serviceform', '" + tempobj.name + "')", 0);
					pass=false;
					break;
				}
				// Check the length
				if(strippedNumber.length != 10){
					alert("The phone number is the wrong length.\n Make sure you include an area code.");
					setTimeout("focusElement('serviceform', '" + tempobj.name + "')", 0);
					pass=false;
					break;
				}
				
				
	        }
	    }
	}
	return pass;
}

function checkPhoneCharacters(strippedNumber) {
    var validCharacters = "0123456789";
    var isNumber=true;
    var character;
    for (i = 0; i < strippedNumber.length; i++) {
        character = strippedNumber.charAt(i);
        if (validCharacters.indexOf(character) == -1) {
            return false;
        }
    }
    return true;
}






