// === PRELOAD FUNCTIONS ===

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



// === TOGGLE ID ===

	var showMode = 'block';
	if (document.all) showMode = '';

	function toggleId(id, y_scroll){
	  if (document.all) {
		var obj = document.all[id];
	  } else if (document.getElementById) {
		 var obj = document.getElementById(id);
	  } else return false;
	  if (obj.style.display == 'none') {
	     obj.style.display = showMode;
	  	 if (y_scroll) scroll(0,y_scroll);
	  } else obj.style.display = 'none';
	  return false;
	}


// === POPUP OPEN ===

	function openWin(indirizzo,olw) {
  		myWindow=window.open(indirizzo,'','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,top=30,left=20,width=626,height=520');
		return myWindow;
	}
	mw=null;


// === SET LINKS TO "splinder.com" ===

	function parse_links() {
		   for(i=0; i< document.links.length; i++) {
		     re = /splinder.it/gi;
		     if ( document.links[i].href != document.links[i].href.replace(re,'splinder.com') ) {
		       document.links[i].href = document.links[i].href.replace(re,'splinder.com');
		       document.links[i].innerHTML = document.links[i].innerHTML.replace(re,'splinder.com');
			 }
		   }
	}

function isValidKeyCode(key) {
  switch (key) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
    case 9:  // tab
    case 13: // enter
    case 27: // esc
    case 112: // F1
    case 113: // F2
    case 114: // F3
    case 115: // F4
    case 116: // F5
    case 117: // F6
    case 118: // F7
    case 119: // F8
    case 120: // F9
    case 121: // F10
    case 122: // F11
    case 123: // F12
      return false;
  }
  return true;
}

function toggleCheckboxes(obj_name) {
	var d = document.getElementsByTagName('input');
        for(i=0;i<d.length;i++) if(d[i].type=='checkbox') {
		if (obj_name && d[i].name.indexOf(obj_name)==-1) continue;
		d[i].checked=!d[i].checked;
	}
        return false;
}

function myblogManagePostsComments(action, e) {
	var frm = document.forms[0];
	switch(action) {
		case 'filter':
			frm.action = submit_url;
			frm.submit();
			return;
		case 'selectall':
			return toggleCheckboxes('edit[selected]');	
		case 'validate':
			var d = document.getElementsByTagName('input');
			var result = false;
			for(i=0;i<d.length;i++) if(d[i].type=='checkbox') {
				if (d[i].checked) {
					result = true;
					break;
				}
			}
			if (result) frm.submit();
				else alert(selectMessage);
			return result;
		case 'onUserKeyPress':
		case 'onUserKeyUp':
		case 'onUserBlur':
			var objStatus = document.getElementById('filter_status');
			var objUser = document.getElementById('filter_author');
			if (!objStatus) return false;
			if (action=='onUserBlur' && !objUser.value) {
				objStatus.disabled = false;
				return false;
			}
			objStatus.value = 'all';
			var user = objUser.value;
                        if (action=='onUserKeyUp' && !user) {
				objStatus.disabled = false;
	                        return false;
			}
			if (e.keyCode==8 && user.length==1) {
				objStatus.disabled = false;
				return false;
			}
			if (isValidKeyCode(e.keyCode)) {
				objStatus.disabled = true;
				return false;
			}
			return false;
	}
}

function showOverlibPopup(title, content) {
    overlib(content,
       FOLLOWSCROLL,
       STICKY,
       CAPTION, title,
       WIDTH, 300,
       CSSCLASS,
       TEXTFONTCLASS,'fontClassOL',
       FGCLASS,'fgClassOL',
       BGCLASS,'bgClassOL',
       CAPTIONFONTCLASS,'capfontClassOL',
       CLOSECLICK);
    return false;
}

function showOverlibHelp(title, content) {
    overlib(content,
       LEFT,
       STICKY,
       CAPTION, title,
       WIDTH, 300,
       CSSCLASS,
       TEXTFONTCLASS,'fontClassOL',
       FGCLASS,'fgClassOL',
       BGCLASS,'bgClassOL',
       CAPTIONFONTCLASS,'capfontClassOL',
       CLOSECLICK);
    return false;
}

function showOverlibCentered(title, content) {
    overlib(content,
       FOLLOWSCROLL,
       STICKY,
       WIDTH, 400,
       CENTERPOPUP,
       CSSCLASS,
       TEXTFONTCLASS,'fontClassOL',
       FGCLASS,'fgClassOL',
       BGCLASS,'bgClassOL',
       CAPTIONFONTCLASS,'capfontClassOL',
       CLOSECLICK);
    return false;
}

function media_popup_style(width, height) {
    // keep alignment styles sync with function _media_post_format() in media.module
    var style = '';

    var size = '';
    if (width) size += 'width:'+width+'px;';
    if (height) size += 'height:'+height+'px;';

    for(i=0; i<document.getElementsByName('edit[align]').length; i++) {
	  if (document.getElementsByName('edit[align]')[i].checked) {
		switch(i) {
			case 0:
				style = ' style="margin: 0pt 10px 10px 0pt; float:left;'+size+'" ';
				break;
			case 1:
				style = ' style="margin: 0px auto 10px; display: block; text-align: center;'+size+'" ';
				break;
			case 2:
				style = ' style="margin: 0pt 0pt 10px 10px; float: right;'+size+'" ';
				break;
		}
	  }
	}
	return style;
}

function media_popup_post_photo(textarea_id, title, path_thumbnail, path_small, path_medium) {
    var style = media_popup_style(0, 0);
    var path = '';
	for(i=0; i<document.getElementsByName('edit[thumb_id]').length; i++) {
	  if (document.getElementsByName('edit[thumb_id]')[i].checked) {
		switch(i) {
			case 2:
				path = path_medium;
			    if (path) break;
			case 1:
				path = path_small;
			    if (path) break;
			case 0:
				path = path_thumbnail;
		}
	  }
	}
	if (!path) {
		alert('Path not valid');
		return false;
	}

	opener.InsertHTML(textarea_id, '<img ' + style + ' src=\'' + path + '\' alt=\'' + title + '\' />');
}

function media_popup_post_audio(textarea_id, placeholder) {
	style = media_popup_style(0, 0);
        placeholder = placeholder.replace(/%style/gi, style);
	opener.InsertHTML(textarea_id, placeholder);	
}


function media_popup_post_video(textarea_id, placeholder) {
    var size = '';
    for(i=0; i<document.getElementsByName('edit[thumb_id]').length; i++) {
      if (document.getElementsByName('edit[thumb_id]')[i].checked) {
        size = document.getElementsByName('edit[thumb_id]')[i].value;
        var size_a = size.split('x');
        //size = 'width="' + size_a[0] + '" height="' + size_a[1] +'"';
      }
    }
    style = media_popup_style(size_a[0], size_a[1]);

    placeholder = placeholder.replace(/%style/gi, style);
    //placeholder = placeholder.replace(/%size/gi, size);
    opener.InsertHTML(textarea_id, placeholder);
}

function mysearch_submit(type) {
	var frm = document.topbar_search;
	var query = frm.elements[0].value;
	if (!query || query=='') return false;
	if (type == 'site') frm.elements[1].value = '';
	frm.submit();
}

function blognotifier_launch_tipicweb(uid, chat, notify) {
  var url = '/blognotifier/launchtipicweb';
  if (chat) url += '?chat_with=' + uid;
  window.open(url, 'TipicWEB', 'width=250, height=500, resizable');
}

function AjaxReport(nid, report_type) {
  var btn = new Array();
  var post_url = 'ajax_report/' + nid + '?' + report_type + '=1';
  AjaxSubmit(btn, post_url, null, AjaxReportResponse, 'content_control_throbber');
}
function AjaxReportResponse(xmlhttp, parameter) {
  var obj = document.getElementById('content_control');
  if (obj) obj.innerHTML = xmlhttp.responseText;
}




// === topframe animation ===

var visualization_order;
function makeSpans(textParam, destinationParam)
{
  textParam = textParam.replace(/\|/g, " ");
  mytext = textParam.split("</A>");
  if (mytext.length==1) // firefox puts everything in lowcase, IE not
     mytext = textParam.split("</a>");

  for(i =0; i< mytext.length; i++)
  {
     mytext[i]="<span style='visibility: hidden' id='keyword"+i+"' >" + mytext[i] + "</A></span>";
  }

  document.getElementById(destinationParam).innerHTML = "";
  for(i =0; i< mytext.length; i++) {
     document.getElementById(destinationParam).innerHTML += mytext[i];
     if (i< mytext.length-2)
        document.getElementById(destinationParam).innerHTML += "<span style='visibility: hidden' id='separator"+i+"_" + (i+1) + "' >&nbsp;&nbsp; | &nbsp;&nbsp;</span>";
  }

  visualization_order = new Array( mytext.length );  
  for(i=0; i< visualization_order.length; i++)
  {
     visualization_order [i] = i;
  }
}

function start_show()
{
   visualization_order = Shuffle(visualization_order);
   currentChar=0;
   visualization_order = Shuffle(visualization_order);
   for (i=0; i<visualization_order.length; i++) {
      document.getElementById("keyword"+i).style.visibility="hidden";
      sep1 = document.getElementById("separator"+(i-1)+"_"+i);
      if (sep1)
          sep1.style.visibility = "hidden";


   }

   setTimeout("show()", delay);
}

function show()
{
  if (document.getElementById)
  {
    var dest=document.getElementById(destination);
    if (dest)
    {
      toshow = visualization_order[currentChar];
      document.getElementById("keyword"+toshow).style.visibility="visible";
      preword   = document.getElementById("keyword"+(toshow+1));
      postword  = document.getElementById("keyword"+(toshow-1));
      sep1 = document.getElementById("separator"+toshow+"_"+(toshow+1));
      sep2 = document.getElementById("separator"+(toshow-1)+"_"+toshow);
      if (sep1)
          sep1.style.visibility = preword.style.visibility;
      if (sep2)
          sep2.style.visibility = postword.style.visibility;


      currentChar++;
      if (currentChar>=visualization_order.length)
      {
        setTimeout("start_show()", 6000);
      }
      else
      {
        setTimeout("show()", delay);
      }
    }
  } 
}

function Shuffle(Q) 
{
    var R, T, J;
    for (J = Q.length - 1; J > 0; J--) {
        R = Math.floor(Math.random() * (J+1));
        T = Q[J];
        Q[J] = Q[R];
        Q[R] = T;
    }
    return Q;
}

function startTyping2(textParam, delayParam, destinationParam)
{
  makeSpans( textParam, destinationParam);
  destination = destinationParam;
  delay = delayParam;
  start_show();
}

function startTopframeAnimation()
{
try {

startTyping2(
  document.getElementById("block-right").innerHTML,
  750,
  "block-right" );

}
catch(e) {};
}


function CopyToClipboard(id) {
  var obj = document.getElementById(id);
  if (obj==null) return false;
  var myText = obj.value;
  if (window.clipboardData) {
    // for IE
    window.clipboardData.setData("Text", myText);
  } else if (window.netscape) {
    // Firefox requires this setting   user_pref("signed.applets.codebase_principal_support", true);  (open the about:config page)
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
    var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
    if (!clip) return;

    var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
    if (!trans) return;

    trans.addDataFlavor('text/unicode');

    var str = new Object();
    var len = new Object();
    var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
    var copytext = myText;
    str.data = myText;
    trans.setTransferData("text/unicode", str, myText.length*2);
    var clipid = Components.interfaces.nsIClipboard;
    if (!clip) return false;
    clip.setData(trans,null,clipid.kGlobalClipboard);
  }
  return false;
}

function killbanner() {
}

function adsense_toggle_checkboxes(obj_name) {
  if (obj_name == 'edit[position][manual]') {
    for (i=0; i<document.forms[0].length; i++) {
      if (document.forms[0].elements[i].type == 'checkbox' && document.forms[0].elements[i].name != obj_name) {
        document.forms[0].elements[i].checked = false;
      }
    }
  }
  else {
    var count = 0;
    document.forms[0].elements['edit[position][manual]'].checked = false;
    for (i=0; i<document.forms[0].length; i++) {
      if (document.forms[0].elements[i].type == 'checkbox'
        && document.forms[0].elements[i].name != 'edit[position][permalink]'
        && document.forms[0].elements[i].checked) {
          count++;
          if (document.forms[0].elements[i].name == 'edit[position][posts]') count++;
      }
      if (count > 3) {
        alert('Attenzione! Hai superato il limite di \n 3 banner visualizzabili nella pagina!');
        return false;
      }
    }
  }
  return false;
}

function toggleText(id) {
  var s = document.getElementById(id).style;
  s.display = (s.display == 'none') ? '' : 'none';
}

function mysearchBasicSubmit(frm1) {
  var frm2 = null;
  if (document.frmSearchPosts) frm2 = document.frmSearchPosts;
    else if (document.frmSearchUsrss) frm2 = document.frmSearchUsers;
      else if (document.frmSearchMedia) frm2 = document.frmSearchMedia;
  if (frm2 == null) return;

  var replace = {' ':'+'};
  var fields = new Array('edit[tag]', 'edit[blog]', 'edit[blogger]');
  for (var i in fields) {
    var obj1 = frm1.elements[fields[i]];
    var obj2 = frm2.elements[fields[i]];
    if (obj1 && obj2 && obj2.value) {
      obj1.value = obj2.value;
    }
  }
}

function mysearchUsersSubmit(frm1) {
  if (frm1 == 'frmSearch') {
    var frm1 = document.forms[frm1];
    var frm2 = document.frmSearchUsers;
    var fields = new Array('edit[gender]', 'edit[age]', 'edit[location]', 'edit[tag]');
    for (var i in fields) {
      var obj1 = frm1.elements[fields[i]];
      var obj2 = frm2.elements[fields[i]];
      if (fields[i] == 'edit[gender]') {
        if (obj1 && obj2) for (var j = 0; j < 3; j++) if (obj2[j].checked) obj1.value = j;
      }
      else if (obj1 && obj2 && obj2.value) obj1.value = obj2.value;
    }
  }
  else {
    var frm1 = document.forms[frm1];
    var frm2 = document.frmSearch;
    var fields = new Array('edit[query]', 'edit[name]', 'edit[blogger]', 'edit[birth]', 'edit[blog]');
    for (var i in fields) {
      var obj1 = frm1.elements[fields[i]];
      var obj2 = frm2.elements[fields[i]];
      if (obj2.value) obj1.value = obj2.value;
    }
  }
  return;

  var replace = {' ':'+'};
  var fields = new Array('edit[query_adv]', 'edit[age]', 'edit[location]', 'edit[tag]', 'edit[name]', 'edit[blogger]', 'edit[birth]', 'edit[blog]');
  for (var i in fields) {
    var obj1 = frmBasic.elements[fields[i]];
    var obj2 = frmQuick.elements[fields[i]];
    if (obj1 && obj2) {
      if (obj1.value) obj2.value = obj1.value;
        else obj1.value = obj2.value;
    }
  }
  var fields = new Array('edit[gender]');
  for (var i in fields) {
    alert(this.form.name);
  }
}

function mysearchQuickSubmit(frm1) {
  var frm2 = null;
  if (document.frmSearch) frm2 = document.frmSearch;
  if (frm2 == null) return;

  var obj = frm2.elements['edit[query_adv]'];
  if (obj && obj.value) {
   frm1.elements['edit[query_adv]'].value = obj.value;
  }
  else {
    obj = frm2.elements['edit[query]'];
    if (obj) frm1.elements['edit[query_adv]'].value = obj.value;
  }
  return;

  var replace = {' ':'+'};
  var fields = new Array('edit[tag]', 'edit[blog]', 'edit[blogger]');
  for (var i in fields) {
    obj = frm1.elements[fields[i]];
    if (obj && obj.value) {
      str = obj.value;
      for (var character in replace) {
        str = str.replace(character, replace[character]);
      }
      obj.value = str;
    }
  }
}

// MEDIA PLAYER FUNCTIONS
function shareMediaF(playList) {
  window.open("/community/contacts/invite?nid=" + playList.id, "_blank");
}
function embedF(playList) {
  var iLeft=(screen.width-580)/2;
  var iTop=(screen.height-400)/3;
  window.open("/media/embed/" + playList.id + "?code=1", "popup", "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=0, screenX=0, screenY=0, top=" + iTop + ", left=" + iLeft + ", width=580, height=400");
  return false;
}
function commentF(playList) {
  openWin("/media/comment/view/" + playList.id, mw);
  return false;
}
function reportF(playList) {
}

var pageid=Math.floor(Math.random()*1000000);

function getCookie(name) {
  var prefix = name + "=";
  var cookieStartIndex = document.cookie.indexOf(prefix);
  if (cookieStartIndex == -1) return null;
  var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
  if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
  //return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
  var cookie_string = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
  var cookie_array = new Array();
  var parts = cookie_string.split("&");
  for (var i in parts) {
    var part = parts[i].split("=");
    cookie_array[part[0]] = part[1];
  }
  return cookie_array;
}

function getDadanetCookie() {
  return getCookie('dadanetuser');
}

function my_url_encode(s) {
  var SAFECHARS = "0123456789" +	// Numeric
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
	"abcdefghijklmnopqrstuvwxyz" +
	"-_.!~*'()";			// RFC2396 Mark characters
  var HEX = "0123456789ABCDEF";
  var encoded = "";
  for (var i = 0; i < s.length; i++ ) {
    var ch = s.charAt(i);
    if (ch == " ") {
      encoded += "+";			// x-www-urlencoded, rather than %20
    } else if (SAFECHARS.indexOf(ch) != -1) {
      encoded += ch;
    } else {
      var charCode = ch.charCodeAt(0);
      if (charCode > 255) {
        alert( "Unicode Character '" + ch +
	  "' cannot be encoded using standard URL encoding.\n" +
	  "(URL encoding only supports 8-bit characters.)\n" +
	  "A space (+) will be substituted." );
	encoded += "+";
      } else {
	encoded += "%";
	encoded += HEX.charAt((charCode >> 4) & 0xF);
	encoded += HEX.charAt(charCode & 0xF);
      }
    }
  } // for
  return encoded;
};

function trackStats(context, stat_img_url) {
  if (!context || !context.uri) return;
  stat_img_url += "?u=" + context.uri;
  if (context.context) stat_img_url += "&amp;c=" + context.context;
  if (context.action) stat_img_url += "&amp;a=" + context.action;
  if (context.author) stat_img_url += "&amp;n=" + context.author;
  if (context.login) stat_img_url += "&amp;i=1";
  if (context.nodename) stat_img_url += "&amp;p=" + context.nodename;
  if (context.blogname) stat_img_url += "&amp;l=" + context.blogname;
  if (document.referrer) stat_img_url += '&amp;r=' + escape(document.referrer);
  return '<img src="' + stat_img_url + '" width="1" height="1" alt="" border="0" />';
  document.write('<img src="' + stat_img_url + '" width="1" height="1" alt="" border="0" />');
}

function textCounter(text, counter, maxLength) {
  var str = text.value;
  var len = str.length;
  var nLines = str.split(/\r?\n|\r/).length;
  len = len + nLines - 1;
  counter.value = len;
  if (len <= maxLength) {
    counter.style.fontWeight = 'normal';
    counter.style.color = '#000000';
  }
  else {
    counter.style.fontWeight = 'bold';
    counter.style.color = '#FF0000';
  }
}

function trackStats(context, stat_img_url) {
  if (!context || !context.uri) return;
  stat_img_url += "?u=" + context.uri;
  if (context.context) stat_img_url += "&amp;c=" + context.context;
  if (context.action) stat_img_url += "&amp;a=" + context.action;
  if (context.author) stat_img_url += "&amp;n=" + context.author;
  if (context.login) stat_img_url += "&amp;i=1";
  if (context.nodename) stat_img_url += "&amp;p=" + context.nodename;
  if (context.blogname) stat_img_url += "&amp;l=" + context.blogname;
  if (document.referrer) stat_img_url += '&amp;r=' + escape(document.referrer);
  return '<img src="' + stat_img_url + '" width="1" height="1" alt="" border="0" />';
}
