// Define some errors and hold `em all in an array
var errors = new Array();
errors[0]  = "Nu ai uploadat sau nu ai ales nicio poza din galerie!";
errors[1]  = "Mascareala nu poate fi trimisa deoarece nu ai scris nimic pe poza!";
errors[2]  = "Te rog sa introduci numele tau!";
errors[3]  = "Te rog sa introduci adresa de e-mail!";
errors[4]  = "Adresa de e-mail este invalida!";
errors[5]  = "Poza a fost deja mascarita si se afla in stadiul de verificare. Poti incerca un pic mai tarziu?";
errors[6]  = "Te rog sa introduci titlul acestei mascareli!";
errors[7]  = 'Nu ai selectat nicio poza!';
errors[8]  = 'Te rog sa introduci codul !';

function createHttpRequest()
{
	  if (window.XMLHttpRequest)
	  {
			return new XMLHttpRequest();
	  }
	  else if (window.ActiveXObject)
	  {
			try
			{
				  return new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e)
			{
				  try
				  {
						return new ActiveXObject("Microsoft.XMLHTTP");
				  }
				  catch (e)
				  {
						return null;
				  }
			}
	  }
}

var ajax = createHttpRequest();

function deleteLOL(url)
{
	  ajax.onreadystatechange = function()
	  {
			if (ajax.readyState == 4 && ajax.status == 200)
			{
				  deleted = ajax.responseText;
				  deleted = deleted.split(' | ');
				  if(deleted[0] == 1)
				  {
						window.scroll(0,0);
						document.getElementById('upload_info').innerHTML='Poza a fost stearsa cu succes!';
						document.getElementById('upload_success').style.display='block';
						setTimeout('hideMsg("'+deleted[1]+'")',3000);
				  }
			}
	  }
	  ajax.open('GET', url, true);
	  ajax.send(null);
}

function hideMsg(redirect)
{
	  var path = redirect || null;
          document.getElementById('upload_success').style.display='none';
          path ? document.location.href = path : document.location.reload(true);
}

function showPostedMsg()
{
	  document.getElementById('upload_success').style.display='block';
	  document.getElementById('upload_info').innerHTML='Mascareala a fost trimisa. Vei primi un e-mail cand aceasta se face publica.';
	  setTimeout('hideMsg()',6000);
}

function sendToEditor(LOL, blogURL)
{
	  var LOLstatus;

	  ajax.onreadystatechange = function()
	  {
                document.getElementById('imgLoader').style.display = 'block';

			if (ajax.readyState == 4)
			{
				  if(ajax.status == 200)
				  {
						LOLstatus = ajax.responseText;
						if(LOLstatus == 1 || LOLstatus == -1)
						{
							  displayError(errors[5]);
							  window.scrollTo(0, 0);
							  document.getElementById('imgLoader').style.display = 'none';
							  return false;
						}
						else
						{
							  document.getElementById('placeHolder').src = blogURL + "/builder/getImage.php?path=" + LOL;
							  document.getElementById('uploadedLOL').value = LOL;
							  getPicName = LOL.split('/');
							  LOLname    = getPicName[1];
							  document.getElementById('LOLname').value = LOLname;
							  document.getElementById('imgLoader').style.display = 'none';
						}
				  }
			}
	  }
	  ajax.open('GET', '/builder/checkStatus.php?lol=' + LOL, true);
	  ajax.send(null);
}

function exportValue(objID)
{
      var importVal = document.getElementById(objID).value;
      document.getElementById('scriptDescription').value = importVal;
}

function asyncPost(url, media_title, media_author, media_email)
{
      // build query
      var parameters = "joke_title=" + escape(media_title) +
                       "&author=" + escape(media_author) +
                       "&email=" + escape(media_email) +
                       "&embededScript=" + escape(encodeURI(document.getElementById("embededScript").value)) +
                       "&scriptDescription=" + escape(encodeURI(document.getElementById("scriptDescription").value)) +
                       "&addMedia=adaug";

			// open request
			ajax.open('POST', url, true);

			// send headers
			ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			ajax.setRequestHeader("Content-length", parameters.length);
			ajax.setRequestHeader("Connection", "close");

			ajax.onreadystatechange = function()
			{
                              if (ajax.readyState == 4 && ajax.status == 200)
                              {
                                    // get result
                                    result = ajax.responseText;

                                    // check result
                                    if(result != "error")
                                    {
                                          document.getElementById('async_info').innerHTML = 'Mascareala a fost trimisa. Vei primi un e-mail cand aceasta se face publica!';
                                          // hide
                                          toggleLayer('previewScript');
                                          toggleLayer('customizeScript');

                                          // show
                                          toggleLayer('asyncResult');
                                          setTimeout("clearMedia()", 5000);
                                    }
                              }
			}

      ajax.send(parameters);
      return false;
}

function clearMedia()
{
	  document.getElementById('asyncResult').style.display = 'none';
	  document.getElementById('embed').style.display = 'block';
	  document.getElementById('joke_title').value = '';
	  document.getElementById('author').value = '';
	  document.getElementById('email').value = '';
	  document.getElementById('script').value = '';

	  if(document.getElementById('script_description').value != "")
	  {
			document.getElementById('script_description').value = '';
	  }
}

function SetAlignment(section, alignment)
{
	  document.getElementById(section + 'alignment').value = alignment;
	  document.getElementById(section + 'left').style.backgroundColor='white';
	  document.getElementById(section + 'left').style.border = '1px solid #9047D0';
	  document.getElementById(section + 'center').style.backgroundColor='white';
	  document.getElementById(section + 'center').style.border = '1px solid #9047D0';
	  document.getElementById(section + 'right').style.backgroundColor='white';
	  document.getElementById(section + 'right').style.border = '1px solid #9047D0';
	  document.getElementById(section + alignment).style.backgroundColor = '#E1BFFF';
	  document.getElementById(section + alignment).style.border = '1px solid #9047D0';
}

function toggleLayer( whichLayer )
{
	  var elem, vis;

	  if( document.getElementById )
	  {
			elem = document.getElementById( whichLayer ); // standard way
	  }
	  else if( document.all ) // old versions
	  {
			elem = document.all[whichLayer];
	  }
	  else if( document.layers ) // ns4
	  {
			elem = document.layers[whichLayer];
	  }

	  vis = elem.style;

	  if(vis.display == '' && elem.offsetWidth !=undefined && elem.offsetHeight != undefined)
	  vis.display = (elem.offsetWidth !=0 && elem.offsetHeight !=0) ? 'block' : 'none';
	  vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}

function checkCustomization()
{
	  uploadedLOL = document.getElementById('placeHolder').src;
	  LOL = uploadedLOL.split('/');
	  if(LOL[LOL.length - 1] == 'bg_uploader.gif')
	  {
			displayError(errors[0]);
			return false;
	  }

	  theForm    = document.capit;
	  jokeTitle  = theForm.joke_title.value;
	  txtTop     = theForm.txtTop.value;
	  txtBottom  = theForm.txtBottom.value;
	  author     = theForm.author.value;
	  email      = theForm.email.value;

	  if(jokeTitle == '')
	  {
			displayError(errors[6]);
			return false;
	  }

	  if(txtTop == '')
	  {
			if(txtBottom == '')
			{
				  displayError(errors[1]);
				  return false;
			}
	  }

	  if(txtBottom == '')
	  {
			if(txtTop == '')
			{
				  displayError(errors[1]);
				  return false;
			}
	  }

	  if(txtTop != '' || txtBottom != '' || txtTop != '' && txtBottom != '')
	  {
			if(author == '')
			{
				  displayError(errors[2]);
				  return false;
			}

			if(email == '')
			{
				  displayError(errors[3]);
				  return false;
			}

			if(email != '' && !isEmail(email))
			{
				  displayError(errors[4]);
				  return false;
			}
	  }

	  return true;
}

function processUpload()
{
          if(document.upload.LOL.value != '')
	  {
			document.getElementById('submit').style.display='none';
	  }
	  else
	  {
			displayError(errors[7]);
			return false;
	  }
	  return true;
}

function checkScript()
{
	  if(document.embed.script.value != '')
	  {
			toggleLayer('embed'); // hide embeder form

			document.getElementById('previewScript').style.height = "150px";
			setTimeout("swapScript('script', 'previewScript')", 1500);

			toggleLayer('previewScript'); // show embeded script
			toggleLayer('customizeScript'); // show customization script

			document.getElementById('embededScript').value = document.getElementById('script').value;

			return false;
	  }
	  else
	  {
			displayError(errors[8]);
			return false;
	  }
	  return true;
}

function swapScript(obj1,obj2)
{
	  var embededScript = "<center>" + document.getElementById(obj1).value + "</center>";
	  embededScript += "\n<div id='scriptDescription'>\n";
	  embededScript += "<label for=\"script_description\">Descriere (optional)</label>\n";
	  embededScript += "<textarea name=\"script_description\" id=\"script_description\" onkeyup=\"exportValue(this.id)\"></textarea>";
	  embededScript += "</div>\n"

	  document.getElementById(obj2).innerHTML = embededScript;
	  document.getElementById(obj2).setAttribute('class', '');
	  document.getElementById(obj2).style.background = 'none'; // for IE only
	  document.getElementById(obj2).style.height = "";
}

function cancelMedia()
{
	  document.getElementById('embededScript').value = '';

	  toggleLayer('customizeScript'); // hide customization
	  toggleLayer('previewScript'); // hide embeded script

	  document.getElementById('script').value = '';
	  if(document.getElementById('script_description').value != "")
	  {
			document.getElementById('script_description').value = '';
	  }
	  document.getElementById('previewScript').innerHTML = '';

	  toggleLayer('embed'); // show embeder form
}

function checkMedia(url)
{
	  theForm    = document.media;
	  jokeTitle  = theForm.joke_title.value;
	  author     = theForm.author.value;
	  email      = theForm.email.value;

	  if(jokeTitle == '')
	  {
			displayError(errors[6]);
			return false;
	  }

	  if(author == '')
	  {
			displayError(errors[2]);
			return false;
	  }

	  if(email == '')
	  {
			displayError(errors[3]);
			return false;
	  }

	  if(email != '' && !isEmail(email))
	  {
			displayError(errors[4]);
			return false;
	  }

	  asyncPost(url, jokeTitle, author, email);
	  return false;
}

function overlay(LOLsrc, LOLwidth)
{
	  el = document.getElementById("overlay");
	  el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";

	  if(el.style.visibility == "visible")
	  {
			el = document.getElementById('overlayedLoL');
			el.style.width  = LOLwidth + "px";
	  }

	  objImage        = new Image();
	  objImage.src    = LOLsrc;
	  objImage.onLoad = setTimeout("showLoadedLOL('"+LOLsrc+"')", 1000);

	  el.innerHTML = '<span id="renderer_txt">Se afiseaza poza <img src="http://www.mascarit.ro/builder/images/indicator.gif" alt="indicator" /></span>';
}

function showLoadedLOL(LOLsrc)
{
	  el = document.getElementById('overlayedLoL');
	  lolSrc = "http://mascarit.ro/builder/" + LOLsrc;

	  // Show lol
	  el.innerHTML = '<img src="'+lolSrc+'" alt="se deschide..." onclick="hideImg()" /><a href="javascript:void(0)" title="Inchide" onclick="hideImg()"><img class="icon_close" src="http://www.mascarit.ro/builder/images/close_lol.gif" alt="inchide" /> Inchide</a>';
}

function hideImg()
{
	  el = document.getElementById("overlay");
	  el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";

	  if(el.style.visibility == "visible")
	  {
			el.style.visibility == "hidden";
	  }
	  else
	  {
			el.style.visibility == "visible";
	  }
}

function checkSize()
{
	  var myWidth = 800;
	  if( typeof( window.innerWidth ) == 'number' )
	  {
			// Non-IE
			myWidth = window.innerWidth;
	  }
	  else if( document.documentElement && ( document.documentElement.clientWidth ) )
	  {
			// IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
	  }
	  else if( document.body && ( document.body.clientWidth ) )
	  {
			// IE 4 compatible
			myWidth = document.body.clientWidth;
	  }
	  return myWidth;
}

function displayError(error)
{
	  // Content creation
	  var content = new Array();
	  var index = 0;

          content[index++] = '<h1><img src="http://www.mascarit.ro/builder/images/fail.gif" /> Uhm!</h1>';
	  content[index++] = error + "<br /><br />";
	  content[index++] = '<p style="border: 1px solid #c3c3c3; width: 25px; text-align: center; background-color: #f3f3f3; padding: 2px; margin-bottom: 5px;"><a href="javascript:void(0);" onclick="hideErrorBox()">ok</a></p>';

	  document.getElementById("errorBox").innerHTML = content.join("");
	  document.getElementById("errorBox").style.visibility = "visible";

	  window.scrollTo(0,100);
}

function hideErrorBox()
{
	  document.getElementById('errorBox').style.visibility = 'hidden';
}

function switchTab(objID)
{
	  selected_tab = document.getElementById(objID);
	  switch(objID)
	  {
			case "newPics":
				 selected_tab.setAttribute("class","selected");
				 document.getElementById('oldPics').setAttribute("class","");
				 document.getElementById('oldLoLs').style.display='none';
				 document.getElementById('newLoLs').style.display='block';
				 break;
			case "oldPics":
				 selected_tab.setAttribute("class","selected");
				 document.getElementById('newPics').setAttribute("class","");
				 document.getElementById('oldLoLs').style.display='block';
				 document.getElementById('newLoLs').style.display='none';
				 break;
			case "img":
				 selected_tab.setAttribute("class","selected");
				 document.getElementById('mov').setAttribute("class","");
				 document.getElementById('uploader').style.display='block';
				 document.getElementById('embeder').style.display='none';
				 break;
			case "mov":
				 selected_tab.setAttribute("class","selected");
				 document.getElementById('img').setAttribute("class","");
				 document.getElementById('uploader').style.display='none';
				 document.getElementById('embeder').style.display='block';
				 break;
	  }
}

function calcHeight()
{
          //find the height of the internal page
          var the_height = document.getElementById('framedGallery').contentWindow.document.body.scrollHeight;

          //change the height of the iframe
          document.getElementById('framedGallery').height = the_height;
}

function isEmail(email)
{
	  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
	  {
			return true;
	  }
	  return false;
}

//returns the window size
function windowsize() {
	  var x,y;
	  if (self.innerHeight) // all except Explorer
	  {
		  x = self.innerWidth;
		  y = self.innerHeight;
	  }
	  else if (document.documentElement && document.documentElement.clientHeight)
          // Explorer 6 Strict Mode
	  {
		  x = document.documentElement.clientWidth;
		  y = document.documentElement.clientHeight;
	  }
	  else if (document.body) // other Explorers
	  {
		  x = document.body.clientWidth;
		  y = document.body.clientHeight;
	  }
	  retval = new Object;
	  retval.x = x;
	  retval.y = y;
	  return retval;
}

function toggleEmbeder(id)
{
      if (document.getElementById(id).style.display =='none')
      {
            document.getElementById(id).style.display = 'block';
      }
      else
      {
            document.getElementById(id).style.display = 'none';
      }
}
