// JavaScript Document
// Javascript Code for highlight Tags:
var SiteUrl="'"+window.location+"'";
var ctimeTagHide=0;
if(SiteUrl.indexOf("localhost") > -1 )
{
	//var AjaxTagRootPath='http://localhost/wordpress/jcm/?page_id=300';
	var AjaxTagRootPath='SaveTag.php';
}
else
{
	//var AjaxTagRootPath='http://www.jamesmetzger.net/wordpress/jcm/?page_id=283';
	var AjaxTagRootPath='SaveTag.php';
}

function hovers(event,isover,x,y,w,h,TagText,TagId){	
if(isover)
{
	//alert("in");
	 clearTimeout(ctimeTagHide);
	//Storing Tag Id in the hidden feild which will be used if delete a tag
	 document.getElementById("hdnTagId").value=TagId;
	// here instead of width and height i have passed right and bottom
	//so we have to calculate the width and height;	
	//alert(pageLeft);
	 w=parseInt(w)-parseInt(x);
	 h=parseInt(h)-parseInt(y);	
    // showing div in position
    //$("#odiv").css({top:x+'px', left:y+'px', width:w+'px',height:h+'px',opacity:1}).show().click(function (){window.open(m,"Jordan Map");
	var ImageShowed=document.getElementById('PopUpImageOnWindow'); 
	var ImageLeft =findPosX(ImageShowed)+130;
	var ImageTop=findPosY(ImageShowed);
	//alert(ImageLeft+ " "+ImageTop);
	
	x=parseInt(x)+parseInt(ImageLeft);
	y=parseInt(y)+parseInt(ImageTop)+1;// i have added 1 px here because when we create a div with same area parameters 
	//and place over area it will not reach up to the correct area bottom so when i move out mouse from div it will call hiding function 
	//at the same time it will call show function by area
											//alert(x +" "+ y);
	$("#divTagPopUp").css({top:y+'px', left:x+'px', width:w+'px',height:h+'px',opacity:1}).show();
	document.getElementById('divTagPopUpMessage').innerHTML='<b>'+TagText+'</b>';
	//var tagx=parseInt(x)+parseInt(w)-w/2; //starts  from picure area center to right
	var tagx=parseInt(x)//+parseInt(w)-w/2;//starts  from picure area left to right
	var tagy=parseInt(y)+parseInt(h);
	//alert(tagx +" "+tagy);
	document.getElementById('divTagPopUpMessageContainer').style.left=tagx+"px";
	document.getElementById('divTagPopUpMessageContainer').style.top=tagy+"px";
	//document.getElementById('divTagPopUpMessageContainer').style.width=TagText.length*7+19+"px";
	//document.getElementById('divTagPopUpMessageContainer').style.overflow="hidden";
	document.getElementById('divTagPopUpMessageContainer').style.display='';
}
else 
{
	//alert("out");
	clearTimeout(ctimeTagHide);
	if(document.getElementById('UserLoggedIn').value=="Admin")
	    ctimeTagHide=setTimeout('HideTagHighLight()',1000);
	else
	    ctimeTagHide=setTimeout('HideTagHighLight()',0);
	//document.getElementById('divTagPopUpMessageContainer').style.display='none';	
	// hiding this div.
	//$("#divTagPopUp").hide().unbind('click');
}
}
$('#textbox').blur(function () {
  var content = $(this).val();
  if (!content) return; // Don't make anything out of empty textboxes.
  // Create a DIV and make it a sibling to the textbox.
  $('<div>').html(content).appendTo($(this).parent());
  // Remove the textbox.
  $(this).remove();
});

function HideTagHighLight()
{
	
	document.getElementById('divTagPopUpMessageContainer').style.display='none';	
	// hiding this div.
	$("#divTagPopUp").hide().unbind('click');
}
function ShowTagHighLightDiv()
{
	clearTimeout(ctimeTagHide);
	document.getElementById('divTagPopUpMessageContainer').style.display='';
}
// Javascript Code for making Tagger box:
//<![CDATA[

// Using DragResize is simple!
// You first declare a new DragResize() object, passing its own name and an object
// whose keys constitute optional parameters/settings:

var dragresize = new DragResize('dragresize',
 { minWidth: 30, minHeight: 30, minLeft: 20, minTop: 20, maxLeft: 1000, maxTop: 2000 });

// Optional settings/properties of the DragResize object are:
//  enabled: Toggle whether the object is active.
//  handles[]: An array of drag handles to use (see the .JS file).
//  minWidth, minHeight: Minimum size to which elements are resized (in pixels).
//  minLeft, maxLeft, minTop, maxTop: Bounding box (in pixels).

// Next, you must define two functions, isElement and isHandle. These are passed
// a given DOM element, and must "return true" if the element in question is a
// draggable element or draggable handle. Here, I'm checking for the CSS classname
// of the elements, but you have have any combination of conditions you like:

dragresize.isElement = function(elm)
{
 if (elm.className && elm.className.indexOf('drsElement') > -1) return true;
};
dragresize.isHandle = function(elm)
{
 if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true;
};

// You can define optional functions that are called as elements are dragged/resized.
// Some are passed true if the source event was a resize, or false if it's a drag.
// The focus/blur events are called as handles are added/removed from an object,
// and the others are called as users drag, move and release the object's handles.
// You might use these to examine the properties of the DragResize object to sync
// other page elements, etc.

dragresize.ondragfocus = function() { };
dragresize.ondragstart = function(isResize) { };
//dragresize.ondragmove = function(isResize) { };
dragresize.ondragmove = function(isResize) { 
			objTagImgDiv = document.getElementById('divTagger'); 
			objFormDiv = document.getElementById('divTagDetails'); 
			newLeftPos = objTagImgDiv.offsetLeft + objTagImgDiv.offsetWidth;
			objFormDiv.style.left = newLeftPos+'px';
			
			newTopPos = objTagImgDiv.offsetTop+'px';
			objFormDiv.style.top = newTopPos;
};

dragresize.ondragend = function(isResize) { };
dragresize.ondragblur = function() { };

// Finally, you must apply() your DragResize object to a DOM node; all children of this
// node will then be made draggable. Here, I'm applying to the entire document.
dragresize.apply(document);

//]]>

//Java script function for showing tagger,saving tags and cancel tags
var Coordinates;
var TaggerText;
function ShowTagger(event)
{
	var ImageShowed=document.getElementById('PopUpImageOnWindow'); 
	var ImageLeft=ImageShowed.offsetLeft;
	//alert(ImageLeft);
	var pageLeft=document.getElementById('content-inner').offsetLeft;
	//ImageLeft=findPosX(ImageShowed);
	//var ImageTop=ImageShowed.offsetTop; 
	var ImageTop=findPosY(ImageShowed);
	if(event.pageX)//Mozilla  or chrome    All other browser's other than IE Will take the page left = actual page left and the left blank space  so it is a problem in wide screen  -Rinosh
	{		
		ImageLeft=ImageLeft- pageLeft;
	}
	else
	{
		ImageLeft=ImageLeft+ pageLeft;
		//ImageTop=ImageTop+200;
	}
	//alert(document.getElementById('content').offsetTop);
	//alert(document.getElementById('PopUpImageOnWindow').offsetTop);
	document.getElementById('divTagger').style.left=ImageLeft+50+"px";
	document.getElementById('divTagger').style.top=ImageTop+50+"px";
	document.getElementById('divTagger').style.width=75+"px";
	document.getElementById('divTagger').style.height=50+"px";
	//document.getElementById('divTagger').style.zindex=2000;
	document.getElementById('divTagDetails').style.left=ImageLeft+50+75+"px";
	document.getElementById('divTagDetails').style.top=ImageTop+50+"px";
	
	document.getElementById('divTagger').style.display='';
	document.getElementById('divTagDetails').style.display='';

}
function CancelTag()
{
document.getElementById('divTagger').style.display='none';
document.getElementById('divTagDetails').style.display='none';
}
function DeleteTag()
{
	document.getElementById("hdnDeleteTagId").value=document.getElementById("hdnTagId").value;
	var TagId=document.getElementById("hdnTagId").value;
	var deletePermission=confirm("Are You Want to delete this tag");
	if(deletePermission==true)
	{
		var mapArea="area"+TagId;		
		var areaToDelete=document.getElementById(mapArea);
		var map = document.getElementById("Map");
        //map.removeChild(areaToDelete);// removed in th process delete function
		var Action="Delete";
		// the following values are needed when add a tag
		var ImgId=0;
		var Coords="";
		var TagText="";
		
		var url = AjaxTagRootPath+'?ImageId='+ImgId+'&Action='+Action+'&TagId='+TagId+'&Coordinates='+Coords+'&TagText='+TagText; 
		//alert(url);
		//Server
	    //var url = 'http://www.jamesmetzger.net/wordpress/jcm/?page_id=283&ImageId='+ImgId+'&Action='+Action+'&TagId='+TagId+'&Coordinates='+Coords+'&TagText='+TagText; 
	
	    if (window.XMLHttpRequest) 
		{
			req = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}		
		req.onreadystatechange = processTagDeleteRequest;
		req.open("GET", url, true);
		req.send(null);
	}
}
function processTagDeleteRequest() 
	{	
		if (req.readyState == 4) 
		{
			
			if (req.status == 200) 
			{
				
			    ajaxPageResponse = req.responseText;				
			    var TagId=document.getElementById("hdnDeleteTagId").value;
			  	var mapArea="area"+TagId;		
				var areaToDelete=document.getElementById(mapArea);
				var map = document.getElementById("Map");
				map.removeChild(areaToDelete);
				document.getElementById('divTagPopUpMessageContainer').style.display='none';
			} else {
			  ajaxPageResponse = '';
			  alert('Tag could not be deleted. Please try again.');
			}
		}
	}
function SaveTag(event,ImgId,UserId,TeamId)
{
  var TagTextBox=document.getElementById('txtTaggerTag');  
  var hdnTaggedPersonId=document.getElementById('hdnTagSeletedPersonId');  
  if(trim(TagTextBox.value)=='')
  {
	  alert("Please Enter tag");
	  return false;
  }
  //var pageLeft=document.getElementById('content').offsetLeft;
  var pageLeft=findPosX(document.getElementById('content'));
  //alert(findPosX(document.getElementById('content')));
  var TagText=trim(TagTextBox.value);
  var TaggedPlayer=hdnTaggedPersonId.value;
  
  var ImageDiv=document.getElementById('PopUpImageOnWindow');   
  var TaggingDiv=document.getElementById('divTagger');    
   //var TagLeft=TaggingDiv.offsetLeft; 
  var TagLeft=findPosX(TaggingDiv); 
  
  var TagTop=TaggingDiv.offsetTop;
  var TagWidth=TaggingDiv.offsetWidth;
  var TagHeight=TaggingDiv.offsetHeight;   
  var ImageLeft=ImageDiv.offsetLeft;  
  var ImageDivLeft=findPosX(ImageDiv); 
  var pageOffSetLeft=document.getElementById('content').offsetLeft;
  //alert(pageOffSetLeft +" " +pageLeft+" "+TaggingDiv.offsetLeft);
  var TagLeftToSave;
  //var ImageLeft=122;
  if(event.pageX)//Mozilla  or chrome    All other browser's other than IE Will take the page left = actual page left and the left blank space  so it is a problem in wide screen  -Rinosh
	{		
		ImageLeft=ImageDiv.offsetLeft-ImageDivLeft;// now i got 125 in all wide scrrens for Mozzilla
		//TagLeft=TagLeft-pageOffSetLeft;
		var TagLeftToSave=TagLeft-findPosX(ImageDiv);//-ImageLeft;
	}
	else
	{
		ImageLeft=ImageDiv.offsetLeft+ImageDivLeft-pageLeft;// now i got 134 in all wide scrrens for IE
		//Value Needed is 125
		ImageLeft=ImageLeft-9;//for Site
		//ImageLeft=ImageLeft-3;//for local the value was 128
		//TagLeft=TagLeft-pageLeft+(TaggingDiv.offsetLeft-TagLeft);
		TagLeftToSave=TagLeft-findPosX(ImageDiv);
	}
 
  var ImageWidth=ImageDiv.offsetWidth;
  var ImageHeight=ImageDiv.offsetHeight;   
  var ImageTop=findPosY(ImageDiv);
  var TagRight=TagLeft+TagWidth;
  var TagBottom=TagTop+TagHeight;
  var ImageRight=ImageLeft+ImageWidth;
  var ImageBottom=ImageTop+ImageHeight;
  //var TagLeft=TaggingDiv.offsetLeft-TagLeft;
  
  //alert(TagLeft+" "+ImageLeft +" "+ TagWidth+" "+ImageWidth +" "+ TagTop+" "+ImageTop +" "+ TagHeight+" "+ImageHeight); 
  //alert(TagLeft+" "+ImageLeft +" "+ TagRight+" "+ImageRight +" "+ TagTop+" "+ImageTop +" "+ TagBottom+" "+ImageBottom);

  if(TagLeftToSave<=0 || TagRight>ImageRight || TagTop<ImageTop || TagBottom>ImageBottom )
  {
	    alert("Please select an area inside th image");
		return false;
  }
  else
  {
	     TagLeftToSave=TagLeftToSave-5;//For tag selections the saved point is 2 px in right in all browswer may be by border diff
		 // var TagLeftToSave=TagLeft-ImageLeft;
		  var TagWidthToSave=TagWidth;
		  var TagHeightToSave=TagHeight; 
		  var TagTopToSave= TagTop-ImageTop;
		  var TagRightToSave= TagLeftToSave+TagWidth;
		  var TagBottomToSave= TagTopToSave+TagHeight;
		  //alert(TagLeftToSave+" "+TagTopToSave+" "+TagWidthToSave+" "+TagHeightToSave);
		  //return false;
		  //var Coords=TagLeftToSave+","+TagTopToSave+","+TagWidthToSave+","+TagHeightToSave;
		   var Coords=TagLeftToSave+","+TagTopToSave+","+TagRightToSave+","+TagBottomToSave;
		  //http://www.jamesmetzger.net/wordpress/jcm/?page_id=283 pageid- Server 283   and local 300
		  var Action="Add";
		  var TagId=0;
		  //Local
		   var url = AjaxTagRootPath+'?ImageId='+ImgId+'&Action='+Action+'&TagId='+TagId+'&Coordinates='+Coords+'&TagText='+TagText+'&TaggedPlayer='+TaggedPlayer+'&userid='+UserId+'&teamid='+TeamId; 
		  
		  //alert(url);
		  
		  //var url = 'http://www.jamesmetzger.net/wordpress/jcm/?page_id=283&ImageId='+ImgId+'&Action='+Action+'&TagId='+TagId+'&Coordinates='+Coords+'&TagText='+TagText; 
		  //Old Urls
		   //var url = 'http://localhost/wordpress/jcm/?page_id=300&ImageId='+ImgId+'&Coordinates='+Coords+'&TagText='+TagText;
		   //var url = 'http://www.jamesmetzger.net/wordpress/jcm/?page_id=283&ImageId='+ImgId+'&Coordinates='+Coords+'&TagText='+TagText;
		  // this values will be used in hides tag function
		 
		  Coordinates=Coords;
		  TaggerText=TagText;
		  //Server
		   if (window.XMLHttpRequest) 
		  	{
				req = new XMLHttpRequest();
			} else if (window.ActiveXObject) {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			req.onreadystatechange = processRequest;
			req.open("GET", url, true);
			req.send(null);
		  
	}
}
	
	
	var ajaxPageResponse = '';
	var ctime = 0;
	
	function processRequest() 
	{
		if (req.readyState == 4) 
		{
			if (req.status == 200) 
			{
			    ajaxPageResponse = req.responseText;	
				var SaveResponseText=req.responseText;
				var Startloc=SaveResponseText.indexOf("SavedTagIdStart");
				var Endloc=SaveResponseText.indexOf("SavedTagIdEnd");
				Startloc=Startloc+15;
				//alert(Startloc+" "+Endloc);
				var TagId=SaveResponseText.substring(Startloc,Endloc);
				//alert(TagId);
			    hidesTag(TagId);
			  
			} else {
			  ajaxPageResponse = '';
			  alert('Tag could not be saved. Please try again.');
			}
		}
	}
  function hidesTag(TagId)
  {
	  //include current values in the area map
	   //Coordinates,TaggerText		 
	      var CurrentTags=document.getElementById('Map').innerHTML;
		  CurrentTags=CurrentTags+'<area id="area'+TagId+'" shape="rect" coords="'+Coordinates+'"  alt="'+TaggerText+'" onmouseover="hovers(event,true,'+Coordinates+',\''+TaggerText+'\','+TagId+')" onmouseout="hovers(event,false);"/>'
	      //alert(CurrentTags);
		  document.getElementById('Map').innerHTML=CurrentTags;
		  document.getElementById('txtTaggerTag').value="";
		  document.getElementById('divTagger').style.display='none';
		  document.getElementById('divTagDetails').style.display='none';
  }
function trim(str, chars) 
{
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
	{
		
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
		curleft = curleft -125;
	}
	else if(obj.x)
	{
        curleft +=  obj.x ;
	}
    return curleft;
  }
function findPosY(obj)
  {
    var curTop = 0;
    if(obj.offsetParent)
	{
		
        while(1) 
        {
          curTop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
		//curTop = curTop -125;
	}
	else if(obj.x)
	{
        curTop +=  obj.y ;
	}
    return curTop;
  }
