// Create XMLhttp Object on ClientSide

var getTransferObject = function(){    return null;    };
if(window.ActiveXObject){
    // Check if the browser has support for ActiveXObject (IE Usually) 
    try{ 
	// Check for the new version of XMLHttp compoment 
	var x= new ActiveXObject("MSXML2.XMLHTTP"); 
	getTransferObject = function(){ return new ActiveXObject("MSXML2.XMLHTTP"); }
	delete x;
       }catch(_ex){ 
		try{ // Check for late version of XMLHTTP compoment 
		    var x = new ActiveXObject("Microsoft.XMLHTTP"); 
		    getTransferObject = function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
		    delete x;
		}catch(ex){
		    // Otherwise the version of IE is too old 
		} 
	    } 
	}else if(window.XMLHttpRequest){
	    // XMLHttpRequest object supported by Opera, Firefox and Safari - may too in IE 7. 
	    getTransferObject = function(){ return new XMLHttpRequest(); }
	}



function AjaxCall (URL, Parameters, Method, IsAsync, func_OnSuccess, func_OnFailure)
{
	var xmlhttp = getTransferObject();

	if(!xmlhttp)
	{
		throw "Download the newer Firefox/IE or upgrade your browser please.";
		return false;
	}
		
	else
	{

		xmlhttp.open(Method, URL, IsAsync);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		xmlhttp.send(Parameters);

		if (IsAsync)
		{
			xmlhttp.onreadystatechange = function ()
			{
				if (xmlhttp.readyState == 4)
				{
					HttpStatus = xmlhttp.status;
					ResponseText = xmlhttp.responseText;

					if (HttpStatus==200)
					{
						return func_OnSuccess(ResponseText);
					}
					else
					{
						func_OnFailure (ResponseText, HttpStatus);
					}
				}
			}
		}
		else
		{
			HttpStatus = xmlhttp.status;
			ResponseText = xmlhttp.responseText;

			if (HttpStatus==200)
			{
				return func_OnSuccess(ResponseText);
			}
			else
			{
				func_OnFailure (ResponseText, HttpStatus);
			}
		}
	}	
}

function loadXMLfromString (TheString)
{
	try //Internet Explorer
	  {
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async="false";
	  xmlDoc.loadXML(TheString);
	  return xmlDoc;
	  }
	catch(e)
	  {
	  try //Firefox, Mozilla, Opera, etc.
		{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(TheString,"text/xml");
		return xmlDoc;
		}
	  catch(e) {alert(e.message)}
	  }

}


var innerHeight;
function getInnerSize()
{
	innerHeight = document.documentElement.clientHeight;
}


function radio_button_checker(object)
{
	var radio_choice = false;

	for (counter = 0; counter < object.length; counter++)
	{
		if (object[counter].checked)
		radio_choice = true; 
	}

	if (!radio_choice)
	{
		return (false);
	}
return (true);
}




var movieImagesPreview_Interval;
function movieImagesPreview_OnMouseOver(imageObject, ThumbnailFilename)
{

	movieImagesPreview (imageObject, ThumbnailFilename);
	movieImagesPreview_Interval = setInterval (function() {movieImagesPreview (imageObject, ThumbnailFilename)},1000);
}

function movieImagesPreview_OnMouseOut (imageObject, ThumbnailFilename)
{
	clearInterval (movieImagesPreview_Interval);
	ThumbnailNumber = 0;
	movieImagesPreview (imageObject, ThumbnailFilename);
}


var ThumbnailNumber = 1;
function movieImagesPreview (imageObject, ThumbnailFilename)
{
	if (ThumbnailNumber == 10)
	{

		ThumbnailNumber = 0;
	}
	ThumbnailNumber ++;

	if (ThumbnailNumber < 10)
	{
		ThumbnailNumber = '0' + ThumbnailNumber;
	}

	imageObject.src = ThumbnailFilename + ThumbnailNumber + '.jpg';

	ThumbnailNumber = parseInt (ThumbnailNumber,10);

}

function getStringWidth(string,fontFamily,fontSize,fontWeight)
{
	var spanElement = document.createElement('span');
	spanElement.style.whiteSpace = 'nowrap';
	spanElement.style.fontFamily = fontFamily;
	spanElement.style.fontSize = fontSize;
	spanElement.style.fontWeight = fontWeight;
	spanElement.innerHTML = string;
	document.body.appendChild(spanElement);
	var width = spanElement.offsetWidth;
	document.body.removeChild(spanElement);

	return width;
}


function getXMLNodeValue (nodeObject)
{
	if (navigator.userAgent.indexOf("Firefox")!=-1)
	{
		return nodeObject.textContent;
	}
	else
	{
		if (nodeObject.text == undefined)
		{
			return nodeObject.textContent;
		}
		else
		{
			return nodeObject.text;
		}
	}
}




// shows a standard movie box without getting data from DB
function showMovieBox (thumbnailURL, movieTitle, i, PlaylistControl_HTML, movieID, username, rating, movieDuration, userID)
{

	var HTML = '';
	
	// limit movie title width
	movieTitle_cut = movieTitle

	stringWidth_movieTitle = getStringWidth (movieTitle, 'arial', '12px', 'bold');
	stringWidth_3periods = getStringWidth ('...', 'arial', '12px', 'bold');

	charsToRemove = 0;
	while (stringWidth_movieTitle > 159)
	{
		charsToRemove ++ ;

		movieTitle_cut = movieTitle.substring (0,movieTitle.length - charsToRemove) + '...';
		stringWidth_movieTitle = getStringWidth (movieTitle_cut, 'arial', '12px', 'bold');
	}


	// build movie box html
	HTML = '<div style="width:158px; height:118px; border:solid 1px #dddddd; margin-bottom:5px;">';
		HTML += '<div style="position:relative; width:156px; height:116px; border:solid 1px white; text-align:left;">';
			HTML += '<a href="'+VirtualPathFromRoot+'movies/'+movieID+'/'+escape(movieTitle)+'"><img src="'+thumbnailURL+'" style="border:none; width:156px; height:116px;" alt="'+movieTitle+'\'s preview image" onmouseover = "movieImagesPreview_OnMouseOver(this, \''+thumbnailURL.substring (0,thumbnailURL.length - 6)+'\');" onmouseout = "movieImagesPreview_OnMouseOut(this, \''+thumbnailURL.substring (0,thumbnailURL.length - 6)+'\');"></a>';
			HTML += '<div id="movie_PlaylistControl_'+movieID+'" style="position:absolute; width:17px; height:17px; bottom:1px; left:1px;">'+PlaylistControl_HTML+'</div>';
		HTML += '</div>';
	HTML += '</div>';
	HTML += '<div style="text-align:left"><a href="'+VirtualPathFromRoot+'movies/'+movieID+'/'+escape(movieTitle)+'" class="lnk_movieTitle" title="'+movieTitle+'">'+movieTitle_cut+'</a></div>';;
	HTML += '<div style="text-align:left;" class="text1">By: <a href="'+VirtualPathFromRoot+'MyArea.asp?userID='+userID+'" class="text2" style="text-decoration:none;">'+username+'</a></div>';


	rating = rating+'';
	if (rating.indexOf (".") != -1) {showHalfStar = true;}
	else {showHalfStar = false;}

	rating = parseInt (rating);

	HTML_rating = '';
	for (j=1; j<=rating; j++)
	{
		HTML_rating += '<img src="'+VirtualPathFromRoot+'Design/MainPage/icon_redstar.gif" alt="full star">';
	}

	if (showHalfStar) {HTML_rating += '<img src="'+VirtualPathFromRoot+'Design/MainPage/icon_redhalfstar.gif" alt="half star">'; j++}

	for (j=j; j<=5; j++)
	{
		HTML_rating += '<img src="'+VirtualPathFromRoot+'Design/MainPage/icon_graystar.gif" alt="gray star">';
	}


	HTML += '<div style="float:left;" class="text1">Rating: '+HTML_rating+'</div>';
	HTML += '<div style="float:right; padding-right:5px;" class="text1">'+movieDuration+'</div>';
	HTML += '<div style="clear:both;"></div>';

	return HTML;
}


function addToPlaylist(movieID)
{
	// Create http request
	var xmlhttp = getTransferObject();
	if(!xmlhttp)
	{
		throw "Download the newer Firefox/IE or upgrade your browser please.";
		return false;
	}
		
	else
	{

		File = DomainURL+'/ajax_PlayList_AddMovie.asp';

		Parameters = '?movieID='+movieID
		TheUrl = File + Parameters;
		xmlhttp.open("GET",TheUrl ,true);
		xmlhttp.send(null);

		xmlhttp.onreadystatechange = function ()
		{
			
			if (xmlhttp.readyState == 4)
			{
				HttpStatus = xmlhttp.status;
				HttpResponseText = xmlhttp.responseText;
				HttpResponseXml = xmlhttp.responseXml;

				if (HttpStatus == 200)
				{
					if (document.getElementById("movie_PlaylistControl_"+movieID) != undefined)
					{
						document.getElementById("movie_PlaylistControl_"+movieID).innerHTML = '<img src="'+VirtualPathFromRoot+'Design/Mainpage/RemoveFromPlayList.png" title="Remove movie from playlist" onclick="removeFromPlaylist('+movieID+')" style="cursor:pointer">';
					}
					if (PlaylistLoaded) {PlaylistLoaded = false;}
					if (PlaylistOpened) {PlaylistOpened = false; popup_Playlist(false);}
					
					updatePlaylistItems (1);					
				}
				else
				{
					errorContent = 'An error accessing the playlist has occured.<br>Error information was sent to technical team.<br>Please try again at a later time.';
					alert (errorContent);
					//popup_ErrorMsgBox (errorContent, HttpStatus);
				}
			}
		}
	}
	delete xmlhttp;



}



function removeFromPlaylist(movieID)
{
	// Create http request
	var xmlhttp = getTransferObject();
	if(!xmlhttp)
	{
		throw "Download the newer Firefox/IE or upgrade your browser please.";
		return false;
	}
		
	else
	{

		File = DomainURL+'/ajax_PlayList_DeleteMovie.asp';

		Parameters = '?movieID='+movieID
		TheUrl = File + Parameters;
		xmlhttp.open("GET",TheUrl ,true);
		xmlhttp.send(null);

		xmlhttp.onreadystatechange = function ()
		{
			
			if (xmlhttp.readyState == 4)
			{
				HttpStatus = xmlhttp.status;
				HttpResponseText = xmlhttp.responseText;
				HttpResponseXml = xmlhttp.responseXml;

				if (HttpStatus == 200)
				{
					if (document.getElementById("movie_PlaylistControl_"+movieID) != undefined)
					{
						document.getElementById("movie_PlaylistControl_"+movieID).innerHTML = '<img src="'+VirtualPathFromRoot+'Design/Mainpage/AddToPlayList.png" title="Add movie to playlist" onclick="addToPlaylist('+movieID+')" style="cursor:pointer">';
					}
					if (PlaylistLoaded) {PlaylistLoaded = false;}
					if (PlaylistOpened) {PlaylistOpened = false; popup_Playlist(false);}
					updatePlaylistItems (2);

				}
				else
				{
					errorContent = 'An error accessing the playlist has occured.<br>Error information was sent to technical team.<br>Please try again at a later time.';
					alert (errorContent);
					//popup_ErrorMsgBox (errorContent, HttpStatus);
				}
			}
		}
	}
	delete xmlhttp;



}




function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;

	if(window.addEventListener)	{ 
		// Standard
		element.addEventListener(type, expression, bubbling);
		return true;
	} 
	else if(window.attachEvent) { 
		// IE
		element.attachEvent('on' + type, expression);
		return true;
	} 
	else return false;
}

function removeListener(element, type, expression)
{

	if(window.removeEventListener)	{ 
		// Standard
		element.removeEventListener(type, expression, false);
		return true;
	} 
	else if(window.detachEvent) { 
		// IE
		element.detachEvent('on' + type, expression);
		return true;
	} 
	else return false;
}

function DisplayNavigation (currentPage, totalPages, jsFunction, hrefContent, displayFirstAndLast)
{
	if (totalPages > 1)
	{

		// get min page to show
		closestBottomPage = currentPage - 3;
		while (closestBottomPage < 1)
		{
			closestBottomPage++;
		}

		// get max page to show
		closestLastPage = currentPage + 3;
		while (closestLastPage > totalPages)
		{
			closestLastPage--;
		}


		while ( ((closestLastPage - closestBottomPage + 1) < 7) && (closestLastPage < totalPages) )
		{
			closestLastPage++;
		}

		while ( ((closestLastPage - closestBottomPage + 1) < 7) && (closestBottomPage > 1) )
		{
			closestBottomPage--;
		}

		// build html
		html = '<div style="text-align:center;">';

		if (currentPage > 1)
		{
			if (displayFirstAndLast)
			{
				html += '<a class="Paging_TextButtons_Active" href="'+hrefContent.replace('{p}', '1')+'" onclick="'+jsFunction+'(1);">&lt;&lt; First page</a>&nbsp;';
			}

			html += '<a class="Paging_TextButtons_Active" href="'+hrefContent.replace('{p}', parseInt(currentPage-1))+'" onclick="'+jsFunction+'('+parseInt(currentPage-1)+');">&lt; Previous</a>&nbsp;';
		}

		for (i=closestBottomPage; i<=closestLastPage; i++)
		{
			if (i == currentPage)
			{
				html += '<a class="Paging_Number_NotActive" nohref>'+i+'</a>&nbsp;';
			}
			else
			{
				html += '<a class="Paging_Number_Active" href="'+hrefContent.replace('{p}', i)+'" onclick="'+jsFunction+'('+i+');">'+i+'</a>&nbsp;';
			}
		}

		if (currentPage < totalPages)
		{
			html += '<a class="Paging_TextButtons_Active" href="'+hrefContent.replace('{p}', parseInt(currentPage+1))+'" onclick="'+jsFunction+'('+parseInt(currentPage+1)+');">Next &gt;</a>&nbsp;';

			if (displayFirstAndLast)
			{
				html += '<a class="Paging_TextButtons_Active" href="'+hrefContent.replace('{p}', totalPages)+'" onclick="'+jsFunction+'('+totalPages+');">Last page &gt;&gt;</a>';
			}
		}

		html += '</div>';
	
	}
	else
	{
		html = '';
	}


	return html;
}



function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function focusElementToBottom (object)
{
	pagingYpos = findPosY (object);
	window.scrollTo (1, pagingYpos - document.documentElement.clientHeight + object.style.height);
}


function getOuterHTML(object) {
var element;
if (!object) return null;
element = document.createElement("div");
element.appendChild(object.cloneNode(true));
return element.innerHTML;
}


function updatePlaylistItems (mathAction)
{
	if (document.getElementById ("totalPlaylistItems") != undefined)
	{
		if (mathAction == 1)
		{
			document.getElementById ("totalPlaylistItems").innerHTML = parseInt(document.getElementById ("totalPlaylistItems").innerHTML) + 1;
		}

		if (mathAction == 2)
		{
			document.getElementById ("totalPlaylistItems").innerHTML = parseInt(document.getElementById ("totalPlaylistItems").innerHTML) - 1;
		}
	}

}

function newWindowLinks()
{
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors .length; i++)
	{
		var anchor = anchors[i];
		if (
			anchor.getAttribute("href") && (
			anchor.getAttribute("rel") == "external" ||
			anchor.getAttribute("rel") == "external nofollow" ||
			anchor.getAttribute("rel") == "nofollow external" )
		)
		anchor.target = "_blank";
	}
}

