if(!utils) var utils={}

var userNameValid = false;
String.prototype.encode = function(){
	var str = this;
	str= str.replace(/\&/g,"&amp;");
	str= str.replace(/'/g,'&#39;');
	return str;
}
String.prototype.decode = function(){
	var str = this;
	str= str.replace(/\&amp;/g,'&');
	str= str.replace(/&#39;/g,'\'');
	
	return str;
}
String.prototype.trim = function(){
	
	var str = this;
	return str.replace(/^\s*|\s*$/g,"");
}
String.prototype.endsWith = function( substr ){
	
	var str = this;
	
	return (str.lastIndexOf( substr ) ) == (str.length - substr.length);
}
String.prototype.startsWith = function (substr){
	
	var str = this;
	
	return str.indexOf(substr) ==0;
}
String.prototype.isEmpty = function (){
	
	var str = this;
	
	return str.trim() == "" || trim(str) == "";
}
String.prototype.notEmpty = function (){
	
	return !this.isEmpty();
}
/**
 * ignores case
 * 
 */
Array.prototype.contains = function( str )
{
	var tempArray = this;
	
	for(var index=0; index<tempArray.length; index++) {
			
		if( tempArray[index].toLowerCase() ==  str.toLowerCase() )
			return true;
	}
	return false;
}

var ratedMovie = true;
var discoveryCode = null; //for use in amall discover box
/**************** objects ******************/
function Point()
{
	this.x =0;
	this.y =0;
	function print()
	{
		alert(x +","+y);
	}
}
function Line()
{
	this.y = 0;
	this.x = 0;
	this.b = 0;
	this.a = 0;
	
	
}

/********** parameters for the discovery menus *************/
var discoveryShow = false;
var discoveryMenuItem1 = document.getElementById('back_discLink');
var discoveryMenuItem2 = document.getElementById('sortby_menu');
var discoveryMenuItem3 = document.getElementById('taste_menu');

/*************** global parameters ***********/
var departurePoint = new Point();
var destinationPoint = new Point();
var leg = new Line();
var pilot;
var flyingSpeed = 5;
var textToAdd;
var expandedReview;
/********************************************/
function getKeyboard( e )
{
	var charKey = 0;
	if ( !e ) e = window.event;
	if ( e.keyCode ) charKey = e.keyCode;
	else if ( e.which ) charKey = e.which;
	return charKey;
	
}
utils.getKeyboard = function (event)
{
	return getKeyboard( event );
}
function doMainUnload()
{
	var url = document.location.href;
	var page = "";
	
	if(url.indexOf("discovery")>-1) page="discovery";
	
	
	if(page == 'discovery')
	{
		resetTasteSliders();
		
	}
	
	
	
}
function trim(str)
{
	return str.replace(/^\s+|\s+$/g,"");
}

String.prototype.trim = function(){ this.replace(/^\s+|\s+$/g,""); };

function getPosX(obj)
{
	var curleft = 0;
	while (obj.offsetParent)
	{
	  curleft += obj.offsetLeft;
	  obj = obj.offsetParent;
	}
	return curleft;

}
function getPosY(obj)
{
	var curtop = 0;
	while (obj.offsetParent)
	{
	  curtop += obj.offsetTop;
	  obj = obj.offsetParent;
	}
	return curtop;

}

/********* show Menu Floating Div ***********/
function showMenu(objLink,obj) {
	var menuLink = obj;
	objLink.style.left = getPosX(menuLink) - 10 + "px";
	objLink.style.top  = getPosY(menuLink) + 14 + "px";
	objLink.style.display = 'inline';
}

function discoveryMenuClick( e ){
	if ( !e )
  	{
  	  	e = window.event;
  	}
	var item;
  	if ( e.target ) 
	{
  		item = e.target;
	}
  	else if ( e.srcElement ) 
	{
  		item = e.srcElement;
	}
	if ( item.nodeType == 3 ) // defeat Safari bug
	{
		item = item.parentNode;
	}
	// activates the HIstory menu
	if ( item.innerHTML.indexOf('History') != -1 ) 
	{
		if ( discoveryShow == false  )
		{
			showMenu(document.getElementById('back_discLink'),item);
			discoveryShow = true;
			return;
		}
		else if ( discoveryShow == true )
		{
			hide(document.getElementById('back_discLink'));
			discoveryShow = false;
			return;
		}
	}		
		
	// activates the sort by menu
	if ( item.innerHTML == "relevancy" || item.innerHTML == "date" || item.innerHTML == "length" || item.innerHTML == "rating" )
	{ 
		if ( discoveryShow == false )			
		{
			showMenu(document.getElementById('sortby_menu'),item);
			discoveryShow = true;
			return;
		}
		else if ( discoveryShow == true )
		{
			hide(document.getElementById('sortby_menu'));
			discoveryShow = false;
		}
	}
		
	// activates the scales menu
	if ( item.innerHTML == "Story Tuners" )
	{
		if ( discoveryShow == false )
		{
			showTasteScales(document.getElementById('taste_menu'),item);
			initThinSliders(document.getElementById('taste_menu'));
			discoveryShow = true;
			return;
		}
		else if ( discoveryShow == true ) 
		{
			hide(document.getElementById('taste_menu'));
			discoveryShow = false;
			return;
		}
	}
}
function closeDiscoveryPops(){
	var discoveryMenuItem1 = document.getElementById('back_discLink');
	var discoveryMenuItem2 = document.getElementById('sortby_menu');
	var discoveryMenuItem3 = document.getElementById('taste_menu');
	for ( x=1; x<=3; x++){
		//alert("discoveryMenuItem" + x );
		//alert(eval("discoveryMenuItem" + x ));
		//alert(document.getElementById( "discoveryMenuItem" + x ));
		//document.body.onclick = hide(eval("discoveryMenuItem" + x ));
		if ( eval("discoveryMenuItem" + x ).style.display == 'inline' )
		{
			hide( eval("discoveryMenuItem" + x ));	
		}
	}
}

function showTasteScales(objLink,obj) {
	var menuLink = obj;
	objLink.style.left = getPosX(menuLink) - 231 + "px";
    objLink.style.top  = getPosY(menuLink) + 14 + "px";
    objLink.style.display = 'inline';
}
/********* Hide Menu Floating Div **********/
function hide(obj) {
	if(obj){
		obj.style.display = 'none';
		discoveryShow = false;
	}
}

/********** color linked text ***************/
function hoverText(obj) {
	var myObject = obj;
	myObject.style.color = '#cd3301';
	myObject.style.cursor = 'pointer';
}

function unHoverText(obj) {
	var myObject = obj;
	myObject.style.color = '#000000';
	myObject.style.cursor = 'default';
}
/**/

/******** bottom links of collage floating div and the content details ********/

function botStripOver(prevObj,obj) {
	prevObj.style.background = '#cd3301';
	obj.style.color = '#ffffff'; 
}

function botStripOut(prevObj,obj) {
	prevObj.style.background = '#c7d47d';
	obj.style.color = '#676767';
}
/***  hide the vote div  ***/

function hideVoteDiv() {
	var vote = document.getElementById('suggestedVote');
	if( vote.style.display == 'block' ){
		vote.style.display = 'none';
	}
}

/**** the image buttons activation ****/

function imgButtonOn(obj) {
	obj.style.backgroundColor = '#F0F6D2';
	obj.style.cursor = 'pointer';
}
function imgButtonOff(obj) {
	obj.style.backgroundColor = 'transparent';
}
/***								***/
////////////// this function for collage rollover container //////////////

//////

function SimilarMoviesAction(obj) {
	var floatingDiv = obj;
	document.getElementById('SimilarMovieRODiv').style.left = getPosX(floatingDiv) - 10 + 'px';
    document.getElementById('SimilarMovieRODiv').style.top  = getPosY(floatingDiv) - 10 + 'px';
	document.getElementById('SimilarMovieRODiv').style.padding = 10 + 'px' ; 
	document.getElementById('SimilarMovieRODiv').style.display = 'inline';
}

function HideContentSimilarDiv() {
	document.getElementById('SimilarMovieRODiv').style.display = 'none';
}
//////

function changeCaptcha(imageId,url){
	randUrl = url+'?rand='+Math.random();
	document.getElementById(imageId).src = randUrl ;
}


function isValidUsername(){
	
	var inputText = document.getElementById('registrationForm:usernameInput');	
	var htmlItem = document.getElementById('userNameMsg');
	
	if ( inputText.value == "" ){
		 htmlItem.innerHTML = 'Username please';
		 inputText.className = 'theInputBox invalid';
		 return false;
	}
	if ( (inputText.value).length < 3 ){
		 htmlItem.innerHTML = 'Enter 3-15 chars';
		 inputText.className = 'theInputBox invalid';
		 return false;
	}
	if ( !((inputText.value).match(/ [A-Z]|[a-z]|[0-9]|[_]|[.] /)) ) {
		 htmlItem.innerHTML = 'Use letters & numbers';
		 inputText.className = 'theInputBox invalid';
		 return false;
	}	
	
}

function userNameBlur(){ 

	var inputText = document.getElementById('registrationForm:usernameInput');	
	var htmlItem = document.getElementById('userNameMsg');
	
	
	AjaxController.verifyUserName( inputText.value , function(data) {
		//remove old messages
		//htmlItem = document.getElementById(htmlItemId);
    	var kids = htmlItem.childNodes;   
    	var numkids = kids.length; 
    	for(var i = numkids-1; i >= 0; i--) {  
        	htmlItem.removeChild(kids[i]);                  
    	}
    	//check if we got error
		if( data == null || data == ""){
			newImg = document.createElement("img");
			newImg.src = imgUrl ;
			htmlItem.appendChild(newImg);
			inputText.className = 'theInputBox valid';
			userNameValid = true;
			return;
		}
		//append the error text to the table
    	//newitem = document.createElement("SPAN");
    	text = document.createTextNode(data);
    	htmlItem.appendChild(text);
    	inputText.className = 'theInputBox invalid';
    	
  	});
  	
}

function checkRegistrationMail() { 
	var inputText = document.getElementById('registrationForm:emailInput');	
	var htmlItem = document.getElementById('emailValidationMsg');
	
    var kids = htmlItem.childNodes;   
    var numkids = kids.length; 
    for(var i = numkids-1; i >= 0; i--) {  
       	htmlItem.removeChild(kids[i]);                  
    }
	var et = inputText.value.indexOf('@');
	var dot = inputText.value.lastIndexOf('.');
	if (et > 0 && dot > 0 && dot > et && dot < (inputText.value.length-2)) {
		newImg = document.createElement("img");
		newImg.src = imgUrl ;
		htmlItem.appendChild(newImg);
		inputText.className = 'theInputBox valid';
		return true;
	}
	else if ( inputText.value == '' ){
		htmlItem.innerHTML = 'Email please';
		inputText.className = 'theInputBox invalid';
		return false;
	}
	else
	{
		htmlItem.innerHTML = 'Invalid email';
		inputText.className = 'theInputBox invalid';
		return false;
	}	
}

function checkPasswordEnter(){ 
	var inputText = document.getElementById('registrationForm:passwordInput');	
	var htmlItem = document.getElementById('passwordEnterMsg');
    var kids = htmlItem.childNodes;   
    var numkids = kids.length; 
    for(var i = numkids-1; i >= 0; i--) {  
       	htmlItem.removeChild(kids[i]);                  
    }
    if ((inputText.value).length > 0 && (inputText.value).length < 4 )
	{
		htmlItem.innerHTML = '4 characters min.';
		inputText.className = 'theInputBox invalid';
		return false;
	}
	else if ( inputText.value != '' ) {
		newImg = document.createElement("img");
		newImg.src = imgUrl ;
		htmlItem.appendChild(newImg);
		inputText.className = 'theInputBox valid';
		return true;
	} 
	else
	{
		htmlItem.innerHTML = 'Password please';
		inputText.className = 'theInputBox invalid';
		return false;
	}	
}

function checkPasswordConfirmation(){
	var inputText = document.getElementById('registrationForm:confitrmPasswordInput');	
	var htmlItem = document.getElementById('passworConfirmationMsg');
	var pass = document.getElementById('registrationForm:passwordInput');
    var kids = htmlItem.childNodes;   
    var numkids = kids.length; 
    for(var i = numkids-1; i >= 0; i--) {  
       	htmlItem.removeChild(kids[i]);                  
    }
	if ( inputText.value != pass.value ) {
		htmlItem.innerHTML = "Doesn't match";	
		inputText.className = 'theInputBox invalid';
		return false;
	} 
	else if ( inputText.value == '' ) {
		htmlItem.innerHTML = "Password please";
		inputText.className = 'theInputBox invalid';
		return false;
	}
	else
	{
		newImg = document.createElement("img");
		newImg.src = imgUrl ;
		htmlItem.appendChild(newImg);
		inputText.className = 'theInputBox valid';
		return true;
	}	
}

function ageCheck(){ 	
	var htmlItem = document.getElementById('ageMsg');
	var inputAge = document.getElementById('registrationForm:over13Input');
	
	
	if ( inputAge.checked == true ) {
		htmlItem.innerHTML = "<img src="+ imgUrl +">";
		return true;
	}
	else
	{
		htmlItem.innerHTML = "Must be over 13";
		return false;
	}
}

function tcCheck(){ 	
	var htmlItem = document.getElementById('termsMsg');
	var inputtc = document.getElementById('registrationForm:agreeToTermsInput');
	
	if ( inputtc.checked == true ) {
		htmlItem.innerHTML = "<img src="+ imgUrl +">";
		return true;
	}
	else
	{
		htmlItem.innerHTML = "Must agree";
		return false;
	}
}

function formValidation(){
	var bazooka = "";
	bazooka += isValidUsername();
	bazooka += checkRegistrationMail();
	bazooka += checkPasswordEnter();
  	bazooka += checkPasswordConfirmation();
  	//bazooka += checkRegZip();
  	bazooka += ageCheck();
  	bazooka += tcCheck();
  	
  	if ( bazooka.indexOf("false") < 0  ){
  		return true;
  	}
  	return false;
}

function checkRegistraionStatus(){

	htmlHidden = document.getElementById('registrationForm:resistrationStatus');
	if( htmlHidden.value == 'true' ){
		alert( 'Haim show the div' );
	}
}

////// Content review componenet expand
function expandReviewBox(index)
{
	if(expandedReview != undefined ) 
		hideReviewBox(expandedReview)
	
	expandedReview = index;
	
	document.getElementById('expended'+index).style.display = "block" ;
	document.getElementById('preview'+index).style.display = "none" ;
}

function hideReviewBox(index)
{
	document.getElementById('expended'+index).style.display = "none" ;
	document.getElementById('preview'+index).style.display = "block" ;
}

//save the scroll possitin
function saveScrollCoordinates(formId) {
	scrollx = document.getElementById(formId+':scrollx');
	scrolly = document.getElementById(formId+':scrolly');
	
	scrollx.value = (document.all)?document.body.scrollLeft:window.pageXOffset;
	scrolly.value = (document.all)?document.body.scrollTop:window.pageYOffset;
}

function scrollToCoordinates(formId) {
  scrollx = document.getElementById(formId+':scrollx');
  scrolly = document.getElementById(formId+':scrolly');
  window.scrollTo(scrollx.value, scrolly.value);
  
} 

//update filter status
function saveFilterValue(filterValue) {
	filter = document.getElementById('reviewsForm:filter');
	filter.value = filterValue;
}

// add to favorites
//function addToFavorites(){

//	var url = location.href ;
//	var title = 'Jinni - ' + document.title ;
	
//	if (window.sidebar) { // Mozilla Firefox Bookmark
//		window.sidebar.addPanel( title, url,"" );
		
//	} else if( window.external ) { // IE Favorite
//		window.external.AddFavorite( url, title); }
		
//	else if(window.opera && window.print) { // Opera Hotlist
//		return true; 
//	}
//}

//// slider functionality

//// end slider functionality


function getImagePath(content,imageType)
{
	
	switch (imageType) {
		
		case ImageType.RELATED_MOVIES:
			 
			 if(content.availableImage == true)
			 {
			 	return collageImagePath + (content.contentType=='FeatureFilm'?'movie/':content.contentType=='TvSeries'?'tv/':'short-film/') + content.unqiueName + "/" + content.unqiueName + "-4.jpeg";	
			 }
			 else
			 {
			 	return noImagePath;
			 }
			
			break;

		default:
			break;
	}

}

function getContentPagePath(content)
{
	
	switch (content.contentType) {
		
		case "FeatureFilm":
			return "movies/" + content.unqiueName;
		break;
		
		case "TvSeries":
				return "tv/" + content.unqiueName;
		break;

		case "ShortFilm":
				return "shorts/" + content.unqiueName;
		break;

		default:
			break;
	}

}

function getContentImageBasePath(contentTypeString)
{
	var basePath = null;
	
	switch ( contentTypeString ) {
		
		case "FeatureFilm":
			basePath = "movie/";
		break;
		
		case "TvSeries":
			basePath = "tv/";
		break;

		case "ShortFilm":
			basePath = "shorts/";
		break;

		default:
			basePath = "movies";
			break;
	}

	return basePath;
}

function ImageType()
{
	this.RELATED_MOVIES = "relatedMovies";
}

var addToWishListPressed = false ;
function addCurrentToWishList(){

		if( addToWishListPressed == true ) return ;
		addToWishListPressed = true ;
		
		AjaxUserFavorites.addCurrentToWishList( function(data) {
		var wishlistDiv = document.getElementById('wishlist');
		var popup = document.getElementById('addToWishlistToolTip');
		var span = document.getElementById('addToWishlistReply');
    	//check if we got error
		span.innerHTML = data ;
		popup.style.top  = getPosY(wishlistDiv) - 30 + "px";
		popup.style.left  = getPosX(wishlistDiv) - 30 + "px";
		popup.style.display = 'block' ;
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
		addToWishListPressed = false ;
  	});
}

var addContentToWishListPressed = false ;
function addContentToWishList(rollOverId){
		if( addContentToWishListPressed == true ) return ;
		if( generalFunctions.goToPrivatePage() == false) return;
		
		addContentToWishListPressed = true ;
		
		AjaxUserFavorites.addContentToWishList( discoveryCurrentContentId , function(data) {
			
			var wishlistDiv = document.getElementById('botLinkDivA');
			var popup = document.getElementById('addToWishlistToolTip');
			var span = document.getElementById('addToWishlistReply');
	    	//check if we got error
			span.innerHTML = data ;
			
			if(rollOverId != undefined )
			{
				if (rollOverId == 'collage_ro'){
					
						popup.style.top  = (getPosY(document.getElementById(rollOverId)) + 211 ) + "px";
						popup.style.left  = (getPosX(document.getElementById(rollOverId)) + 348 ) + "px";
						//alert(popup.style.left+ ", " + popup.style.top );
					}
					else if(rollOverId == 'listRollover')
					{ 
						//alert(parseInt(document.getElementById(rollOverId).style.top) + ", " + document.getElementById(rollOverId).clientHeight);
						popup.style.top  = ( parseInt(document.getElementById(rollOverId).style.top) + document.getElementById(rollOverId).clientHeight - 60) + "px";
						popup.style.left  = (getPosX(document.getElementById(rollOverId)) + 286 ) + "px";	
					}
			}
			else
			{
				popup.style.top  = "-50px";
				//popup.style.left  = getPosX(wishlistDiv) - 30 + "px";
			}
			popup.style.display = 'block' ;
			window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
			addContentToWishListPressed = false ;
  	});
}


var addToFavoritePressed = false ;

function addContentToFavorites(){
		if( addToFavoritePressed == true ) return;
		addToFavoritePressed = true;
		AjaxUserFavorites.addCurrentToFavorite( function(data) {
		var favoritesDiv = document.getElementById('favorite');
		var popup = document.getElementById('addToFavoritesToolTip');
		var span = document.getElementById('addToFavoriteReply');
    	//check if we got error
		span.innerHTML = data ;
		popup.style.top  = getPosY(favoritesDiv) - 30 + "px";
		popup.style.left  = getPosX(favoritesDiv) - 30 + "px";
		popup.style.display = 'block' ;
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
		addToFavoritePressed = false ;
  	});
}

function addCollageContentToFavorites(){
		if( addToFavoritePressed == true ) return;
		if( generalFunctions.goToPrivatePage() == false) return;
		addToFavoritePressed = true;
		AjaxUserFavorites.addToFavorite(discoveryCurrentContentId, function(data) {
		var favoritesDiv = document.getElementById('favorite');
		var popup = document.getElementById('addToWishlistToolTip');
		var span = document.getElementById('addToWishlistReply');
    	
		span.innerHTML = data ;
    	
		popup.style.top  = getPosY(favoritesDiv) - 30 + "px";
		popup.style.left  = getPosX(favoritesDiv) - 30 + "px";
		//alert(popup.style.left + ', ' + popup.style.top);
		popup.style.display = 'block' ;
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
		addToFavoritePressed = false ;
  	});
}



var canRate = true ;
function submitUserRating(rateValue,sId){
	AjaxUserRatingBean.submiteUserRating( parseInt(rateValue), {
	
		callback: function(data) { userRatingHandler(sId , data); },
		errorHandler: 	generalFunctions.handleAjaxServerErrors
		
		}
  	);
}

function saveRateForContent(rate, sliderContainerID){
	AjaxUserRatingBean.submiteContentUserRating( discoveryCurrentContentId , rate, {
	
		callback:		function(data) {userRatingHandler(data, sliderContainerID);},
		errorHandler: 	generalFunctions.handleAjaxServerErrors
		
		}
	);
}

function saveUserRating( rate, sliderContainerID )
{
	AjaxUserRatingBean.submiteUserRating( parseInt(rate), {
	
		callback: function(data) { userRatingHandler(data, sliderContainerID); },
		errorHandler: 	generalFunctions.handleAjaxServerErrors
		
		}
  	);
	
}

function userRatingHandler(data, sliderContainerID){

	var sliderDiv = document.getElementById(sliderContainerID);
	var popup = document.getElementById('addToWishlistToolTip');
	var span = document.getElementById('addToWishlistReply');

	span.innerHTML = data ;
	var popupTop  = getPosY(sliderDiv) - 30 ;
	var popupLeft  = getPosX(sliderDiv) + 30 ;
	
	popup.style.top  = popupTop + "px";
	popup.style.left = popupLeft + "px";
	popup.style.display = 'block' ;
	
	window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
}

function showToolTip(trigger,obj){
	
		var toolTipTrigger = obj;
		var popup = document.getElementById('rollOverToolTip');
		var toolTipText = document.getElementById('toolTipText');
	
		switch (trigger){
			
			case "homeRO":
				toolTipText.innerHTML = obj.name ;
				popup.style.top  = getPosY(toolTipTrigger) - 30 + "px";
				popup.style.left  = getPosX(toolTipTrigger) + 30 + "px";
				popup.style.display = 'block' ;
		}
	
		
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);

  
}

function fadeTooltipDiv(popup, currentOpacity) {
	currentOpacity -= 5;
  	if (currentOpacity < 0) {
  		popup.style.display = 'none' ;
    	setTooltipDivOpacity(popup, 100);
    	return 1;
  	}
  	else {
    	setTooltipDivOpacity(popup, currentOpacity);
    	window.setTimeout(function() { fadeTooltipDiv(popup, currentOpacity); }, 45);
  	}

	
}

//function fadeInTooltipDiv(popup, currentOpacity) {
//	currentOpacity += 5;
//  	if (currentOpacity > 100) {
//  		popup.style.display = 'block' ;
//    	setTooltipDivOpacity(popup, 100);
//  	}
//  	else {
//    	setTooltipDivOpacity(popup, currentOpacity);
//    	window.setTimeout(function() { fadeTooltipDiv(popup, currentOpacity); }, 45);
//  	}
//}

function setTooltipDivOpacity(el, opacity) {
	opacity /= 100;
	el.style.opacity = opacity;
	el.style.MozOpacity = opacity;
	el.style.filter = "alpha(opacity=" + (opacity*100) + ")";
}

var tmpLessCategories ;
function showMoreCategories(spanMoreId,spanMoreCategoriesId){
	tmpLessCategories = document.getElementById(spanMoreId).innerHTML ;
	document.getElementById(spanMoreId).innerHTML = document.getElementById(spanMoreCategoriesId).innerHTML;
}

function showLessCategories(spanMoreId){
	document.getElementById(spanMoreId).innerHTML = tmpLessCategories ;
}

var selectedCategory ;
var selectedCategoryName ;
var selectedCategoryGroup ;
function setSelectedCategory(categoryId,categoryName,categoryGroup){
	selectedCategory = categoryId ;
	selectedCategoryName = categoryName ; 
	selectedCategoryGroup = categoryGroup ;
}   

//enables the user to search for category related titles
function searchCategoryRelatedTitles () {
	searchByMovieGene(selectedCategoryName,selectedCategoryGroup,selectedCategory,"G");
}

//enables the user to vote (1/0)
function contentCategoryVote( vote ){
	clearLastVoteResult();
	AjaxContentCategoryVote.contentCategoryVote( selectedCategory , vote , function(data) {
		if( (data.positiveVotes + data.negativeVotes) != 0 ){
			var sumVotes = data.positiveVotes + data.negativeVotes;
			var positivePercentage = (data.positiveVotes/sumVotes)*100;
			var negativePercentage = (data.negativeVotes/sumVotes)*100;
			document.getElementById('voteSoFar').innerHTML = 'Votes so far:';
			document.getElementById('numOfYesVotes').innerHTML = Math.round(positivePercentage) + '%' + ' - Just right';
			document.getElementById('numOfNoVotes').innerHTML = Math.round(negativePercentage) + '%' + ' - Nope';
			document.getElementById('voteResult').innerHTML = '';
			document.getElementById('numOfVotes').style.display = 'block' ;
			document.getElementById('voteResult').style.display = 'none';
		}else{
			document.getElementById('voteResult').innerHTML = data.status;
			document.getElementById('numOfVotes').style.display = 'none' ;
			document.getElementById('voteResult').style.display = 'block';
		}
		
  	});
}

function clearLastVoteResult(){
	document.getElementById('voteSoFar').innerHTML = '';
	document.getElementById('numOfYesVotes').innerHTML = ' ';
	document.getElementById('numOfNoVotes').innerHTML = ' ';
	document.getElementById('numOfVotes').style.display = 'none' ;
	document.getElementById('voteResult').innerHTML = ' ';
	document.getElementById('voteResult').style.display = 'none';
}

function hideCategoryVotePanels(){
	hide(document.getElementById('suggestedVote')); 
	hide(document.getElementById('VoteGeneMenu')); 
	hide(document.getElementById('votedUsers')) ;
}

function contentReviewVote( reviewId ,vote, posObj ){
	
	if(generalFunctions.goToPrivatePage() == false) return;
	
	AjaxController.contentReviewVote( reviewId ,vote, function(data) {
		var voteDiv = document.getElementById('contentReviewVote'+reviewId);
		var popup = document.getElementById('contentReviewVoteToolTip'+reviewId);
		var span = document.getElementById('contentReviewVoteReply'+reviewId);
		
    	var thumbsUp = data.thumbsUpPercentage + "%";
    	var thumbsDown = data.thubmsDownPercenteage + "%";
    	
    	try{
    		
    		if( data.thumbsUpPercentage != null &&  data.thubmsDownPercenteage != null)
    		{
	    		document.getElementById('thumbsUp-' + reviewId).innerHTML = thumbsUp;
	    		document.getElementById('thumbsDown-' + reviewId) = thumbsDown;
    		}
    	}
    	catch(e){}
    	
		span.innerHTML = data.message ;
		popup.style.top  = getPosY(posObj) - 30 + "px";
		popup.style.left  = getPosX(posObj) - 27 + "px";
		popup.style.display = 'block' ;
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
//		window.setTimeout(function() { canRate = true ; }, 2000);
  	});
}

function relatedMoviestooltip(obj,movieName){

		var popup = document.getElementById('rollOverToolTip');
		var span = document.getElementById('toolTipText');
		
    	//check if we got error
		span.innerHTML = movieName ;
		popup.style.top  = getPosY(obj) - 28  + "px";
		popup.style.left  = getPosX(obj) - 15  + "px";
		popup.style.display = 'block' ;
		//window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
}

function reviewReportAbuse( reviewId ){
	
	
	if( generalFunctions.goToPrivatePage() == false) return;
	
	AjaxController.contentReviewReportAbuse( reviewId , function(data) {
		var reportDiv = document.getElementById('spanReportAbuse'+reviewId);
		var popup = document.getElementById('reviewReportAbuseToolTip'+reviewId);
		var span = document.getElementById('reviewReportAbuseReply'+reviewId);
		
    	//check if we got error
		span.innerHTML = data ;
		popup.style.top  = getPosY(reportDiv) - 25 + "px";
		popup.style.left  = getPosX(reportDiv) + "px";
		popup.style.display = 'block' ;
		window.setTimeout(function() { fadeTooltipDiv(popup, 100); }, 2000);
//		window.setTimeout(function() { canRate = true ; }, 2000);
  	});
}

/****  user preferences   ****/

function trOver(obj) {
	obj.style.color='#cd3301'; 
	obj.parentNode.style.cursor='arrow';
	obj.style.fontWeight = 'bold';
}

function trOut(obj, cbx) {
	if (cbx.checked==false){
		obj.style.fontWeight='normal'; 
		obj.style.color='#676767'; 
	}
	else{
		obj.style.fontWeight='bold'; 
		obj.style.color='#cd3301'; 
	}
}

function trClick(obj, cbx) {
	
	if (cbx.checked==true){
		obj.parentNode.style.backgroundColor='#F0F6D2';
		obj.style.fontWeight='bold';
		obj.style.color='#cd3301'; 
	}
	else
	{
		obj.parentNode.style.backgroundColor='#ffffff';
		obj.style.fontWeight='normal';
		obj.style.color='#676767';
	}
}

function initDiscoverySlider(){
	AjaxUserRatingBean.getContentRating(discoveryCurrentContentId , {
	
	callback: function(rate) {
		
		document.getElementById('sliderTableDR').style.visibility = "visible";
		
		if ( rate.rated )
		{
			ratedMovie = true;
			document.getElementById('sliderMatchTitleDR').innerHTML = 'Your Rating:' ;
			document.getElementById('sliderMatchTitleDR').style.color = "#676767";
			document.getElementById('sliderTableDR').className = 'sliderClass' ;
			document.getElementById('sliderValueNameDR').style.display = 'inline';
			document.getElementById('rate_noticeDR').style.color = "#676767";
			document.getElementById('rate_noticeDR').innerHTML = '';
			document.getElementById('ratingSliderDivDR').style.borderColor = '#cd3301';
			document.getElementById('whatIsThisDR').style.display = 'none';
			document.getElementById('sliderMaskDR').style.backgroundImage = "url('" + imagePath + "sliderleft.gif')";
			document.getElementById('sliderBarDR').style.backgroundImage = "url('" + imagePath + "sliderright.gif')";
			document.getElementById('sliderRubishDR').src = imagePath + "24_rubish_red.gif";
			document.getElementById('sliderOscarDR').src = imagePath + "24_Oscar_red.gif";
			document.getElementById('knobImageDR').src = imagePath + "knob.gif";
			setNotSeenIt();
		}
		else if ( rate.suggested )
		{
			ratedMovie = true;
			document.getElementById('sliderMatchTitleDR').innerHTML = 'Your Match:' ;
			document.getElementById('sliderMatchTitleDR').style.color = "#696969";
			document.getElementById('sliderValueNameDR').style.display = 'inline';
			document.getElementById('rate_noticeDR').style.color = "#cd3301";
			document.getElementById('rate_noticeDR').innerHTML = 'Seen it? Rate it!';
			document.getElementById('ratingSliderDivDR').style.borderColor = '#579482';
			document.getElementById('whatIsThisDR').style.display = 'inline';
			document.getElementById('sliderMaskDR').style.backgroundImage = "url('" + imagePath + "sliderleft_turq.gif')";
			document.getElementById('sliderBarDR').style.backgroundImage = "url('" + imagePath + "sliderright_turq.gif')";
			document.getElementById('sliderRubishDR').src = imagePath + "24_rubish_turquois.gif";
			document.getElementById('sliderOscarDR').src = imagePath + "24_Oscar_turquois.gif";
			document.getElementById('knobImageDR').src = imagePath + "knob_turquois.gif";
			if ( rate.likelyOrNotInterested == null )
			{
				setNotSeenIt();
			}
			else if ( rate.likelyOrNotInterested )
			{
				showLikelyToSee();
			}
			else
			{
				showNotForMe();
			}
		}
		else
		{
			ratedMovie = false;
			document.getElementById('sliderMatchTitleDR').innerHTML = 'Rate this title';
			document.getElementById('sliderMatchTitleDR').style.color = "#cd3301";
			document.getElementById('sliderValueNameDR').style.display = 'none';
			document.getElementById('rate_noticeDR').style.color = "#cd3301";
			document.getElementById('rate_noticeDR').innerHTML = '';
			document.getElementById('ratingSliderDivDR').style.borderColor = '#cd3301';
			document.getElementById('whatIsThisDR').style.display = 'none';
			document.getElementById('sliderMaskDR').style.backgroundImage = "url('" + imagePath + "sliderleft.gif')";
			document.getElementById('sliderBarDR').style.backgroundImage = "url('" + imagePath + "sliderright.gif')";
			document.getElementById('sliderRubishDR').src = imagePath + "24_rubish_red.gif";
			document.getElementById('sliderOscarDR').src = imagePath + "24_Oscar_red.gif";
			document.getElementById('knobImageDR').src = imagePath + "knob.gif";
			if ( rate.likelyOrNotInterested == null )
			{
				setNotSeenIt();
			}
			else if ( rate.likelyOrNotInterested )
			{
				showLikelyToSee();
			}
			else
			{
				showNotForMe();
			}
		}
		document.getElementById('sliderInitialValueDR').value = rate.rate;
		initialzeSliderDR();
		
  	},
  	
  		errorHandler: generalFunctions.handleAjaxServerErrors
  		
	}
  	);
}

function updateSliderTableClass(sliderTable,sId){
	if (document.getElementById('sliderMatchTitle'+sId).innerHTML == 'Your Match:' ){
		sliderTable.className = 'sliderClassDimmed' ;
	}
}

function seeAll(link){
	if( document.getElementById('seeMore').style.display == 'none' ){
		link.innerHTML = 'See less' ;
		document.getElementById('seeMore').style.display = 'block';
	}else{
		link.innerHTML = 'See all' ;
		document.getElementById('seeMore').style.display = 'none';
	}
}

function seeMoreDiv(link,moreDivId){
	if( document.getElementById(moreDivId).style.display == 'none' ){
		link.innerHTML = 'See less' ;
		document.getElementById(moreDivId).style.display = 'block';
	}else{
		link.innerHTML = 'See all' ;
		document.getElementById(moreDivId).style.display = 'none';
	}
}

function findSimilarClick(movieName)
{
	if(document.getElementById('collage_ro'))
		document.getElementById('collage_ro').style.display = 'none';
	
	if(movieName != undefined) findSimilarTo = movieName;
	else findSimilarTo = moreLikeItTitle;
	if(discoveryCode != undefined && discoveryCode != null && discoveryCode != "")
	{
		document.cookie = "similar=" + findSimilarTo + "; path=/";
		document.getElementById('discoveryCode').value = discoveryCode; 
		addToSearchShowSimilar(findSimilarTo,discoveryCode);
		
//		findSimilarTo = movieName;
		//document.getElementById('showSimilarForm').submit();
		
	}
}
function addToSearchShowSimilar(searchPhrase,id)
{
	cleanearchBox();
	searchPhrase = searchPhrase.decode();
	addToSearchBox("Like: " + searchPhrase,'Similar Titles',id,'TS')
	doSearch();
	
}
function doSearch()
{
	if(!isAnythingInSearchBox()) return;
	
	document.getElementById("searchCriteria").value = "";
//	document.getElementById("searchCriteria").value = document.getElementById("txt").innerHTML;
	
	
	var searchString = document.getElementById("searchInput").value;
	
  	SearchFilter.globalFilter = document.getElementById('globalFilter').value;
  	SearchFilter.searchFilter = document.getElementById('searchFilter').value;
  	SearchFilter.tasteFilter = TasteFilter;
	SearchFilter.searchType = searchTypeDropState;
  	
  	
  	if(SearchFilter.globalFilter == "") SearchFilter.globalFilter = "All";
  	
  	SearchBean.searchFilter = SearchFilter;

  	// rebuild the search string, replacing the terms with their IDs
  	
	
  	SearchBean.userSearchPhrase = getSearchCode( searchString );
  	
  	  	
  	saveSearchCookie();
  	newSearch = true;
  	setSessionCookie("page","-1");
  	
  	if(document.location.href.indexOf("discovery")<0)
  	{
  		AjaxController.searchWithNoResponse(SearchBean, collageSort, {
  		
  			callback:		handleResult,
  			errorHandler: 	generalFunctions.handleAjaxServerErrors
  			
  		});
  	}
  	else
	{
	  	AjaxController.Search(SearchBean, collageSort, {
	  		
	  		callback:		handleResult,
  			errorHandler: 	generalFunctions.handleAjaxServerErrors
	  		
	  	});
	}
	//document.getElementById('searchForm').submit();
	displayCollagePreload();
	return false;
	
}
function getSearchCode( searchString )
{
	for ( var i = 0; i < searchBoxData.length; i++ )
  	{
  		var regExpStr = searchBoxData[i].displayName.replace(/([\(\)\[\]\\\+\*\:\^\$\.])/g,"\\$1"); //escape regex characters
  		searchString = searchString.replace( new RegExp( regExpStr, "ig" ), "" );
  		if ( searchBoxData[i].itemId.match( /^\[\d+\]TS$/ ) )
  		{
  			searchString = searchString.replace( /like:\s*/i, "" );
  			searchBoxData[i].type = "Similar Titles";
  			if ( searchBoxData[i].displayName.match(/^\s*like.+/i) )
  			{
  				searchBoxData[i].displayName = trim( searchBoxData[i].displayName );
  			}
  			else
  			{
  				searchBoxData[i].displayName = "Like: " + trim( searchBoxData[i].displayName );
  			}
  			searchBoxData[i].start = 0;
  			searchBoxData[i].end = searchBoxData[i].displayName.length;
  		}
  	} 
  	for ( var i = 0; i < searchBoxData.length; i++ )
  	{
  		searchString += "@#@" + searchBoxData[i].displayName + "-" + searchBoxData[i].itemId;
	}
	
	return searchString;
}
function handleResult(searchResponse)
{
	if(searchResponse!=null && searchResponse.results.length ==1)
	{
		document.location.href = "/movies/" + searchResponse.results[0].content.unqiueName;
		return;
	}
	else if(document.location.href.indexOf("discovery")<0)
	{
		setSessionCookie("page",-1);
		document.location.href = "/discovery.html";
		return;
	}
	
	
	if(searchResponse != null && searchResponse.results.length>0)
	{
		if(newSearch == true)
			setSessionCookie("page",-1);
		if ( searchResponse.expression.similarTitleCriterias.length > 0 )
		{
			var foundSimilarInData = false;
			for ( var i = 0; i < searchBoxData.length; i++ )
			{
				if ( searchBoxData[i].type == "Similar Titles" )
				{
					foundSimilarInData = true;
					break;
				}
			}
			if ( !foundSimilarInData )
			{
				// this is a text search that has "Like:" in the beginning. We need to manually put in the search term.
				var entry = new SearchBoxDataEntry();
				entry.displayName = "Like: " + searchResponse.expression.similarTitleCriterias[0].contentDTO.displayTitle;
				entry.start = 0;
				entry.end = entry.displayName.length;
				entry.itemId = "[" + searchResponse.expression.similarTitleCriterias[0].contentDTO.id + "]TS";
				entry.type = "Similar Titles";
				searchBoxData.push( entry );
			}
			initStatusLine( searchResponse.expression.similarTitleCriterias[0].contentDTO.unqiueName );
		}
		else
		{
			initStatusLine();
		}
		//since we now have also the IDs of the search criterias we will use it to put unique names in searchLiterals:
		addLinkToStatusLine(searchResponse.expression.similarTitleCriterias)
		
		
		statusText = searchResultFuncs.renderResultsSummary();
		document.getElementById('resultsSummaryBar').innerHTML = statusText;
		document.getElementById('resultsSummaryBar').style.visibility = "visible";
		
//		addInput();
		
		hideNoResultImage();
		displayPreloadText(searchResponse.totalResults,null);
		searchResponseObject = searchResponse;
		AjaxController.getSearchTree( searchResponse.commonCategoriesList, buildSearchTree );
		loadDiscoveryCollage(searchResponseObject);
		
	}
	else
	{
		showNoResultImage();
		document.getElementById('pagingTextLower').innerHTML = "";
		
		document.getElementById('collage_results_links').innerHTML = "";
		
		if( document.getElementById('numOfResults') ) 
			document.getElementById('numOfResults').innerHTML = "0";
		
	}
	
}
function addLinkToStatusLine(similarTitles)
{
	if(similarTitles == null || similarTitles.length ==0 ) return;
	
	var uniqueName = similarTitles[0].contentDTO.unqiueName;
	var similarID = similarTitles[0].id;
	
	for(var index=0;searchLiterals!=null && index<searchLiterals.length; index++) {
		
		if(searchLiterals[index].id == similarID)
			searchLiterals[index].url = uniqueName;
		
	}
	
}
function loadSearchResponseFromSession()
{
	displayCollagePreload();
	AjaxController.pickUpSearchResponseFromSession(handleResult);
}

function cleanearchBox()
{
	try{

	searchBoxData.length = 0;
	document.getElementById( "searchInput" ).value = "";
	
	resetFilterForm();
	
	}
	catch(e){}
}

function displayCollagePreload(displayText)
{
	try{
	hideCollage();
	hideNoResultImage();
	
	document.getElementById('loadingImage').style.display = 'block';
	
	if(displayText != undefined) displayPreloadText(null,displayText);
	}
	catch(e){}
}
function hideCollage()
{
	try{
	document.getElementById(currentDisplayedCollage).style.display = "none";
	}catch(e){}
}
function hideNoResultImage()
{
	try{
	document.getElementById('noResultImage').style.display = 'none';
	}catch(e){}
}
function handleDiscoveryResult(searchResponse)
{
	var statusText = null;
	if(searchResponse.results.length==1 && searchResponse.results[0].content.contentType == "FeatureFilm")
	{
		document.location.href = "movies/" + searchResponse.results[0].content.unqiueName;
		return;
	}
	
	if(document.location.href.indexOf("discovery")<0)
	{
		document.location.href = "/discovery.html";
		return;
	}
	
	
	if(searchResponse != null && searchResponse.results.length>0)
	{
		initStatusLine();
		statusText = searchResultFuncs.renderResultsSummary();
		document.getElementById('resultsSummaryBar').innerHTML = statusText;
		document.getElementById('resultsSummaryBar').style.visibility = "visible";
		
		addInput();
		
		hideNoResultImage();
		displayPreloadText(searchResponse.totalResults,null);
		searchResponseObject = searchResponse;
		AjaxController.getSearchTree( searchResponse.commonCategoriesList, buildSearchTree );
		loadDiscoveryCollage(searchResponseObject.results);
		
	}
	else
	{
		showNoResultImage();
		
	}
}


function rmTooltip(obj) {
	var menuLink = obj;
	var floatingMenu = document.getElementById('rollOverToolTip');
	floatingMenu.style.left = getPosX(menuLink) - 10;
    floatingMenu.style.top  = getPosY(menuLink) + 14;
    floatingMenu.style.display = 'inline';
    alert(obj);
    alert(getPosX(menuLink));
    alert(getPosY(menuLink));
    //alert(floatingMenu.style.top);
    //var Int = setInterval("document.getElementById('tooltip').style.display = 'none'", 3000);
    //return;
}
function getCookieValue(cookieName)
{
	var aCookie = "";
	var cookiesArray = document.cookie.split(";");
	var cookieNameStartIdx = 0;
	var cookieNameEndIdx = 0;
	var cookieValueStartIdx = 0;
	var cookieValueEndIdx = 0;
	var cookieValue = "";
	
	for(var index=0; index < cookiesArray.length; index++) {
		
		aCookie = trim( cookiesArray[index] );
		
		if( aCookie.startsWith(cookieName) )
		{
//			cookieNameStartIdx = aCookie.indexOf(cookieName);
//			cookieNameEndIdx = aCookie.indexOf("=",cookieNameStartIdx);
//			cookieValueStartIdx = cookieNameEndIdx+1;
//			cookieValueEndIdx = aCookie.indexOf(';',cookieValueStartIdx) == -1 ? aCookie.length : aCookie.indexOf(';',cookieValueStartIdx);
			cookieValue = aCookie.split("=")[1]; 
			
	
			return cookieValue;
			
		}
		
		
		
	}
	
	
	
	return "";

}

function setSessionCookie(cookieName,cookieValue)
{
	document.cookie = cookieName + "=" + cookieValue + "; path=/";
}
function removeCookie(cookieName)
{
	var expDate=new Date();
	expDate.setTime(expDate.getTime() - 100000000);
	document.cookie= cookieName + "=deleting;expires=" + expDate.toGMTString()+ "; path=/";
}

function setPersistanteCookie(cookieName, cookieValue, expiryMiliseconds, path)
{
	var expDate=new Date();
	expDate.setTime(expDate.getTime() + expiryMiliseconds);
	document.cookie= cookieName + "=" +escape( cookieValue ) + ((expiryMiliseconds == null) ? "" : ";expires=" + expDate.toGMTString()) + "; path=/";
}
function setPersistanceConfigCookie ()
{
	
}
function setSessionConfigCookie()
{
	
}

/* check username / password */
function checkForm() {
	if (document.getElementsByName('user').value == '' ) {
		alert('Enter Username');
		return false;	
	}
	if (document.getElementsByName('pass').value == '' ) {
		alert('Enter Password');
		return false;
	}
}


/**
 * Returns the size of the window.
 */
function getWindowSize()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) 
  {
  	//Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } 
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
  {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } 
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
  {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight];
}

/**
 * Returns the scroll offset in pixels (X,Y).
 */
function getScrollSize()
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) 
  {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } 
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) 
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } 
  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) 
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
/*
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version < 7.0) || (version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
window.attachEvent("onload", correctPNG);
*/


function getCaretPosition(input)
{
	var result = { start: 0, end: 0 };
	if (input.setSelectionRange)
	{
		result.start = input.selectionStart;
		result.end = input.selectionEnd;
	}
	else if (document.selection && document.selection.createRange)
	{
		var range = document.selection.createRange();
		var r2 = range.duplicate();
		result.start = 0 - r2.moveStart('character', -100000);
		result.end = result.start + range.text.length;
	}
	return result;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

utils.dimThePage = function()
{
	var overlay = document.getElementById('feedbackNotice');
	overlay.style.height = ( utils.getWindowSize().height + utils.getScrollXY().offsetY ) + "px";
	overlay.style.width = ( utils.getWindowSize().width + utils.getScrollXY().offsetX) + "px"; 
	overlay.style.display = "block";
}
utils.unDimThePage = function()
{
	var overlay = document.getElementById('feedbackNotice');
	overlay.style.display = "none";
	
}
utils.getScrollXY = function() 
{
	var returnObject = {offsetX: 0, offsetY: 0};
	
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		returnObject.offsetY = window.pageYOffset;
		returnObject.offsetX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		returnObject.offsetY = document.body.scrollTop;
		returnObject.offsetX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		returnObject.offsetY = document.documentElement.scrollTop;
		returnObject.offsetX = document.documentElement.scrollLeft;
  	}
  	
  return returnObject;
}
utils.getWindowSize = function() 
{
	var resultObject = {width: 0, height: 0}

  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    resultObject.width = window.innerWidth;
    resultObject.height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    resultObject.width = document.documentElement.clientWidth;
    resultObject.height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    resultObject.width = document.body.clientWidth;
    resultObject.height = document.body.clientHeight;
  }
  return resultObject;
}

utils.fadeOut = function( fadeOutObjectId )
{	
	
	if(! document.getElementById(fadeOutObjectId) ) return;
	
	var fadeOut = new OpacityTween(document.getElementById(fadeOutObjectId),Tween.regularEaseOut, 100, 0, 1);
		
	fadeOut.start();
	
	return false;
}
utils.whichElement = function( e )
{
	var targ;
	if (!e)
  	{
  		var e=window.event;
  	}
	if (e.target)
	{
	  	targ=e.target;
	}
	else if (e.srcElement)
	{
	  targ=e.srcElement;
	}
	if (targ.nodeType==3) // defeat Safari bug
	{
	  targ = targ.parentNode;
	}
	
	return targ;
}
utils.Hash = function()
{
	this.length = 0;
	this.items = new Array();
	
	this.put = function(key, value){
		
		this.length++;
		this.items["h-"+key] = value;
	}
	this.get = function(key){
		var returnVal = null;
		try{
			returnVal = this.items["h-"+key];
		}
		catch(ex){}
		
		return returnVal;
	}
	this.remove = function(key){
		
		var returnVal = null;
		try{
			
			returnVal = this.items["h-"+key];
			delete this.items[""+key];
			this.length--;	
		}
		catch(ex){}
		
		return returnVal;
		
	}
}
utils.getSecuredPagesURL = function()
{
	return securedPagesBaseURL;
}
utils.getNonSecuredPagesURL = function()
{
	
	if( !userPages.endsWith("/") ) userPages += "/";
	return userPages;
}
utils.getXMLDocObject = function( text )
{
	var xmlDoc = null;
	
	if (window.ActiveXObject)// Internet Explorer
  	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(text);
		
	}
	else 
	{
		parser=new DOMParser();
  		xmlDoc=parser.parseFromString(text,"text/xml");
	} 
	return xmlDoc;
}
utils.AjaxError = function( url, error, module)
{
	this.ajaxError = {url: url, errorDescription: error, module: module}
}