// JavaScript Document

// open page in new window
function openWin(url){
	window.open(url,'textWin','scrollbars=1,width=385,height=549,top=175,left=175,screenX=175,screenY=175'); 
	return false;
}

// target swf
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

// pauses slideshow and plays setup video
function playSetup(playerUrl, swfId, swfWidth, swfHeight, flvUrl, isGay){
    cmCreatePageElementTag("Setup","BrochureVideo");
	thisMovie("panel1SwfID").pauseSlideshow();
	addFlashVideoToPage(playerUrl, swfId, swfWidth, swfHeight, flvUrl, isGay);
}

// pauses slideshow and plays cleaning video
function playCleaning(playerUrl, swfId, swfWidth, swfHeight, flvUrl, isGay){
    cmCreatePageElementTag("Cleaning","BrochureVideo");
	thisMovie("panel1SwfID").pauseSlideshow();
	addFlashVideoToPage(playerUrl, swfId, swfWidth, swfHeight, flvUrl, isGay);
}

// resumes slideshow and closes cleaning video
function closeCleaning(){
	if (document.getElementById('panel1Swf') != null) {
		thisMovie("panel1SwfID").resumeSlideshow();
	}
	// this is for the generic close video functionality used throughout the site
	hideVideoLightbox();
}

function showVideoLightbox() {
	$('#fade').show();
	$('#videoContainerDiv').show();
}

function hideVideoLightbox() {
	$('#fade').hide();
	$('#videoContainerDiv').hide();
}

function pauseMainSlideshow() {
	thisMovie("panel1SwfID").pauseSlideshow();
}

function playMainSlideshow() {
	thisMovie("panel1SwfID").resumeSlideshow();
}

function addFlashVideoToPage(playerUrl, swfId, swfWidth, swfHeight, flvUrl, isGay){
	var so = new SWFObject(playerUrl, swfId, swfWidth, swfHeight, "8", "#000000");
	so.addParam('scale', 'noscale');
	so.addParam('wmode', 'transparent');
	so.addParam('allowScriptAccess', 'always');
	so.addVariable("isGay",isGay);
	so.addVariable("flvUrl",flvUrl);
	so.addVariable("movie", "cleaning");
	so.write("flashLightboxDiv");
	showVideoLightbox();
    cmCreatePageElementTag(swfId, "HowToVideo");
}

// resizes fade if window is resized
function resizeFade(){
	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2){
		winW = document.body.scrollWidth;
		winH = document.body.scrollHeight;
	}
	else{
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
	}
	
	var cH = document.body.parentNode.clientHeight;

	if(cH){
		winH = cH;
	}
	
	totalHeight = document.getElementById('mainContentCell').offsetHeight;
	totalWidth = document.getElementById('mainContentCell').offsetWidth;
	
	if(winH > totalHeight) {
		document.getElementById('fade').style.height = winH + "px";
	} else {
		document.getElementById('fade').style.height = (totalHeight + 75) + "px";
	}
	
	if(winW > totalWidth) {
		document.getElementById('fade').style.width = winW + "px";
	} else {
		document.getElementById('fade').style.width = (totalWidth + 75) + "px";
	}

}

/*=======================================================
Cart & Option Bar
=======================================================*/

//sets up cart click for every video element on page
function setCartClickEvent(thisEl){

		var thisElemId = thisEl.getAttribute('id');
		var jquerySelector = '#' + thisElemId;
		var thisIdObj = parseId(thisElemId);
		var data;
				
		switch (thisIdObj.moduleName) {
			case 'videoDetails':
				$(jquerySelector).data('flag',1);
				getRentalOptions(thisIdObj);
			break;
			case 'rentAgain':
				var rentAgainAncestor = $(jquerySelector).parent().parent().next().attr('id');
				var ancestorSelector = '#'+rentAgainAncestor;
				
				if ($(ancestorSelector).data('flag') == 1) {	
					$(jquerySelector).removeAttr('onclick');
					data = {
						moduleName: thisIdObj.moduleName,
						root: thisIdObj.root,
						movieId: thisIdObj.movieId
					};
					showRentalsOptions(data, null);
				}
				else {
					rentAgainObj = rentAgain(jquerySelector);
					getRentalOptions(rentAgainObj);						
				}				
			break;
			default:
				ieZindexSet();
	        	$(jquerySelector).bind('click', function(){
					getRentalOptions(thisIdObj);
				});					
		}

		if(! $(jquerySelector).attr('onload')){
			$(jquerySelector).removeAttr('onclick');
			$(jquerySelector).bind('click', function(){
				data = {moduleName:thisIdObj.moduleName, root:thisIdObj.root, movieId:thisIdObj.movieId};
				showRentalsOptions(data,null);
			});
		}
		else{
			$(jquerySelector).removeAttr('onload');
		}
			
}


//gets rental options overlay data
function getRentalOptions(event){

	var rtModuleName = event.moduleName;
	
	typeof(event) === 'object' ? rtMovieId = event.movieId : rtMovieId = event ;

    $.ajax({
        url: "rentalOptions",
        data: {realTouchMovieId:rtMovieId},
        dataType: "json",
        success: function(data){	
            showRentalsOptions(data,rtModuleName);
        },
        error: function(){
            rentalOptionsMessage('errorGettingRentalData',rtMovieId);
        }
    });
	
}


//controls the display of rental options overlay
function showRentalsOptions(data,rtModuleName){

	var messageBoxId;
    var rtMovieId;
	var rtModuleName;
    var rtMovieSelector;
	var buildRentalOptionsContainerVars;

	//for Rent Again to determine which module on the page it appears in
    if (!data.scene) {	
		if (rtModuleName === null) {
			rtMovieId = data.movieId;
			var rentAgainRoot = data.root;
			var moduleName = data.moduleName;
			var triggerSelector = '#' + moduleName + '-' + rentAgainRoot + '-' + rtMovieId;
			var ancestorId = $(triggerSelector).parent().parent().attr('id');
			var parseObj = parseId(ancestorId);
			rtModuleName =	parseObj.moduleName;		
		}
		else {
        	rtMovieId = data.movieId;
			rtModuleName = data.moduleName;				
		}

        rtMovieSelector = '#' + rtModuleName + '-addToCart-' + rtMovieId;
    }
    else {
        buildRentalOptionsContainerVars = buildRentalOptionsContainer(data,rtModuleName);
        rtMovieId = buildRentalOptionsContainerVars.rtMovieId;
        rtMovieSelector = buildRentalOptionsContainerVars.rtMovieSelector;
    }
	
	messageBoxId = rtModuleName + '-messageId-' + rtMovieId;
	rentalOptionsContainerSelector = '#' + rtModuleName + '-rentalOptionsContainer-' + rtMovieId;
	
    $(rtMovieSelector).unbind();
    $(rtMovieSelector).bind('click', {movieId:rtMovieId, moduleName:rtModuleName}, hideRentalOptions);
    $(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_cart_active.gif');
	if (buildRentalOptionsContainerVars != undefined) {
		//hides rentalOptionsContainer for scene with unlimited rental on video details page	
		if (buildRentalOptionsContainerVars.size < 1) { 
			$('#' + rtModuleName + '-videoElementContainer-' + rtMovieId).css('display', 'none');
		}
	}
	$('#' + rtModuleName + '-rentalOptionsContainer-' + rtMovieId).addClass('rentalOptionsVisible');
	coverParent(messageBoxId);
	
	//sets DOM property flag on element so later can determine whether 
	//AJAX call was already made for this element, IMPORTANT for elements 
	//with more than two ways of opening rentalOptionsContainer 
	//(example cart button and rentAgain link)
	$(rentalOptionsContainerSelector).data('flag',1);  
	
}


//builds rental options overlay
function buildRentalOptionsContainer(data,rtModuleName){

	var cartItemTypeId;
	var rentalLinks;
	var rentalOptions;
	var rentalType;
    var rtMovieId = data.scene.realTouchMovieId;
    var rtMovieSelector = '#' + rtModuleName + '-addToCart-' + rtMovieId;
	var videoElementContainer = '#' + rtModuleName + '-videoElementContainer-' + rtMovieId;
	var rentalOptionsContainer;
	var objSize;
	
	if(rtModuleName != 'videoDetails'){ //check to see if this is video details module 
		rentalOptionsContainer = '<div id="' + rtModuleName + '-rentalOptionsContainer-' + rtMovieId + '" class="rentalOptionsContainer"><p>Streaming Rental Options</p></div>';
	}
	else {
		objSize = objectSize(data.scene.rentalTypes);
		if (objSize < 1) { //if an unlimited rental, return to showRentalsOptions
			return {
				rtMovieId: rtMovieId,
				rtMovieSelector: rtMovieSelector,
				size: objSize
			};
		}
		rentalOptionsContainer = '<div id="' + rtModuleName + '-rentalOptionsContainer-' + rtMovieId + '" class="rentalOptionsContainer videoDetailsModifier"><p>Streaming Rental Options</p></div>';
	}
   
    $(videoElementContainer).append(rentalOptionsContainer);
    
    $.each(data.scene.rentalTypes, function(cartItemTypeId){
    		cartItemTypeId = cartItemTypeId;
					
			$.each(data.scene.rentalTypes[cartItemTypeId], function(rentalDays, rentalPrice){
                rentalDays == 0 ? rentalDayString = 'Unlimited' : rentalDayString = (rentalDays/24) + ' - Days';
		        rentalType = '<div class="rentalType">' + rentalDayString + '<br />' + rentalPrice + '</div>';
				
		        //checks if logged in then if user has activated device
		        if (data.loggedIn == "yes") {
		            if (data.activatedDevice == "yes") {
		                rentalLinks = '<div class="rentalLinks"><span onclick="addRental(' + rtMovieId + ',' + cartItemTypeId + ',\'' + rtModuleName + '\');">Add to Cart</span><br /><a href="paymentRedirect?realTouchMovieId=' + rtMovieId + '&rentalTypeId=' + cartItemTypeId + '">Buy it Now</a>';
		            } else {
		               rentalLinks = '<div class="rentalLinks"><span onclick="rentalOptionsMessage(\'activation\',\'' + rtMovieId + '\',\'' + rtModuleName + '\');">Add to Cart</span><br /><span onclick="rentalOptionsMessage(\'activation\',\'' + rtMovieId + '\',\'' + rtModuleName + '\');">Buy it Now</span>';
		            }
		        } else {
		            rentalLinks = '<div class="rentalLinks"><a href="/dispatcher/login?returnUrl=/dispatcher/videoDetail?realTouchMovieId=' + rtMovieId + '">Add to Cart</a><br /><a href="/dispatcher/login?returnUrl=/dispatcher/videoDetail?realTouchMovieId=' + rtMovieId + '">Buy it Now</a>';
		        }
		        
		        rentalOptions = '<div class="rentalOptions">' + rentalType + rentalLinks + '</div>';                   
                $('#' + rtModuleName + '-rentalOptionsContainer-' + rtMovieId).append(rentalOptions);						
			});
    });
    
    return { rtMovieId:rtMovieId, rtMovieSelector:rtMovieSelector };
	
}


//sets zIndex so rental options can overlap video element in next row
function ieZindexSet(){

	if ($('body').data('setZindex') != 1) {
		var layer = 444;

		if ( $.browser.msie ) {
				$('.videoElementContainer').each(function(i){
					$(this).css({'z-index' : layer});
					layer = layer-1;
				});
		}
	}
	$('body').data('setZindex',1); //prevents function from running on every instance of element
	
}


//lets server know what user has added to cart
function addRental(rtMovieId,rentalTypeId,rtModuleName){
	
    $.ajax({
        url: "addToCart",
        data: {
            realTouchMovieId: rtMovieId,
            rentalTypeId: rentalTypeId,
            cartItemTypeId: 1 //StreamingRental = 1, RealTouchMinutes = 0
        },
        dataType: "json",
        success: function(data){
            updateCartStatus(data,rtMovieId,rtModuleName);
        },
        error: function(){
            window.location.href = '/dispatcher/videoDetail?realTouchMovieId='+rtMovieId;
        }
    });
	
}


//pushes time package purchase to cart
function addTimePackage(timePackage){
		
    $.ajax({
        url: "addToCart",
		data: {
            packageId: timePackage,
            cartItemTypeId: 0 //StreamingRental = 1, RealTouchMinutes = 0
        },
        dataType: "json",
        success: function(data){
            updateCartStatus(data);            
            if(window.location.href.indexOf('/dispatcher/cart')>-1){
                window.location='/dispatcher/cart';
            }
        },
        error: function(){
            rentalOptionsMessage('minutePackageError');
        }
    });
	
}


//updates cart indicator and video element
function updateCartStatus(data,rtMovieId,rtModuleName){

	if (typeof rtMovieId === 'number'){
		rentalOptionsMessage('addedToCart', rtMovieId, rtModuleName);
	}
	$('#cartCount').text(data.cartItems);
	if (data.cartExceeded == false) {
		$('#cartIndicatorMessage').text('Item Added').css('background','#11720d');
	}
	else{
		$('#cartIndicatorMessage').text('Cart Limit Exceeded').css('background','#8F0505');
	}	
	$('.cartIndicatorContainer').css({display:'block'});
	$('#cartIndicatorMessage').slideDown('slow', function(){
	    setTimeout( function(){ $('#cartIndicatorMessage').slideUp('slow'); }, 3000); 
	});
	
}


//controls messages related to option bar and cart indicator
function rentalOptionsMessage(mes,rtMovieId,rtModuleName){

	switch(mes){
		case 'activation':
			optionBarMessage(mes,rtMovieId,rtModuleName);
		break;
		case 'addedToCart':
			optionBarMessage(mes,rtMovieId,rtModuleName);
		break;
		case 'errorGettingRentalData':
			optionBarMessage(mes,rtMovieId,rtModuleName);
		break;
		case 'minutePackageError':
		//need to set?
			//alert("error adding minute package to cart");
		break;
		default:
			optionBarMessage();					
	}

}


//display message that appears under option bar
function optionBarMessage(messageType,rtMovieId,rtModuleName){
	
	var rtMessageSelector = ('#' + rtModuleName + '-messageId-' + rtMovieId);
	var inCartMessageId = (rtModuleName + '-messageId-' + rtMovieId);
	var initButton = ('#' + rtModuleName + '-addToCart-'+ rtMovieId);

	switch(messageType){
		case 'activation':
			if (rtModuleName == 'videoDetails') {
				$(rtMessageSelector).addClass('videoDetailsModifier');
				coverParent(inCartMessageId);
				}
			$(rtMessageSelector).addClass('optionMessageVisible');
			$(rtMessageSelector).slideDown(10);
			$(rtMessageSelector).html('<div class="activate">You will need to have an activated RealTouch device to purchase a RealTouch rental.</div>');
			setTimeout( function(){ 
				$('.optionMessageVisible').slideUp('slow'); 
			}, 6000);
			hideRentalOptions(rtMovieId,'activate',rtModuleName);
		break;
		case 'addedToCart':
			if (rtModuleName == 'videoDetails') {
				$(rtMessageSelector).addClass('videoDetailsModifier');
				coverParent(inCartMessageId);
			}
			$(rtMessageSelector).addClass('optionMessageVisible');
			$(rtMessageSelector).slideDown(10);
			$(rtMessageSelector).html('<div>This Rental Was Added To Your Cart</div><a href="/dispatcher/cart" alt="Go to my Cart">Go to my Cart</a>');

			hideRentalOptions(rtMovieId,'inCart',rtModuleName);
		break;
		case 'errorGettingRentalData':
			if (rtModuleName == 'videoDetails') {
				$(rtMessageSelector).addClass('videoDetailsModifier');
				coverParent(inCartMessageId);
			}
			$(rtMessageSelector).addClass('optionMessageVisible');
			$(initButton).attr('src','http://pic.aebn.net/realtouch/images/rt_blank.gif').css('cursor','default');
			$(rtMessageSelector).slideDown();
			$(rtMessageSelector).html('<div>We\'ve experienced an issue retrieving the data you requested. Please try again in a moment.</div>');
			setTimeout( function(){ 
					$(rtMessageSelector).slideUp('slow');
					hideRentalOptions(rtMovieId,'errorRentalData',rtModuleName);
			}, 7000);
		break;
		default:
			$(rtMessageSelector).addClass('optionMessageVisible');
			$(rtMessageSelector).slideDown(10);
			$(rtMessageSelector).html('<div class="error">An error occurred.</div>');
			setTimeout( function(){ 
				$('.optionMessageVisible').slideUp('slow'); 
			}, 6000);
			hideRentalOptions(rtMovieId,'',rtModuleName);
	}
	
}


//hides rental options overlay - resets event listeners on cart button
function hideRentalOptions(event,flag,rtModuleName){
	
	var rtMovieId;
	var rtModuleName;
	var rtMovieSelector;

	if(typeof(event) == 'object'){
		rtMovieId = event.data.movieId;
		rtModuleName = event.data.moduleName;
		flag = 'object';
	} else {
		rtMovieId = event;
	}
	
	var data = {
				moduleName: rtModuleName, 
				movieId: rtMovieId
	}

    rtMovieSelector = '#' + rtModuleName + '-addToCart-' + rtMovieId;
    $(rtMovieSelector).unbind();

	switch(flag){
		case 'object':
            $(rtMovieSelector).bind('click', function(){
				showRentalsOptions(data);
			});
            $(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_cart_default.gif');
		break;
		case 'activate':
            $(rtMovieSelector).bind('click', function(){
				showRentalsOptions(data);
			});
            $(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_cart_default.gif');
		break;
		case 'errorRentalData':
            $(rtMovieSelector).bind('click', function(){
				getRentalOptions(data);
			});
            $(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_cart_default.gif');
			$(rtMovieSelector).css({cursor: 'pointer'});
		break;
		case 'inCart':
            $(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_cart_active.gif');
			$(rtMovieSelector).css({cursor: 'default'});
		break;
		default:
			$(rtMovieSelector).attr('src', 'http://pic.aebn.net/realtouch/images/rt_blank.gif');
			$(rtMovieSelector).css({cursor: 'default'});	
	}

    $('#' + rtModuleName + '-rentalOptionsContainer-'+ rtMovieId).removeClass('rentalOptionsVisible');
	
}

// parse ID of "add to cart" button
function parseId(elId){
	
 	var elIdComponents = elId.split(/-/g);
	var data = {};
	
	if (elIdComponents.length < 3){
		data = {moduleName:elIdComponents[0], movieId:elIdComponents[1]}
	} else {
		data = {moduleName:elIdComponents[0], root:elIdComponents[1], movieId:elIdComponents[2]}
	}

	return data;
			
}


//parses parent element id to set click event handler
function rentAgain(jquerySelector){

	var parentId = $(jquerySelector).parents('.videoElementDetails').attr('id');
	var data = parseId(parentId);
	
	return data;
	
}


//makes in-cart display message same height as its sibling container that it needs to cover on the video detail page
function coverParent(thisId){

	var selector = '#'+thisId;

	if((thisId !== 'messageId') && ($(selector).parent().attr('class') == 'videoDetailRentalOptionsContainer')){
		var siblingHeight = $(selector).next().height();
		$(selector).height(siblingHeight-10);	
	}
	
}


//get size of object
function objectSize(obj){
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
}


/*=======================================================
Video Details Page, Show Hide Detail Information
=======================================================*/

function videoDetailInfoButtonClickEvent(){

	$('.videoDetailInfoButton, .videoDetailImage, .videoDetailSceneThumbs .rentAgain').click( function(){
		
		if ($(this).hasClass('rentAgain')) {
			var getParentClass = $(this).parent().parent().attr('class');
			var isMatch = getParentClass.match(/videoDetail/);

			if ( isMatch == null ) {
				setCartClickEvent(this);
				return;
			}			
		}	

		var thisObj = $(this);
		var thisId = $(this).attr('id');
		var thisClass = $(this).attr('class');
		var thisIdObj = parseId(thisId);
		var rtMovieId = thisIdObj.movieId;
		var optionBarInfoButtonId = '#videoDetails-trigger-' + rtMovieId;
		
		//sets all to hidden states
		if (! thisObj.hasClass('videoDetailInfoActive')) {
			$('.videoDetailInfoActive').each( function(){
				$(this).removeClass('videoDetailInfoActive');
			});
	
			$('.videoDetailInfoButton').each( function(){		
				$(this).attr('src','http://pic.aebn.net/realtouch/images/rt_videoDetail_default.gif');
				$(this).parent().next().addClass('videoDetailStarsActive');
				$(this).parents('.videoDetailSceneThumbs').next().removeClass('videoDetailDetailsActive');
			});	
		}
		
		//sets clicked to open detail state, based on what was clicked
		if (thisObj.hasClass('videoDetailInfoButton')) {
			thisObj.parents('.videoDetailOptionBar').siblings('img').addClass('videoDetailInfoActive');
			thisObj.addClass('videoDetailInfoActive');
			thisObj.attr('src','http://pic.aebn.net/realtouch/images/rt_videoDetail_active.gif');
			thisObj.parent().next().removeClass('videoDetailStarsActive');
			thisObj.parents('.videoDetailSceneThumbs').next().addClass('videoDetailDetailsActive');
			if(thisObj.parents('.videoDetailOptionBar').siblings('.videoElementTime')) {
				thisObj.parents('.videoDetailOptionBar').siblings('.videoElementTime').children('span').addClass('videoDetailInfoActive');
			}			
		}
		else {
			thisObj.addClass('videoDetailInfoActive');
			if(thisObj.hasClass('rentAgain')){
				thisObj.parent().siblings('img').addClass('videoDetailInfoActive');		
			}
			else {
				thisObj.siblings('img').addClass('videoDetailInfoActive')	
				if(thisObj.siblings('.videoElementTime')) {
					thisObj.siblings('.videoElementTime').children('span').addClass('videoDetailInfoActive');
				}
			}
			$(optionBarInfoButtonId).addClass('videoDetailInfoActive');
			$(optionBarInfoButtonId).attr('src','http://pic.aebn.net/realtouch/images/rt_videoDetail_active.gif');
			$(optionBarInfoButtonId).parent().next().removeClass('videoDetailStarsActive');
			$(optionBarInfoButtonId).parents('.videoDetailSceneThumbs').next().addClass('videoDetailDetailsActive');			
		}
		
		//prevents init of AJAX call if already called once	
		if($(optionBarInfoButtonId).data('flag') != 1){getRentalOptions(thisIdObj);}
		$(optionBarInfoButtonId).data('flag',1);
		coverParent(thisId);
		
	});
			
}


/*=======================================================
Init function
=======================================================*/
$(function(){

	if($('div.videoDetailOptionBar').html() != null){videoDetailInfoButtonClickEvent();}
	
});
