jQuery.fn.exists = function(){return jQuery(this).length>0;}


var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }


function dettaglio(url,id)
{
	window.open(url,'dettaglio'+id,'width=750,height=520,scrollbars=yes');
}

function nuovoCv(url,id)
{
	window.open(url,'cv'+id,'width=750,height=600,scrollbars=yes');
}

function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

function selectAll(field, n){
for(i=1; i<=n; i++){
	  fieldTemp = document.getElementById(field+i);
	  fieldTemp.checked=1;
   }
}

function deselectAll(field, n){
for(i=1; i<=n; i++){
	  fieldTemp = document.getElementById(field+i);
	  fieldTemp.checked=0;
   }
}

function invertSelect(field, n){
for(i=1; i<=n; i++)
  {
		fieldTemp = document.getElementById(field+i);
		if(fieldTemp.checked==0)
		{
			fieldTemp.checked=1;
		}
		else
		{
			fieldTemp.checked=0;
		}
  }
}

function one2two() {
    m1len = m1.length ;
    for ( i=0; i<m1len ; i++){
        if (m1.options[i].selected == true ) {
            m2len = m2.length;
            m2.options[m2len]= new Option(m1.options[i].text,m1.options[i].value);
        }
    }

    for ( i = (m1len -1); i>=0; i--){
        if (m1.options[i].selected == true ) {
            m1.options[i] = null;
        }
    }
}

function two2one() {
    m2len = m2.length ;
        for ( i=0; i<m2len ; i++){
            if (m2.options[i].selected == true ) {
                m1len = m1.length;
                m1.options[m1len]= new Option(m2.options[i].text,m2.options[i].value);
            }
        }
        for ( i=(m2len-1); i>=0; i--) {
            if (m2.options[i].selected == true ) {
                m2.options[i] = null;
            }
        }
}

function moveOptionsUp(selectId) {
 var selectList = document.getElementById(selectId);
 var selectOptions = selectList.getElementsByTagName('option');
 for (var i = 1; i < selectOptions.length; i++) {
  var opt = selectOptions[i];
  if (opt.selected) {
   selectList.removeChild(opt);
   selectList.insertBefore(opt, selectOptions[i - 1]);
     }
    }
}

function moveOptionsDown(selectId) {
 var selectList = document.getElementById(selectId);
 var selectOptions = selectList.getElementsByTagName('option');
 for (var i = selectOptions.length - 2; i >= 0; i--) {
  var opt = selectOptions[i];
  if (opt.selected) {
   var nextOpt = selectOptions[i + 1];
   opt = selectList.removeChild(opt);
   nextOpt = selectList.replaceChild(opt, nextOpt);
   selectList.insertBefore(nextOpt, opt);
     }
    }
}








function in_array(the_needle, the_haystack){
	 //alert(the_haystack.length)
	 // alert(the_haystack)
	 matched = false
	 for(c=0; c<=the_haystack.length; c++){
	 	  if(the_needle == the_haystack[c])
	 	  {
	 	  	matched = true
	 	  }
	 }
   return matched;
} 

$(document).ready(function() {
	  $(document).pngFix(); 
	  $("#menuLeft ul>li>ul>li:last-child").css('cssText', 'background: none !important');
	  $("#menuLeft ul>li>ul>liul>li:last-child").css('cssText', 'background: none !important');
	  
	  renderTitles();
	  //loadInfoUtente();
	  
	  //alert($('#certificati').html())
		//renderMenu("");
		//renderMenu2Liv()
		//renderTitles("");


})



function renderMenu() {
   $("#menuTop a").each(function(i) {
      var item_title  = $(this).text();
      //alert(item_title+" "+$(this).attr('id'))
      if (item_title != '') {
       	      
  	      
          var item_label  = escape($(this).text());
          var item_id     = $(this).attr('id');
          var status      = $(this).attr('class');
          var width       = $(this).attr('width');
          var height      = $(this).attr('height');
          //alert(height)
          var img_tag = "<img id=\""+item_id+"\" src=\""+wwwRoot+"/"+wwwLang+"/img/menu/"+item_id+"_"+status+".png\" width=\""+width+"\" height=\""+height+"\" alt=\""+item_title+"\" border=\"0\"/>";
					//img_tag = '';
          //alert(img_tag)
          $(this).text("");
			   	$(this).html(img_tag);


   	      //var img_tag = "<img id=\""+item_id+"\" src=\""+wwwRoot+"/comuni/img/menu/"+item_id+"_"+status+".png\" "+calcolaDimensioni(wwwRoot+"/comuni/img/menu/"+item_id+"_"+status+".png")+" alt=\""+item_title+"\" border=\"0\"/>";
   	      //alert(img_tag)

      }
   });
   //if ($.browser.msie) { $(".png").ifixpng(); }
}



function renderTitles() {
   $(".renderTitle").each(function(i) {
   	  //alert()
      var item_title      = $(this).text();
      var item_label      = escape($(this).text());
      var item_width      = $(this).width();
      //var item_width      = $(this).css('width');
      var item_fontSize   = $(this).css('font-size');
      var item_lineHeight = $(this).css('line-height');
      var item_color      = $(this).css('color');
      if(!item_color.match('#')){
       var item_color      = rgb2hex($(this).css('color'));
      }
      else
      {
       var item_color      = item_color.replace("#","");
      }
      
      
      //alert(item_width+" || "+item_width2+" || "+item_fontSize);
      if (item_title != '') {
   	      var img_tag = "<img src=\""+wwwRoot+"/dynamic/titles/custom/"+item_width+"/"+item_fontSize+"/"+item_lineHeight+"/"+item_color+"/"+item_label+".png\" alt=\""+item_title+"\" border=\"0\"/>";
   	      $(this).text("");
   	      //alert(img_tag)
   	      $(this).html(img_tag);
      }
   });
   //if ($.browser.msie) { $(".png").ifixpng(); }
}

function renderMenu2Liv() {
   $(".menuLiv2 a").each(function(i) {
      var item_title  = $(this).text();
      if (item_title != '') {
   
   	      
  	      
          var item_label  = escape($(this).text());
          var item_status  = $(this).attr('class');
          //alert(item_status)
   	      //var item_id     = item_level+"_"+i;
   	      var img_tag = "<img style=\"\" src=\""+wwwRoot+"/dynamic/img/titles/liv2_"+item_status+"/166px/"+item_label+".png\" alt=\""+item_title+"\" border=\"0\"/>";
   	      
   	      $(this).text("");
   	      $(this).html(img_tag);
      }
   });
   //if ($.browser.msie) { $(".png").ifixpng(); }
}

function stampaImmagine(item_id,status,item_title)
{
	//global wwwRoot;
 $.ajax({
   type: "GET",
   url: wwwRoot+'/ajax/calcolaDimensioni.php?img='+wwwRoot+"/comuni/img/menu/"+item_id+"_"+status+".png",
   success: function(msg){
     return ("<img id=\""+item_id+"\" src=\""+wwwRoot+"/comuni/img/menu/"+item_id+"_"+status+".png\" "+msg+" alt=\""+item_title+"\" border=\"0\"/>");

   }
 });
}


function sm()
{
	$("#tempSimeAjax").load(wwwRoot+'/ajax/sm.php'); 
 /*$.ajax({
   type: "GET",
   url: 'http://portale.sime.it/wps/portal/dgtmedia',
   success: function(msg){
     return false;
   }
 });*/
}


function loadInfoUtente()
{
 $("#login").html($("#login").html() + " <img src='" + wwwRoot + "/comuni/img/login_loading.gif' />");
 if (debug) alert("utente loggato, carico info");
 if (wwwLang=="it") {
  var url = "http://portale.sime.it/wps/myportal/dgtmedia/!ut/p/c1/0wcA1NLTeQ!!/?Jsoncallback=?";
 } else {
  var url = "http://portal.sime.co.uk/wps/myportal/dgtmedia/!ut/p/c1/0wcA1NLTeQ!!/?Jsoncallback=?";
 }
 $.ajax({
   type: "GET",
   dataType: 'json',
   url: url,
   success: function(msg){
	 if (debug) alert("info arrivate");
	 if (debug) alert(msg.userID);
   	 auth          = msg.auth;
   	 fullName      = msg.fullName;
   	 givenName     = msg.givenName;
   	 familyName    = msg.familyName;
   	 userID        = msg.userID;
    
	  if ($('#infoUtente').length) {
       $('#infoUtente').load(wwwRoot + '/get_gruppi_ldap.php?lang=' + wwwLang + '&username=' + rawurlencode(userID), function () {
	     var strumenti_label = "STRUMENTI";
		 var mercato = "01";
	     switch (wwwLang) {
                  case 'it':
                   cambio_pass_url = "http://portale.sime.it/LdapPassword/VerifyPassword?languageParamName=";
                   break;
		  case 'en':
		   strumenti_label = "TOOLS";
		   mercato = "02";
                   cambio_pass_url = "http://portal.sime.co.uk/LdapPassword/VerifyPassword?languageParamName=";
		   break;
		  case 'es':
		   strumenti_label = "INSTRUMENTOS";
		   mercato = "05";
                   cambio_pass_url = "http://portale.sime.it/LdapPassword/VerifyPassword?languageParamName=";
		   break;
		 }
         $('#menuLeft>ul').append("<li class='strumenti'><a href='#' onclick='$(\"#menuLeft>ul>li.strumenti>ul\").toggle()'>" + strumenti_label + "</a></li>");
         $('#menuLeft>ul>li.strumenti').append($('#infoUtente>ul'));
         $("#menuTop #password").text("Cambio password").removeAttr("onclick").attr("href", cambio_pass_url + wwwLang + "&brand=" + mercato);
         eseguiCodaDiAzioniAjax();
       });
      } else {
         eseguiCodaDiAzioniAjax();
      }
   }
 });
}

function eseguiCodaDiAzioniAjax()
{
   if (typeof sime_execute_after_user_session != "undefined") {
      if (debug) alert("qualcosa da eseguire");
      for (var k in sime_execute_after_user_session) {
		 if (debug) alert(sime_execute_after_user_session[k]);
         eval(sime_execute_after_user_session[k]);
         delete sime_execute_after_user_session[k];
      }
      delete sime_execute_after_user_session;
   }
}

function logoutUtente()
{
             switch (wwwLang) {
                  case 'en':
                   url = "http://portal.sime.co.uk/wps/portal/dgtmedia/";
                   break;
                  case 'it':
                   url = "http://portale.sime.it/wps/portal/dgtmedia/";
                   break;
                 }
	$(".iframe_wps").remove();
	var $io = $("<iframe src='" + url + "' class='iframe_wps' />").css({position: 'absolute', top: '-1000px', left: '-1000px'}).appendTo("body");
	var io = $io[0];
	io.attachEvent ? io.attachEvent('onload', lougoutUtenteCallback) : io.addEventListener('load', lougoutUtenteCallback, false);
	return false;
}

function lougoutUtenteCallback()
{
	if (logout_redirect.length>0) {
		window.location.href = logout_redirect;
	} else {
		window.location.href = wwwRoot + "/logout.php";
	}
}

function rawurlencode (str) {
    // URL-encodes string  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/rawurlencode
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin%20van%20Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();
 
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A');
}

