// behnevis API

//	34a50f9fb4799e9d42dbcbc34c93e555

//---- Helper functions -----------

function loadJsOrCssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadJsOrCssfile("http://behnevis.s3.amazonaws.com/highslide_mini.js", "js") //dynamically load and add this .js file
loadJsOrCssfile("http://behnevis.s3.amazonaws.com/highslide.css", "css") ////dynamically load and add this .css file

var IE = document.all?true:false;

var SAFARI = false;
if(/Safari/.test(navigator.userAgent))
{
 SAFARI = true;
}

// for all browsers
function setCaretPosition(ctrl, pos)
{

  if (IE)
  {
	  if(ctrl.setSelectionRange)
	  {
		  ctrl.focus();
		  ctrl.setSelectionRange(pos,pos);
	  }
	  else if (ctrl.createTextRange) {
		  var range = ctrl.createTextRange();
		  range.collapse(true);
		  range.moveEnd('character', pos);
		  range.moveStart('character', pos);
		  range.select();
	  }
  }
  else // firefox
  {
	  ctrl.selectionStart = pos;
	  ctrl.selectionEnd = pos;
  }
}


//--------- Behnevis API functions -----------

var behnevis = new Object(); // object holding all variable and functions

behnevis.lastHash = "";
// these need to be defined inside popup too
behnevis.pipeHashLabel = "behnevis";
behnevis.pipeCancelLabel = "closeBehnevis";


behnevis.setHighSlideInitParameters = function()
{
	// run the function until hs becomes defined and then set tits fields
	if ( typeof( window[ 'hs' ] ) != "undefined" )
	{
	  hs.graphicsDir = 'http://www.behnevis.com/javascript/highslide/graphics/';
	  hs.outlineType = 'rounded-white';
  
  //	hs.creditsText = 'تبدیل با بهنویس';
  //	hs.creditsHref = 'http://www.behnevis.com';
	  hs.showCredits = false;
	  hs.preserveContent = false;
  //	hs.lang.cssDirection = 'rtl';
  //	hs.lang.closeText = '  بستن  ';
	  hs.lang.closeText = '';
	  hs.lang.moveText = 'جابجایی';
	  hs.lang.loadingText = 'در حال بارگزاری...';
	  hs.allowMultipleInstances = false;	
	}
	else
	{
		setTimeout ('behnevis.setHighSlideInitParameters();', 100); // run the function again in 100 ms
	}
}

behnevis.init = function ()
{
	behnevis.setHighSlideInitParameters();
	behnevis.waitingForPipemessage = false;
	behnevis.getAndRemovePipHash();	
}

// remove the hash associated with the behnevis pipe (segemnt identifier)
behnevis.removePipeHash = function (positionInLocationHash)
{			
	if (IE)
	{
		location.hash = location.hash.substring(0,positionInLocationHash-1);
	}
	else
	{
		location.hash = location.hash.substring(0,positionInLocationHash);
	}
}


behnevis.getAndRemovePipHash = function ()
{
	
	var hash = location.hash;
	var myregexp = new RegExp(behnevis.pipeHashLabel ); 

	var pipeHashLabelIndex = hash.search(myregexp);
	
	if (pipeHashLabelIndex>-1)
	{
		var pipeMessage = new Object();	 
		pipeMessage.text = decodeURI(hash.substring(pipeHashLabelIndex+behnevis.pipeHashLabel.length+1,hash.length)); // until the end of hash	
		pipeMessage.type = 'ok'; // ok button was pressed
		behnevis.removePipeHash (pipeHashLabelIndex);	
		return pipeMessage;
		
	}	
	
	var myregexp = new RegExp(behnevis.pipeCancelLabel); 
	var pipeHashLabelIndex = hash.search(myregexp);
	if (pipeHashLabelIndex>-1)
	{			
		var pipeMessage = new Object();	 
		pipeMessage.text = '';
		pipeMessage.type = 'cancel'; // ok button was pressed
		
		behnevis.removePipeHash(pipeHashLabelIndex);	
		return pipeMessage; // null means cancel happened
	}	

	return null; // null no message was received

}

behnevis.checkForPipeMessages = function () // check the hash section and look for text to come in the pip from the iframe
{
if (behnevis.waitingForPipemessage)
  {
  if(location.hash != behnevis.lastHash)
	  {		  
		  var pipeMessage = behnevis.getAndRemovePipHash();
		  behnevis.lastHash = location.hash;
		  
		  if (pipeMessage) // there was an ok or cancek message
		  {		  
			  if (pipeMessage.type=='ok')
			  {
				  pipeMessage.text = pipeMessage.text.replace(/%23/g, '#'); // because # gets mistaken by segment identifier and had to be replaced.
				  document.getElementById(behnevis.targetElementId).style.direction = 'rtl';
				  document.getElementById(behnevis.targetElementId).value = pipeMessage.text;
			  }
		  		 
		  
			  behnevis.waitingForPipemessage = false;
			  hs.close(hs.contentId); // id of the opening element	
		  
  			  // focus on the input element and place the caret at the end of text
			  document.getElementById(behnevis.targetElementId).focus();
			  setCaretPosition(document.getElementById(behnevis.targetElementId), document.getElementById(behnevis.targetElementId).value.length);
		  }
		  else
		  {
			   setTimeout ('behnevis.checkForPipeMessages();', 100); // if hash has changed but no message received
		  }
	  }
	  else // keep looking for pip messages
	  {
		  setTimeout ('behnevis.checkForPipeMessages();', 100); // run the function again in 200 ms
	  }
  }
}


behnevis.startWaitingForPipeMessage = function ()
{
	behnevis.waitingForPipemessage = true;
	behnevis.checkForPipeMessages();
}


behnevis.launchPopup = function(element, targetElementId)
{		
	behnevis.targetElementId = targetElementId;
	var textToSend = document.getElementById(behnevis.targetElementId).value;

	textToSend = textToSend.replace(/#/g, '%23'); // because # gets mistaken by segment identifier.
	
	var url = 'http://www.behnevis.com/api/behnevis_mini.php?latin='+ encodeURI(textToSend)+'&parenturl=' + encodeURI(location.href);
//	var url = 'behnevis_mini.php?latin='+ encodeURI(textToSend)+'&parenturl=' + encodeURI(location.href);
	
	hs.src = url
	element.href = url;
//	element.id = "behnevis_popup";
	hs.preserveContent  = false;
	behnevis.startWaitingForPipeMessage();

	hs.width = 650;
	hs.height = 310;
	hs.htmlExpand(element, {objectType: 'iframe'} );
	
	return false;
}

behnevis.init();