var tabUrl = Array();
var tabPost = Array();
var clickedOnDownload = false;
var searchPrevVal = Array();

/**
 * Added this snipplet for backwardass compatibility with some old jQuery (less than 1.2) syntax
 */
if(!jQuery.fn.lt){
	jQuery.fn.lt = function(n){
		return this.slice(0,n);
	}
}

var fader = {
	open: function (dialog) {
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200);
				$('.cssButtonGreen').click( function() {
					$('#buyForm').submit();
				});
			});
		});
		//$.NiceJForms.build();
		makeCssButtons();
		makeDownloadTorrentButtonFromModal();
		makeNoMoreTestCheckbox();
		$(".flashContainer").css("visibility","hidden");
	},
	close: function (dialog) {
		//dialog.data.fadeOut(200, function () {
			//dialog.container.fadeOut(200, function () {
				//dialog.overlay.fadeOut(200, function () {
					$.modal.close();
				//});
			//});
		//});
		makeBuyButton();
		makeCssButtons();
		makeMustLoginButtons();
		//makeDownloadDirectButtons();
		makeBuyProductsInCartButton();
		clickedOnDownload = false;
		$(".flashContainer").css("visibility","visible");
	}
};

function makeButtons() {
	//Dummy just to remove error in modal open function call for reseller sites
}

function makeCssButtons(){
	$('.cssButton').each(function(){
		var b = $(this);
		var url = $(this).attr('href');
		var tooltip = $(this).children('.tooltip').text();
		var onclick = $(this).attr('onclick');
		$(this).children('.tooltip').remove();
		var tt = b.text() || b.val();
		if ($(':submit,:button',this)) {
			b = $('<a>').insertAfter(this). addClass(this.className).attr('id',this.id);
			$(this).remove();
		}
		if(url != '') {
			b.attr('href', url);
		}
		b.text('').css({cursor:'pointer'}). prepend('<i><\/i>').append($('<span>').text(tt).append('<i><\/i><span><\/span><\/span>'));
		

		if(tooltip) {
			$(b).append('<span class="tooltip">'+ tooltip +'</span>');
		}
	});
	
	
	//$('.cssButtonSubmit, :not(.cssButtonDisable), :not(.mustLogin)').click(function() {
	$('.cssButtonSubmit').click(function() {
		if($(this).is('.mustLogin') || $(this).is('.cssButtonDisable') || $(this).is('.cssButtonRemove')) {
			return;
		}
		if($(this).is('.cssButtonDeposit')) {
			/*var input = $('#amount0');
			while(!$(input).is(':checked')) {
				input = $(input).parent('td').next('td').children('input:first');
			}
			if($(input).is('#amount4')) {
				amount = $(input).siblings('#ownAmount').val();
			} else {
				amount = $(input).val();
			}*/
			depositSubmit();
			//$('#buyForm').action='buy.php?amount=' + amount + '&deposit=true';
		}
		$(this).parents('form').submit();
	});
	$('.cssButtonRemove').click( function() {
		$('#confirm').submit();
		$(this).siblings('.bigButton').remove();
		$(this).remove();
	});
}
function depositSubmit(){
	document.forms.buyForm.action = '/account/buy.php?payDeposit=true';
}

function editDeposit() {
	$('.editDeposit').click(function() {
		$(this).parents('.textblock').find('.content').show();
		$(this).parents('.contentNew').remove();
	});
}

function alreadyUser() {
	$('.alreadyUser').click(function (e) {
		e.preventDefault();
		var box = $(this).parents('.textblock');
		var data = 'purchaseOffer=' + $('#purchaseOffer').val();
		data += '&purchaseOfferBundle=' + $('#purchaseOfferBundle').val();
		data += '&purchaseProduct=' + $('#purchaseProduct').val();
		$.ajax({
			type: 'post',
			//url: 'login.php',
			url : '/ajax/userLogin.php',
			data: data,
			cache: false, 
			success: function(data){
				data = data.split('|', 2);
				$(box).html(data[1]);
				$('.texterror').hide();
				newUser();
				ajaxLogin();
				$('#contactWideModalContainer').attr('id', 'contactModalContainer');
				$('#registerDialogue').children('.rightBoxTitleRed').children('h1').text(data[0]);
			}
		});
	});
}

function ajaxLogin() {
	$('form.loginUser').submit(function(e) {
		e.preventDefault();
		$('.ajaxLogin').click();
	});
	$('.ajaxLogin').click(function (e) {
		var data;
		data = 'username=' + $('input#username').val();
		data += '&password=' + $('input#password').val();
		data += '&purchaseOffer=' + $('input#purchaseOffer').val();
		data += '&purchaseOfferBundle=' + $('input#purchaseOfferBundle').val();
		data += '&purchaseProduct=' + $('input#purchaseProduct').val();
		$.ajax({
			type: 'post',
			url : '/ajax/userLogin.php',
			data: data,
			cache: false, 
			success: function(data){
				data = data.split('|');
				if(data[0] != 'true') {
					$('.texterror').text(data[1]).show();
				} else {
					temp = window.location.toString();
					temp = temp.substr(temp.indexOf('://')); // Get everything after http or https
					if(temp.indexOf('#') > 0) {
						temp = temp.substr(0, temp.indexOf('#')); // Remove any anchor
					}
					temp = data[1].substr(0, data[1].indexOf('://')) + temp; // Paste the new http or https in front of the current url
					window.location = temp;
				}
			}
		});
	});
}

function ajaxRegister() {
	$('form.userRegister').submit(function(e) {
		e.preventDefault();
		$('.ajaxRegister').click();
	});
	$('.ajaxRegister').click(function (e) {
		var data = '';
		$("#registerDialogue").find("input").each(function() {
			if(data != '') {
				data = data + "&";
			}
			if($(this).is(':checkbox')) {
				if($(this).is(':checked')) {
					data = data + $(this).attr("name") + "=" + $(this).val();
				}
			} else {
				data = data + $(this).attr("name") + "=" + $(this).val();
			}
		});
		$.ajax({
			type: 'post',
			url : '/ajax/userRegister.php',
			data: "ajax=true&"+data,
			cache: false, 
			success: function(data) {
				data = data.split('|');
				if(data[0] == 'true') {
					temp = window.location.toString();
					temp = temp.substr(temp.indexOf('://'));
					if(temp.indexOf('#') > 0) {
						temp = temp.substr(0, temp.indexOf('#'));
					}
					temp = data[1].substr(0, data[1].indexOf('://')) + temp;
					if (temp.indexOf("?") > 0 ) {
						temp = temp + "&register=success";
                    } else {
						temp = temp + "?register=success";
                    }
					window.location = temp;
				} else {
					msg = data[1].split(':');
					input = data[2].split(':');
					
					/*$('.texterror').html('');
					for(i = 0; i < msg.length; i++) {
						$('.texterror').append('<p>'+msg[i]+'</p>');
					}
					$('.texterror').show();*/
					
					for(i = 0; i < input.length; i++) {
						if($('input#'+input[i]).is(':checkbox')) {
							$('input#'+input[i]).parent().addClass('inputError');
						} else {
							$('input#'+input[i]).addClass('inputError');
						}
						$('input#'+input[i]).parents('td, th').find('.red').remove();
						$('input#'+input[i]).parents('td, th').prepend('<div class="red"><b>'+msg[i]+'</b></div>');
					}
					$('.inputError').focus(function() {
						$(this).removeClass('inputError');
						$(this).blur(function() {
							$(this).parents('td, th').find('.red').remove();
						});
					});
					for(i = 0; i < input.length; i++) {
						if($('input#'+input[i]).is(':checkbox')) {
							$('input#'+input[i]).focus(function() {
								$(this).parent().removeClass('inputError');
								$(this).blur(function() {
									$(this).parents('td, th').find('.red').remove();
								});
							});
						}
					}
				}
			}
		});
	});
}

function newUser() {
	$('.newUser').click(function (e) {
		e.preventDefault();
		var box = $(this).parents('.textblock');
		$.ajax({
			type: 'post',
			//url: 'login.php',
			url : '/ajax/userRegister.php',
			data: 'onlyBody=true&purchaseOffer=' + $('#purchaseOffer').val() + '&purchaseOfferBundle=' + $('#purchaseOfferBundle').val() + '&purchaseProduct=' + $('#purchaseProduct').val(),
			cache: false, 
			success: function(data){
				data = data.split('|', 2);
				$(box).html(data[1]);
				alreadyUser();
				ajaxRegister();
				$('#contactModalContainer').attr('id', 'contactWideModalContainer');
				$('#registerDialogue').children('.rightBoxTitleRed').children('h1').text(data[0]);
			}
		});
	});
}

function makeMustLoginButtons() {
	$('.mustLogin').click(function (e) {
		$(this).unbind('click');
		e.preventDefault();
		if($(this).is('.cssButtonDisable ')) {
			return;
		}
		var data = '';
		
		if($(this).is('.downloadBundle')) {
			data = data + 'purchaseOffer=' + $('input.offerID').val() + '&';
			data = data + 'purchaseOfferBundle=1&';
		} else if(!$(this).is('.only')) {
			inputElement = $(this).parents('form').find('input:radio:checked');
			offerID = $(inputElement).siblings('.offerID').val();
			tproductID = $(inputElement).siblings('.productID').val();
			data = data + 'purchaseOffer=' + offerID + '&';
			data = data + 'purchaseProduct=' + tproductID;
		} else {
			offerID = $(this).siblings('.offerID').val();
			tproductID = $(this).siblings('.productID').val();
			campaignCode = $(this).siblings('.campaignCode').val();
			if (offerID != null && "null" != (offerID)) {
				data = data + 'purchaseOffer=' + offerID + '&';
			}
			if (campaignCode != null && "null" != (campaignCode)) {
				data = data + 'campaignCode=' + campaignCode + '&';
			}
			if (tproductID != null && "null" != (tproductID)) {
				data = data + 'purchaseProduct=' + tproductID;
			}
		}
		
		$.ajax({
			type: 'post',
			url : '/ajax/userRegister.php',
			data: data,
			cache: false, 
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactWideModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				alreadyUser();
				ajaxRegister();
			}
		});
	});
}

function makeDownloadDirectButtons() {
	//alert('test');
	$('.downloadMovie').click(function (e) {
		e.preventDefault();
		inputElement = $(this).parents('form').find('input:radio:checked');
		offerID = $(inputElement).siblings('.offerID').val();
		torrentDrmTypeID = $(inputElement).siblings('.torrentDrmTypeID').val();
		tproductID = $(inputElement).siblings('.productID').val();
		downloadDirect(tproductID, offerID, torrentDrmTypeID, true);
	});
	$('.downloadById').click(function (e) {
		//the id of the object must be in format X[productId]_[offerId]_[torrentDrmTypeId]
		//X can be anything. It's there just to help you create unique ids...
		e.preventDefault();
		var total = $(this).attr('id');
	
		var productIdAndOfferIdAndTorrentDrmTypeId = total.substr(1,total.length);
		var productId = productIdAndOfferIdAndTorrentDrmTypeId.substr(0,productIdAndOfferIdAndTorrentDrmTypeId.indexOf("_"));
		var offerIdAndTorrentDrmTypeId = productIdAndOfferIdAndTorrentDrmTypeId.substr(productIdAndOfferIdAndTorrentDrmTypeId.indexOf("_")+1, productIdAndOfferIdAndTorrentDrmTypeId.length);
		var offerId = offerIdAndTorrentDrmTypeId.substr(0,offerIdAndTorrentDrmTypeId.indexOf("_"));
		var torrentDrmTypeId = offerIdAndTorrentDrmTypeId.substr(offerIdAndTorrentDrmTypeId.indexOf("_")+1, offerIdAndTorrentDrmTypeId.length);
		
		var checkComputer = true;
		if (total.substr(0,1) == "x") {
			checkComputer = false;
		}
		
		if(productId != 0) {
			downloadDirect(productId, offerId, torrentDrmTypeId, checkComputer);
		} else {
			bundleDownloadDirect(offerId, torrentDrmTypeId, checkComputer);
		}
	});
	$('.downloadBundle').click(function (e) {
		e.preventDefault();
		
		inputElement = $(this).parents('form').find('input:radio:checked');
		offerID = $(inputElement).siblings('.offerID').val();
		
		//bundleDownloadDirect(offerId, torrentDrmTypeId, true);
		bundleDownloadDirect(offerID, 2, true); // force computer check
	});
	
	$('.targetedDownload').click(function() {
		var box = $(this);
		
		var offerId;
		var type;
		offerIdAndTorrentDrmTypeId = $('.rentOfferIdAndTorrentDrmTypeId:checked');
		if($(offerIdAndTorrentDrmTypeId).is('input')) {
			offerIdAndTorrentDrmTypeId = $('.rentOfferIdAndTorrentDrmTypeId:checked').val();
			offerId = offerIdAndTorrentDrmTypeId.substr(0, offerIdAndTorrentDrmTypeId.indexOf("_"));
			type = 1;
		} else {
			str = $(this).attr('id');
			offerId = str.split('_')[1];
			type = 2;
		}
		
		$.ajax({
			type: 'post',
			url : '/ajax/selectTargetedUploadInvite.php',
			data: 'offerID='+offerId,
			cache: false, 
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				
				selectTargetedDownload();
				makeTooltip();
				$('.applyInvite').click(function() {
					var torrentID = $('input#torrentID').val();
					var upUserID = '';
					$('.selectTargetedInvite').find(':checked').each(function(e) {
						if(upUserID.length > 0) {
							upUserID = upUserID+':'+$(this).val();
						} else {
							upUserID = $(this).val();
						}
					});
					var speed = parseInt($('#speedLimit').val());
					var force = $('#force').is(':checked');
					$.ajax({
						type: 'post',
						url : '/ajax/selectTargetedUploadInvite.php',
						data: 'selectTargetedInvite=true&torrentID='+torrentID+'&uploaderID='+upUserID+'&speed='+speed+'&force='+force,
						cache: false, 
						success: function(data){
						
						}
					});
					
					if(type == 1) {
						$(box).removeClass('targetedDownload');
					}
					makeDownloadDirectButtons();
					$.modal.impl.close(true);
					if(type == 1) {
						$(box).click();
					}
				});
			}
		});
	});
}

function advancedTargetedDownload() {
	$('.selectTargetedInvite').find('.advanced').unbind().click(function() {
		var box = $(this).parents('.selectTargetedInvite');
		var inviteOfferID = $(box).siblings('#inviteOfferID').val();
		$.ajax({
			type: 'post',
			url : '/ajax/selectTargetedUploadInvite.php',
			data: 'advanced=true&offerID='+inviteOfferID,
			cache: false, 
			success: function(data){
				$(box).html(data);
				selectTargetedDownload();
			}
		});
	});
	$('.submitInviteForm').click(function(e) {
		e.preventDefault();
		if($('#targetedInvite').is('form')) {
			$('#targetedInvite').submit();
		}
		//;
	});
}

function selectTargetedDownload() {
	
	function clickEffectNoUsers(e) {
		if($(e).is(':checked')) {
			$('.allUsers').addClass('disable');
			if(!$('#force').is(':checked')) {
				$('.speedLimit').addClass('disable');
				$('#speedLimit').attr('disabled', 'disabled');
			}
		} else {
			$('.allUsers').removeClass('disable');
			if(!$('#force').is(':checked')) {
				$('.speedLimit').removeClass('disable');
				$('#speedLimit').removeAttr('disabled');
			}
		}
	}
	
	if($('#force').is(':checked')) {
		$('.speedLimit').addClass('disable');
		$('#speedLimit').attr('disabled', 'disabled');
	}
	
	$('.allUsers').find('input:checkbox').click(function() {
		if($('.allUsers').find('input:checked').is(':checked')) {
			if($('#allUsers').is(':checked')) {
				$('#allUsers').removeAttr('checked');
				clickEffectNoUsers($('#allUsers'));
				//$('#allUsers').click();
			}
		} else {
			if(!$('#allUsers').is(':checked')) {
				$('#allUsers').attr('checked', 'checked');
				clickEffectNoUsers($('#allUsers'));
				//$('#allUsers').click();
			}
		}
	});
	
	$('#allUsers').click(function() {
		clickEffectNoUsers($(this));
	});
	
	$('#force').click(function() {
		if(!$('#allUsers').is(':checked')) {
			if($(this).is(':checked')) {
				$('.speedLimit').addClass('disable');
				$('#speedLimit').attr('disabled', 'disabled');
			} else {
				$('.speedLimit').removeClass('disable');
				$('#speedLimit').removeAttr('disabled');
			}
		}
	});
	
	$('input:radio').click(function() {
		$('#speedLimit').val($(this).val());
	});
}

function checkComputerForDRM(productId, offerId, torrentDrmTypeId, checkComputer) {
	var checked = $.cookie('bigCheck');
	if (checked != "true" && torrentDrmTypeId != 1 && checkComputer) {
		if(!isAllowedOS()) {
			$.ajax({
				type: 'post',
				url: '/ajax/nonWindows.php',
				data: 'productId='+productId+'&offerId='+offerId+'&torrentDrmTypeId='+torrentDrmTypeId+'&box=true',
				cache: false,
				dataType: "html",
				success: function(data){
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactModalContainer',
						iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
					makeDownloadDirectButtons();
				}
			});
			return true;
		} else {
			$.cookie('bigCheck', 'true', {expires: 999, path: '/'});
		}
	}
	return false;
}

function bundleDownloadDirect(offerId, torrentDrmTypeId, checkComputer) {
	//if (!checkComputerForDRM(0, offerId, torrentDrmTypeId, checkComputer)) {
		$.ajax({
			type: 'post',
			url : '/ajax/productBuy.php',
			data: 'buyDirect=1&bundle=1&offerId='+offerId+'&productID=0',
			cache: false, 
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactWideModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				advancedTargetedDownload();
				makeTooltip();
				initiateCreditCardAndPayPal();
			}
		});
	//}
}

function downloadDirect(productId, offerId, torrentDrmTypeId, checkComputer) {
	if (!clickedOnDownload) {
		if (!checkComputerForDRM(productId, offerId, torrentDrmTypeId, checkComputer)) {
			$.ajax({
				type: 'post',
				url : '/ajax/productBuy.php?productID='+productId,
				data: 'buyDirect=true&productID='+productId+'&offerId='+offerId,
				cache: false, 
				success: function(data){
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactWideModalContainer',
						iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
					advancedTargetedDownload();
					makeTooltip();
					initiateCreditCardAndPayPal();
				}
			});
		}
	}
	clickedOnDownload = true;
}
function makeAddToWishlistButtons() {
	$('.addToWishlist').click(function (e) {
		e.preventDefault();
		addToWishlist($(this).attr('id'));
	});
}
function addToWishlist(Id) {
	$.ajax({
		type: 'post',
		url : '/account/content_wishlist.php',
		data: 'addProduct='+Id+'&ajax=true',
		cache: false, 
		success: function(data){
			style = $('#addToWishlist').children('a').attr('style');
			$('#addToWishlist').children('a').remove();
			$('#addToWishlist').append(data).children('span').attr('style', style);
		}
	});
}

function makeBuyProductsInCartButton() {
	$('.buyProductsInCart').click(function (e) {
		e.preventDefault();
		
		var product = $('#buyForm').children('table').children('tbody').children('tr.rowOdd:first');
		var price = 0;
		
		var length = $('#buyForm').children('table').children('tbody').children('tr').length;
		var i = 0;

		while(i<length) {
			i++;			
			if($(product).children('td:first').children('label').children(':checkbox').is(':checked')) { // If the first product is chosen
				price = price + parseFloat( $(product).children('td:first').children('.price').val() ); // Add it's price
				
			}
			product = $(product).next();
		}
		
		if(price > 0) {
			$.ajax({
				type: 'post',
				url : '/cart.php',
				data: 'buy=true&price='+price,
				cache: false, 
				success: function(data){
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactModalContainer',
						iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
				}
			});
		} else {
			$.ajax({
				type: 'post',
				url : '/cart.php',
				data: 'buy=true&cart=empty',
				cache: false, 
				success: function(data){
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactModalContainer',
						iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
				}
			});
		}
	});
}

function makeBuyButton() {
	$('.cssButtonBuy').click(function (e) {
		e.preventDefault();

		var firstProduct = $('#buyForm').children('table').children('tbody').children('tr.rowOdd:first');
		var price = 0;
		if($(firstProduct).children('td:first').children('label').is('.chosen')) { // If the first product is chosen
			price = parseFloat( $(firstProduct).children('td:first').children('.price').val() ); // Add it's price
		}
		var nextProduct = $(firstProduct).next();
		//while(false) {
			if($(nextProduct).children('td:first').children('label').is('.chosen')) {
				price = price + parseFloat( $(nextProduct).children('td:first').children('.price').val() ); // Add it's price
			}
			nextProduct = $(firstProduct).next();
			if(!$(nextProduct).is('tr')) {
				//break;
			}
		//}

		$.ajax({
			type: 'post',
			url : '/cart.php',
			data: 'buy=true&price='+price,
			cache: false, 
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
			}
		});
	});
}

function submitOnEnter(e,f) {
	var characterCode
	if(e && e.which) {
		e = e;
		characterCode = e.which;
	} else{
		e = event;
		characterCode = e.keyCode;
	}
	if(characterCode == 13) {
		f.submit();
		return false;
	} else{
		return true;
	}
}

function searchAjax(searchPrevValIndex) {
	// searchPrevVal - global array with input values
	var currVal = $.trim($('#searchQ').val()); // The current value without starting and ending whitespaces 
	
	if(searchPrevVal[searchPrevValIndex-1] == searchPrevVal[searchPrevValIndex]) { // If this request has the same search query as the previous, fix for very fast writers
		return;
	}
	
	var prevVal = $.trim(searchPrevVal[searchPrevValIndex]); // The previous value without starting and ending whitespaces
	
	if(currVal != prevVal) { // If the user has written somthing since the function call
		return;
	}
	
	if(currVal.length >= 2) { // It must be more then 2 chars
		var searchStr = $('#searchQ').val();
		//alert(searchStr);
//		searchStr = searchStr.replace(/å/,"A_LOWER");
//		searchStr = searchStr.replace(/ä/,"AE_LOWER");
//		searchStr = searchStr.replace(/ö/,"O_LOWER");
//		searchStr = searchStr.replace(/Ö/,"A_UPPER");
//		searchStr = searchStr.replace(/Ö/,"AE_UPPER");
//		searchStr = searchStr.replace(/Ö/,"O_UPPER"); 
		//alert(searchStr);
		$.ajax({
			type: 'post',
			url : '/productlisting.php',
			data: 'ajax=true&searchQ=' + searchStr,
			cache: false, 
			success: function(data){
				if($('#searchResultdiv').is(':visible')) { // If the searchresult is visible, we don't slide it down again
					$('#searchResultdiv').html(data); // Update the result 
				} else {
					$('#searchResultdiv').html(data).slideDown(500);
				}
				$('#closeSearch').click( function() { // Eventlistner for the close button
					$('#searchResultdiv').slideUp(500);
				});
			}
		});
	} else { // If the user didn't supply a valid search string
		if($('#searchResultdiv').is(':visible')) { // If the result is shown
			$('#searchResultdiv').slideUp(500, function() {$('#searchResultdiv').html('')}); // First hide it then remove it
		}
	}
}

function getDownloadStatus(td, offerPurchaseId, torrentId) {

	$.ajax({
		type: 'get',
		url : '/downloadStatus.php',
		data: 'offerPurchaseId=' + offerPurchaseId + '&torrentId=' + torrentId,
		cache: false, 
		success: function(data){
			td.html(data);
		}
	});
	
	setTimeout(function() {getDownloadStatus(td,offerPurchaseId,torrentId);}, (1000 * 5));
}

function makeUnlockTorrentButtons() {
	$(".unlockTorrent").each(function () {
		$(this).css("cursor","pointer");
	});
	$(".unlockTorrent").click(function (e) {
		e.preventDefault();
		ids = $(this).attr('id');
		var torrentId = ids.substr(6, ids.indexOf("_")-6);
		var offerPurchaseId = ids.substr(ids.indexOf("_")+1,ids.lastIndexOf("_")-ids.indexOf("_")-1);
		var drmProviderId = ids.substr(ids.lastIndexOf("_")+1);
		var url = null;
		if (drmProviderId == 1) { //Ezdrm
			url = "/drm/ezdrm/predeliver_license.php?torrentId="+torrentId+"&opId="+offerPurchaseId;
		} else if (drmProviderId == 2) { //Ameibo
			url = "/drm/ameibo/predeliver_request.php?torrentId="+torrentId+"&opId="+offerPurchaseId;
		}
		
		eval("page" + ids + " = window.open(url, '" + ids + "', 'toolbar=1,scrollbars=0,location=1,statusbar=0,menubar=0,resizable=1');");
	});
}

function makeCloseAndReloadOpenerButtons() {
	$(".closeAndReloadOpener").each(function () {
		$(this).css("cursor","pointer");
	});
	$(".closeAndReloadOpener").click(function (e) {
		var torrentId = $("#torrentId").val();
		var offerPurchaseId = $("#offerPurchaseId").val();
		window.opener.$("#unlock" + torrentId + "_" + offerPurchaseId).html('<img src="/image/unlocked.png">');
		window.close();
	});

}

function showProgressBar() {
	$(".showProgressBar").each(function (i) {
		var nextTd = $(this).next();
		var inputbox = $(nextTd).children("input");
		var ids = $(inputbox).val();
		var offerPurchaseId = ids.substr(0,ids.indexOf(","));
		var torrentId = ids.substr(ids.indexOf(",")+1, ids.length);
		getDownloadStatus($(this), offerPurchaseId, torrentId);
	});
}

/*
 * The first time a user visits ameibo.com we check if the browser is IE
 */
function browserCheck() {
	var checked = $.cookie('isBrowserChecked');
	//var checked = "false";
	if (checked != "true") {
		$.cookie('isBrowserChecked', 'true', {expires: 999, path: '/'})
		$.ajax({
			type: 'post',
			url : '/browserCheck.php',
			cache: false, 
			success: function(data){
				if (data != "true") {
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactModalContainer',
							iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
				}
			}
		});	
	}
}

/*
 *
 */
function makeBrowserNotSupportedButtons() {
	$(".browserNotSupported").each(function () {
		$(this).css("cursor","pointer");
	});

	$(".browserNotSupported").click(function (e) {
		$.ajax({
			type: 'post',
			url : '/browserNotSupported.php',
			cache: false, 
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
						iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
			}
		});	
	});	
}


function startDownload(t) {
	var td = t.parent().prev();
	var inputbox = t.next().get(0);
	var ids = $(inputbox).val();
	var offerPurchaseId = ids.substr(0,ids.indexOf(","));
	var torrentId = ids.substr(ids.indexOf(",")+1, ids.length);
	var prevTd = td.prev();
	prevTd.empty();
	getDownloadStatus($(prevTd), offerPurchaseId,torrentId);
	t.css("background-position","0 -29px");
	
	//document.location="downloadTorrent.php?op_id=" + offerPurchaseId + "&torrent_id=" + torrentId;
}

function redirectUserToPosten() {
	$('.payPalButton').hide();
	$('#paypalPayment').hide();
    $('.creditCardPayment').hide();
    $('.creditCardPaymentButton').attr('src', '/image/loader.gif');
	$('#creditCardPaymentDiv').show();
    var amount = $('#formAmount').val();
    amount = Math.round(amount * 100);
    $('#Amount').attr('value', amount);
    
    $.ajax({
        type: 'post',
        url : '/ajax/createPostenCallbackKey.php',
        data: 'amount=' + $('#formAmount').val() + '&callbackKey=' + $('#callbackKey').val(),
        cache: false,
        success: function(data){
		var paymentType = $('#paymentType').val();
		var macData = null;

		if (paymentType == 'CC') {
			macData = 'paymentType=' +  $('#paymentType').val() +
				'&Merchant_id=' +  $('#Merchant_id').val() +
				'&Version=' +  $('#Version').val() +
				'&Customer_refno=' +  $('#Customer_refno').val() +
				'&Currency=' +  $('#Currency').val() +
				'&Amount=' +  $('#Amount').val() +
				'&VAT=' +  $('#VAT').val() +
				'&Payment_method=' +  $('#Payment_method').val() +
				'&Purchase_date=' +  $('#Purchase_date').val() +
				'&Response_URL=' +  escape($('#Response_URL').val()) +
				'&Goods_description=' +  $('#Goods_description').val() +
				'&Language=' +  $('#Language').val() +
				'&Comment=' +  $('#Comment').val() +
				'&Country=' +  $('#Country').val() +
				'&Cancel_URL=' +  escape($('#Cancel_URL').val());
		} else if (paymentType == 'Sub') {
			macData = 'paymentType=' +  $('#paymentType').val() +
				'&Merchant_id=' +  $('#Merchant_id').val() +
				'&Version=' +  $('#Version').val() +
				'&Customer_refno=' +  $('#Customer_refno').val() +
				'&Transaction_id=' +  $('#Transaction_id').val() +
				'&Amount=' +  $('#Amount').val() +
				'&VAT=' +  $('#VAT').val() +
				'&Response_URL=' +  escape($('#Response_URL').val()) +
				'&Request_type=' +  $('#Request_type').val();
		}

		$.ajax({
		  type: 'post',
		  url : '/ajax/calculatePostenMAC.php',
		  data: macData,
		  cache: false,
		  success: function(data){
			$('#MAC').attr('value', data);
			$('.userDepositForm').submit();
		  }
		});
            //do nothing
        }
    });
    

}

function generateInitialPayPalRequest() {
	var formAmount = $('#formAmount').val();
	$.ajax({
		type: 'post',
		url : '/ajax/intialPayPalRequest.php',
		data: 'paymentAmount='+formAmount,
		cache: false,
		success: function(data){
			if (window.execScript) {
				window.execScript('var payPalInttialResponse = '+data+';');
			} else {
				eval('payPalInttialResponse = '+data);
			}
			if (payPalInttialResponse['SUCCESS'] != null) {
				window.location = payPalInttialResponse['SUCCESS'];
            } else if (payPalInttialResponse['ERROR'] != null) {
				//show error message
			} else {
				//this cannot happend
            }
		}
	});
	$('.creditCardPayment').hide();
    $('.creditCardPaymentButton').hide();
	$('#paypalPayment').hide();
	$('.payPalButton').attr('src', '/image/loader.gif');
	$('#paypalPaymentDiv').show();
	
}

function initiateCreditCardAndPayPal() {
	$('#creditCardPayment').click( function(e) {
		if ($(this).is(':checked') && checkDepositAmount()) {
			redirectUserToPosten();
		} else {
			$(this).removeAttr('checked');
		}
	});
	$('.creditCardPaymentButton').click( function(e) {
		if (checkDepositAmount()) {
			redirectUserToPosten();
		} else {
			$('#creditCardPayment').removeAttr('checked');
		}
	});
	$('.payPalButton').click( function(e) {
		if (checkDepositAmount()) {
			generateInitialPayPalRequest();
		} else {
			$(this).removeAttr('checked');
		}
	});	
	$('#paypalPayment').click( function(e) {
		if ($(this).is(':checked') && checkDepositAmount()) {
			generateInitialPayPalRequest();
		} else {
			$(this).removeAttr('checked');
		}
	});
	$('.userSubscriptionDeposit').click(function() {
		var element = $(this);
		var data = '';
		$("#details").find("input, select").each(function() {
			if(data != '') {
				data = data + "&";
			}
			data = data + $(this).attr("name") + "=" + $(this).val();
		});
		var url = $(this).parents('form').attr('action');
		$.ajax({
			type: 'post',
			url : url,
			data: 'ajax=true&'+data,
			cache: false,
			success: function(data){
				data = data.split('|');
				if(data[0] != 'true') {
					input = data[2].split(':');
					msg = data[1].split(':');
					for(i = 0; i < input.length; i++) {
						if(input[i] == 'amount') {
							input[i] = 'formAmount';
						}
						$('input#'+input[i]).addClass('inputError');
						$('input#'+input[i]).parents('td').find('.red').remove();
						$('input#'+input[i]).parents('td').prepend('<div class="red"><b>'+msg[i]+'</b></div>');
						//$('input#'+input[i]).addClass('inputError');
					}
					$('.inputError').focus(function() {
						$(this).removeClass('inputError');
						$(this).blur(function() {
							$(this).parents('td').find('.red').remove();
						});
					});
				} else {
					$(element).parents('.content').hide();
					$(element).parents('.textblock').append('<div class="contentNew"></div>');
					$(element).parents('.textblock').find('.contentNew').html(data[1]);
					makeCssButtons();
					editDeposit();
				}
			}
		});
	});

	$('.resetSubscription').click(function() {
		$.ajax({
			type: 'post',
			url : '/ajax/userDeposit.php',
			data: 'reset=true',
			cache: false,
			success: function(data){
				$('#details').after(data).remove();
				initiateCreditCardAndPayPal();
			}
		});
	});
}

function checkDepositAmount() {
	var formAmount = $('#formAmount').val();
	if (formAmount == null || formAmount == '' || !isNumeric(formAmount) || formAmount < 2) { //minimum deposit amount defined in class_config.php
		$('#formAmount').addClass('inputError');
		return false;
    }
	$('#formAmount').removeClass('inputError');
	return true;
}

function isNumeric(sText) {
   var validChars = "0123456789.";
   var isNumber = true;
   var character;

   for (i = 0; i < sText.length && isNumber == true; i++) {
      character = sText.charAt(i);
      if (validChars.indexOf(character) == -1) {
         isNumber = false;
      }
   }
   return isNumber;

}

function makeDownloadTorrentButton() {

	$('.downloadTorrentButton').click(function() {
		startDownload($(this));


	//This is removed in favor of old javascript confirm...
	/*
		var t = $(this);
		ids = $(this).attr('id');
		var offerPurchaseId = ids.substr(15, ids.indexOf("_")-15);
		var torrentId = ids.substr(ids.indexOf("_")+1,ids.length);
		alert(offerPurchaseId);

		$.ajax({
			type: 'post',
			url: '/checkIfTorrentIsUnlocked.php',
			data: 'offerPurchaseId=' + offerPurchaseId + '&torrentId=' + torrentId,
			cache: false, 
			success: function(data){
				if (data == "true") {
					startDownload(t);
				} else {
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactModalContainer',
							iframeId: 'contactModalIframe',
						onOpen: fader.open,
						onClose: fader.close
					});
				}
			}
		});
	*/
	});

}

function snifferUnlockedIcons() {
	$(".unlockTorrent").each(function (i) {
		var obj = $(this);
		var ids = $(this).attr('id');
		var torrentId = ids.substr(6, ids.indexOf("_")-6);
		var offerPurchaseId = ids.substr(ids.indexOf("_")+1,ids.length);
		
		//alert('torrentId: '+torrentId);
		//alert('offerPurchaseId'+offerPurchaseId);

		$.ajax({
			type: 'post',
			url : '/checkIfTorrentIsUnlocked.php',
			data: 'offerPurchaseId=' + offerPurchaseId + '&torrentId=' + torrentId,
			cache: false, 
			success: function(data){
				//alert(data);
				if (data == "true") {	
					obj.parent().html('<img src="/image/unlocked.png">')
				}
			}
		});
	});
	setTimeout("snifferUnlockedIcons()", (1000 * 5));

}

function makeDownloadTorrentButtonFromModal() {
	$('.downloadTorrentButtonFromModal').click(function() {
		ids = $(this).attr('id');
		var offerPurchaseId = ids.substr(20, ids.indexOf("_")-20);
		var torrentId = ids.substr(ids.indexOf("_")+1,ids.length);
		startDownload($("#downloadTorrent" + offerPurchaseId + "_" + torrentId));
	});
}

function makeNoMoreTestCheckbox() {
	$('#noMoreTest').click(function() {
		if ($('#noMoreTest:checked').length == 1) {
			//set cookie
			$.cookie('bigCheck', 'true', {expires: 999, path: '/'});
		} else {
			//delete cookie
			$.cookie('bigCheck', null);
		}
	});
}

function setNextButtonActive( box ) {
	if(box == 1) {
		$('#nextFeatured').removeClass('disabled');
	} else {
		$('#nextSeed').removeClass('disabled');
	}
}

function setPrevButtonActive( box ) {
	if(box == 1) {
		$('#prevFeatured').removeClass('disabled');
	} else {
		$('#prevSeed').removeClass('disabled');
	}
}

function makeRemoveHeaderMessageButton() {
	$(".removeHeaderMessage").click(function() {
		var obj = $(this).parent().parent();
		obj.fadeOut(300, function () {
			//obj.remove();
			var val = obj.attr("id");
			var messageId = val.substr(1,val.length);
			$.get("/ajax/removeMessage.php?messageId=" + messageId);
		});
	});
}

function makeTooltip() {
	$('.tooltip').Tooltip({
		delay: 0,
		track: true,
		extraClass: 'tooltipBox',
		showURL: false
	 });
	 
	 $('.tooltipRight').Tooltip({
		delay: 0,
		track: true,
		extraClass: 'tooltipBox',
		showURL: false,
		right: true
	 });
}

function makeAutoexpand() {
	$('#reviewText').Autoexpand([400,500]);
}

function tabListeners() {
	$(".productTab").find(".ajaxlink").each(function() {
		var txt = $(this).text();
		var className = $(this).attr("class");
		var parent = $(this).parent();
		$(this).remove();
		$(parent).append('<span class="'+className+'">'+txt+'</span>');
	});
	
	internalProductTab();
	
	$('.ajaxlink').parents('.productTab').click(function() {
		clickProductTab($(this));
    });
}

function internalProductTab() {
	$('.clickTab').click(function(e) {
		e.preventDefault();
		var str = $(this).attr('class');
		str = str.split('{')[1];
		str = str.split('}')[0];
		$('#'+str).click();
	});
}

function clickProductTab(tab) {
	
	var str = $(tab).find('.ajaxlink').attr("class");
	var url = str.substr(str.indexOf("{")+1, str.indexOf("?")-str.indexOf("{")-1);
	var params = str.substr(str.indexOf("?")+1, str.indexOf("}")-str.indexOf("?")-1);
	
	if($(tab).find('.ajaxlink').is('.doNotUseAjax')) {
		window.location = url;
	} else {
		//find the box to replace
		var box = $('.ajaxContent');
	
		//remove the active tab and set new active
		$(tab).siblings().removeClass("active");
		$(tab).addClass("active");
	
		$(box).css("cursor", "wait");
		
		$.ajax({
			type: 'post',
			url: url,
			data: params,
			cache: false, 
			dataType: "html",
			success: function(data){
				
				$(box).html(data);
	
				$(box).css("cursor", "default");
				
				internalProductTab();
				makeButtons();
				makeTooltip();
				
				if(window.resizeTextarea) {
					resizeTextarea();
				}
				if(window.makeProductRate) {
					makeProductRate();
				}
	
				if(window.makeRateReview) {
					makeRateReview();
				}
				
				if(window.makeSynopsisSelectBox) {
					makeSynopsisSelectBox();
				}
	
				if(window.makeUserReviewRate) {
					makeUserReviewRate();
				}
				
				if(window.postProductComment) {
					postProductComment();
				}
			}
		});
	}

	//$(tab).addClass('productTabActive').removeClass('productTab');
	//$(tab).siblings('.productTabActive').addClass('productTab').removeClass('productTabActive');
				
	//$(this).parent('.productTabs').siblings('.productInfo').children('.productRight').text(url);
		
}

function targetedUploadInvite() {
	$('.targetedUploadInviteIcon').click(function() {
	var str = $(this).attr('id');
	var data = str.split(':');
	
		$.ajax({
			type: 'post',
			url: '/ajax/targetedUploadInvite.php',
			data: 'productID='+data[1]+'&torrentID='+data[2]+'&url='+escape(data[3]),
			cache: false, 
			dataType: "html",
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				
				var element = $(data).find('.addFriend');
				
				targetedUploadInviteAddFriend();
				targetedUploadInviteAddMovie();
			}
		});
	});
}

function targetedUploadInviteAddFriend() {
	$('.addFriendLink').click(function() {
		var element = $(this).siblings('input:first');
		var name = $(element).attr('name');
		
		var number = parseInt(name.substr(name.indexOf('[') + 1, 1));
		if(number < 10) {
			number++;
			var nameTag = name.substr(0, name.indexOf('['));
			var newElement = $(element).clone().attr('name', nameTag+'['+number+']').attr('value', '');
			$(element).before(newElement);
		}
		if(number >= 10) {
			$(this).remove();
		}
	});
}

function targetedUploadInviteAddMovie() {
	$('.addMovieLink').click(function() {
	var box = $(this);
		$.ajax({
			type: 'post',
			url: '/ajax/targetedUploadInvite.php',
			data: 'getActiveMovies=true&torrentIdAlreadyLoaded='+$('#mainTorrentId').val(),
			cache: false, 
			dataType: "html",
			success: function(data){
				$(box).parents('.addMovie').append(data);
				$(box).parent('p').remove();
			}
		});
	});
}

function indexReloadBundles() {
	$('.bundlePromo').children('.reload').click(function() {
		var box = $(this).parents('.bundlePromo');
		$.ajax({
			type: 'post',
			url: '/ajax/indexRandomBundle.php',
			data: '',
			cache: false, 
			dataType: "html",
			success: function(data){
				$(box).children('ul').fadeOut(100, function() {$(box).children('ul').html(data).fadeIn(100)});
			}
		});
    });
}

function indexReloadReviews() {
	$('.reviewPromo').children('.reload').click(function() {
		var box = $(this).parents('.reviewPromo');
		$.ajax({
			type: 'post',
			url: '/ajax/indexRandomReview.php',
			data: 'productCategoryId=' + $('#productCategoryId').val(),
			cache: false, 
			dataType: "html",
			success: function(data){
				$(box).children('ul').fadeOut(100, function() {$(box).children('ul').html(data).fadeIn(100)});
			}
		});
    });
}

function getTextAndModalIt() {
	$('.getTextInModal').click(function() {
		var textKey = $(this).attr('class');
		textKey = textKey.split('{')[1];
		textKey = textKey.split('}')[0];
		textKey = textKey.split(':');
		$.ajax({
			type: 'post',
			url: '/ajax/getTextKey.php',
			data: 'titleKey='+textKey[0]+'&textKey='+textKey[1]+'&box=true',
			cache: false, 
			dataType: "html",
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
			}
		});
    });
}

function openBitEasierPopup(url, windowName, height, width) {
	window.open( url, windowName, 
	"dependent = 0, status = 0, menubar=0, location=0, height = "+height+", width = "+width+", resizable = 0" )
}

function clickDownloadButton(modal) {
	$('.startDownload').removeClass('modalClose').unbind('click');
	$('.startDownload').click(function(e) {
		e.preventDefault();
		id = $(this).attr('id');
		beta = '';
		if($(this).is('.beta')) {
			beta = '&beta=true';
		}
		openBitEasierPopup('/account/download.php?key='+id+beta, 'window_'+id, 465, 630);
		if($(this).is('.bigButton')) {
			$(this).addClass('grey');
		}
		$(this).removeClass('startDownload').unbind('click');
		if(modal != null){
			modal.close(false);
		}
	});
}

function openDownloadBox() {
	$('.openDownloadBox').click(function(e) {
		e.preventDefault();
		id = $(this).attr('id');
		var torrentID = id.split('_')[1];
		$.ajax({
			type: 'post',
			url: '/ajax/productDownloadBox.php',
			data: 'torrentID='+torrentID,
			cache: false, 
			dataType: "html",
			success: function(data){
				var modal = $(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'modalDownloadBox'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				clickDownloadButton(modal);
			}
		});
	});
}

function makeSynopsisSelectBox() {
	$('.synopsisSelectBox').change(function() {
		var parent = $(this).parents('.story');
		var languageId = $(this).val();
		var productId = $('#productID').val();
		$.ajax({
			type: 'post',
			url: '/ajax/reloadSynopsis.php',
			data: 'languageId='+languageId+'&productID='+productId,
			cache: false, 
			dataType: "html",
			success: function(data){
				parent.find('.lineheight').text(data);
			}
		});		
    });
}

function preventDefault(e) {
	e.preventDefault();
}

function addKeywordListener() {
	$('.addKeyword').find('.button').click(function(e) {
		addKeyword();
	});
}

function addKeyword() {
	var keyword = $('input#keyword').val()
	keyword = keyword.replace(/^\s+|\s+$/g, ''); // trim the whitespaces
	$('input#keyword').val('');
	if(keyword != '') {
		$('ul.keywords').children('.noKeywords').remove();
		$('ul.keywords').prepend('<li>'+keyword+'</li>');
		var productID = $('#productID').val();
		$.ajax({
			type: 'post',
			url: '/ajax/productKeywords.php',
			data: 'productID='+productID+'&keyword='+keyword,
			cache: false, 
			dataType: "html"
		});
	}
}

function makeKeywordSuggest() {
    $("#keyword").suggest("/ajax/suggestKeyword.php?", {
		onSelect: function() {
            addKeyword();
		}
	});
}

function showMoreKeywords() {
	$('.showMoreKeywords').click(function() {
		$(this).parent().siblings('.keywords').children(':hidden').show();
		$(this).remove();
	});
}

function pushFacebookListener() {
	$('.pushFacebook').click(function() {
		if(window.makeFacebookPush) {
			makeFacebookPush();
		}
	});
}

function postProductComment() {
	$('#commentSubmit').click(function (e) {
		e.preventDefault();
		var form = $(this).parents('form');
		var data = 'comment[productID]='+$('#productID').val();
		$(form).find("input, textarea").each(function() {
			if($(this).is(':checkbox')) {
				if($(this).is(':checked')) {
					data = data + '&'+$(this).attr("name") + "=" + $(this).val();
				}
			} else {
				data = data + '&'+$(this).attr("name") + "=" + $(this).val();
			}
		});
		$(form).find('.inputError').removeClass('.inputError');
		$(form).find('b.red').remove();
		$(form).find('.money').remove();
		$.ajax({
			type: 'post',
			url : '/ajax/productComment.php',
			data: data,
			cache: false, 
			success: function(data){
				data = data.split('|');
				if(data[0] == 'false') {
					msg = data[1].split(':');
					input = data[2].split(':');
					
					for(i = 0; i < input.length; i++) {
						if($('input#'+input[i]).is(':checkbox')) {
							$('input#'+input[i]).parent().addClass('inputError').focus(function() {
								$(this).removeClass('inputError');
							});
						} else {
							$('#'+input[i]).before('<b class="red" style="display:block;">'+msg[i]+'</b>')
								.addClass('inputError').focus(function() {
									$(this).removeClass('inputError');
									$(this).prev('b.red').remove();
								});
						}
						$('input#'+input[i]).parents('td, th').prepend('<div class="red"><b>'+msg[i]+'</b></div>');
					}
				} else {
					$(form).find("input, textarea").each(function() {
						if(!$(this).is('.button')) {
							$(this).val('');
						} else {
							$(this).before('<h3 class="money" style="margin: 5px 0;">'+data[1]+'</h3>');
						}
					});
					$('ul#comments').prepend(data[2]);
				}
			}
		});
	});
}

function postBlogComment() {
	$('.blogCommentSubmit').click(function (e) {
		e.preventDefault();
		var form = $(this).parents('form');

		var arr = $(this).attr("id").split('_');
		var articleId = arr[1];
		var data = 'comment[articleId]='+articleId;
		
		$(form).find("input, textarea").each(function() {
			if($(this).is(':checkbox')) {
				if($(this).is(':checked')) {
					data = data + '&'+$(this).attr("name") + "=" + $(this).val();
				}
			} else {
				data = data + '&'+$(this).attr("name") + "=" + $(this).val();
			}
		});
		$(form).find('.inputError').removeClass('.inputError');
		$(form).find('b.red').remove();
		$(form).find('.money').remove();
		$.ajax({
			type: 'post',
			url : '/ajax/blogComment.php',
			data: data,
			cache: false,
			success: function(data){
				data = data.split('|');
				if(data[0] == 'false') {
					msg = data[1].split(':');
					input = data[2].split(':');

					for(i = 0; i < input.length; i++) {
						if($(form).find('input#'+input[i]).is(':checkbox')) {
							$(form).find('input#'+input[i]).each(function(){
								$(this).parent().addClass('inputError').focus(function() {
									$(this).removeClass('inputError');
								});
							});
						} else {
							$(form).find('#'+input[i]).before('<b class="red" style="display:block;">'+msg[i]+'</b>')
								.addClass('inputError').focus(function() {
									$(this).removeClass('inputError');
									$(this).prev('b.red').remove();
								});
						}
						$(form).find('input#'+input[i]).parents('td, th').prepend('<div class="red"><b>'+msg[i]+'</b></div>');
					}
				} else {
					$(form).find("input, textarea").each(function() {
						if(!$(this).is('.button')) {
							$(this).val('');
						} else {
							$(this).before('<h3 class="money" style="margin: 5px 0;">'+data[1]+'</h3>');
						}
					});
					$('ul#comments_' + articleId).prepend(data[2]);
				}
			}
		});
	});
	//First set initial visibility
	$('.doCommentTogglerShow').show();
	//then attach mouse event listeners
	$('.doCommentTogglerShow').click(function(e){
		e.preventDefault();
		var arr = $(this).attr("id").split('_');
		var divId = 'blogCommentDiv_' + arr[1];
		var togglerHideId = 'doCommentTogglerHide_' + arr[1];
		var this_id = $(this).attr("id");
		$('#'+divId).fadeIn('medium', function(){
			$('#'+this_id).hide();
			$('#'+togglerHideId).show();
		});
		
	});

	$('.doCommentTogglerHide').click(function(e){
		e.preventDefault();
		var arr = $(this).attr("id").split('_');
		var divId = 'blogCommentDiv_' + arr[1];
		var togglerShowId = 'doCommentTogglerShow_' + arr[1];
		var this_id = $(this).attr("id");
		$('#'+divId).fadeOut('medium', function(){
			$('#'+this_id).hide();
			$('#'+togglerShowId).show();
		});
	});

	$('.permalinkToggler').click(function(e){
		e.preventDefault();
		var arr = $(this).attr("id").split('_');
		var divId = 'permalinkDiv_' + arr[1];
		if($('#'+divId).is(':visible')){
			$('#'+divId).fadeOut('medium');
		} else {
			$('#'+divId).fadeIn('medium');
		}
	});
}



function changeCommentOrder() {
	$('.changeCommentOrder').click(function() {
		$(this).siblings('#comments').fadeOut('fast', function() {
			var newListOrder = $(this).clone().html(''); // Create empty list
			$(this).children('li').each(function() {
				$(newListOrder).prepend($(this));
			});
			$(this).html($(newListOrder).html());
			$(this).fadeIn('fast');
		});
	});
}

function userReport() {
	$('.userReport').click(function() {
		$(this).unbind('click').removeClass('userReport');
		button = $(this);
		$.ajax({
			type: 'post',
			url : '/ajax/userReport.php',
			data: 'data='+$(this).children('input').val(),
			cache: false, 
			success: function(data){
				temp = data.split('|');
				$(button).text(temp[0]);
				data = temp[1];
				if($(button).is('.userReportComment')) {
					$(data).modal({
						close: false,
						overlayId: 'contactModalOverlay',
						containerId: 'contactWideModalContainer',
						iframeId: 'contactModalIframe'
						//onOpen: fader.open,
						//onClose: fader.close
					});
					$('.sendReportComment').click(function(e) {
						comment = $('.reportComment').val();
						alert($('.reportComment').val());
						$.ajax({
							type: 'post',
							url : '/ajax/userReport.php',
							data: 'reportID=' + $(data).find('#reportID').val() + '&comment=' + comment,
							cache: false, 
							success: function(data){
								
							}
						});
						$.modal.close();
					});
				}
			}
		});
	});
}

function contentOwnerMarketingLinkGenerator() {
	$('.linkGenerator').click(function(e) {
		e.preventDefault();
		$.ajax({
			type: 'post',
			url : '/ajax/linkGenerator.php',
			data: 'data='+$(this).attr('id'),
			cache: false,
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
				contentOwnerMarketingLinkGeneratorOutput();
			}
		});
	});
}

function contentOwnerMarketingLinkGeneratorOutput() {
	$('#customLocation').keyup(function(e) {
		$.ajax({
			type: 'post',
			url : '/ajax/linkGeneratorOutput.php',
			data: 'movieStringId='+$('#movieStringId').val()+"&inviteTypeId="+$('#inviteTypeId').val()+"&customLocation="+$(this).val(),
			cache: false,
			success: function(data){
				$('#generatedLinkTextArea').val(data);
			}
		});
	});

	$('#movieStringId').change(function(e) {
		$('#exampleText').find('a').text($(this).children(':selected').text());
		$.ajax({
			type: 'post',
			url : '/ajax/linkGeneratorOutput.php',
			data: 'movieStringId='+$(this).val()+"&inviteTypeId="+$('#inviteTypeId').val()+"&customLocation="+$('#customLocation').val(),
			cache: false,
			success: function(data){
				$('#generatedLinkTextArea').val(data);
			}
		});
	});
}

function showAllGenresListener() {
	$('.showAllGenres').click(function() {
		$('#genreList.leftList').find('.leftListRow.hidden').show();
		$(this).parents('.leftListRow, .leftListRowBottom').remove();
	});
}

function adultDialogueOpener() {
	$('#adultDialogueOpener').click(function(e) {
		e.preventDefault();
		$.ajax({
			type: 'post',
			url : '/ajax/adultDialogue.php',
			data: 'data='+$('#adultDialogueOpenerUrl').val(),
			cache: false,
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
			}
		});
	});
}

/**
 * Remove all url-breaking characters to not confuse mod-rewrite.
 */
function fixSearchQ(q) {
	q = q.replace(/\s/g, '+');
	q = q.replace('/', '+');
	q = q.replace('?', '+');
	q = q.replace('&', '+');
	//remove duplicate plus-signs:
	q = q.replace(/(\+){2,}/g, "+");
	q = escape(q);
	return q;
}

$(document).ready(function() { // When the entire site is loaded

	$("ul.dropdown li").each(function() {
		$(this).hover(function(){
			$(this).addClass("hover");
			$('> .dir',this).addClass("open");
			$('ul:first',this).css('visibility', 'visible');
		},function(){
			$(this).removeClass("hover");
			$('.open',this).removeClass("open");
			$('ul:first',this).css('visibility', 'hidden');
		});
	});

	makeAutoexpand();
	
	makeTooltip();
	
	//browserCheck();
	
	showProgressBar();
	makeUnlockTorrentButtons();
	makeCloseAndReloadOpenerButtons();
	snifferUnlockedIcons();

	makeDownloadTorrentButton();
	makeDownloadTorrentButtonFromModal();
	
	makeBrowserNotSupportedButtons();

	makeRemoveHeaderMessageButton();

	adultDialogueOpener();

	searchPrevVal.push('');
	$('#searchQ').parents('form').submit( function(e) {
		e.preventDefault();
		temp = new String(window.location);
		tempPos = temp.indexOf('/', 8); // After https://
		if(tempPos == -1) {
			tempPos = temp.length;
		}
		url = temp.substr(0, tempPos);
		searchQ = $(this).find('#searchQ').val();
		searchQ = fixSearchQ(searchQ);
		window.location = url + '/search/' + searchQ;
	});

	$("#searchQ").suggest("/ajax/suggestSearch.php?",{
		onSelect: function() {
			val = $("#searchQ").val();
			val = fixSearchQ(val);
			$("#searchQ").val('');
			temp = new String(window.location);
			tempPos = temp.indexOf('/', 8); // After https://
			if(tempPos == -1) {
				tempPos = temp.length;
			}
			url = temp.substr(0, tempPos);
			window.location = url + '/search/' + val;
		}
	});
/*
	$("#searchQ").keypress(function(e) {
		if(e.which == 13 || e.keyCode == 13) { // Enter
			e.preventDefault();
			val = $(this).val();
			$(this).val('')
			//addActor(val);
		}
	});
*/
/*
	$('#searchQ').keyup( function(e) { // Bind keyup events in searchfield
		if(e.keyCode != 13 || e.keyCode != 27) { // Not enter or escape
			var index = searchPrevVal.push(''); // Save the current searchvalue
			searchPrevVal[index-1] = $('#searchQ').val();
			setTimeout(function () { searchAjax( index-1 )}, 500); // Call the searchfunction with a delay in ms
		}
	});
*/
	makeBuyButton();
	makeCssButtons();
	makeMustLoginButtons();
	makeDownloadDirectButtons();
	makeAddToWishlistButtons();
	makeBuyProductsInCartButton();
	
	tabListeners();
	
	targetedUploadInvite();
	
	indexReloadBundles();
	indexReloadReviews();
	
	getTextAndModalIt();
	clickDownloadButton(null);
	openDownloadBox();
	makeSynopsisSelectBox();
	
	addKeywordListener();
	showMoreKeywords();
	
	postProductComment();
	postBlogComment();
	changeCommentOrder();
	userReport();
	
	initiateCreditCardAndPayPal();

	contentOwnerMarketingLinkGenerator();

	showAllGenresListener();

    //Do not use for now. Danbe 20091121
    //makeKeywordSuggest();
	
	// Smooth menu dropdown
	$('.subTabs').css("display","none");
	$('.tab, .tabActive').hover(function()
	{
		//$(this).children('.subTabs').css("display","none");
		//$('embed').hide();

		$('.flashContainer').css("visibility","hidden");
		
		$(this).siblings('.tab, .tabActive').children('.subTabs:visible').stop().css("display","none"); // Stop all animations and hide all subtabs that are visible
		
		if($(this).children('.subTabs').is(':visible')) { // If the menu still is visible
			$(this).children('.subTabs').stop().slideDown("fast"); // Stop the animation and slide the menu down
		} else {
			$(this).children('.subTabs').slideDown("fast"); // Slide the menu down
		}
	}, function () {
		$('embed').show();
	
		if($(this).children('.subTabs').is(':visible')) {
			$(this).children('.subTabs').stop().slideUp("fast"); // When the mouse dosn't hover, we hide the menu
		}
		$('.flashContainer').css("visibility","visible");
	});
	
	// Added to not affect the non-javascript behaviour
	// We add classes that only javascript handles
	$(".rightBoxTabs").children('.rightBoxTabActive').addClass('JTabActive');
	$(".rightBoxTabs").children('.rightBoxTab').addClass('JTab');
	
	// Switch box-tabs and load new content
	$(".rightBoxTabs").children(':not(.noAjax)').click( function() { // If a tab is clicked
		var boxData = $(this).parent('.rightBoxTabs').next('.rightBoxData'); // The databox
		
		$(this).addClass('JTabActive').removeClass('JTab'); // Switch class of the clicked tab from non-active to active
		$(this).siblings('.JTabActive').addClass('JTab').removeClass('JTabActive'); // Switch all other active tabs to non-active
		
		var tabName = $(this).attr("id");
		var url = tabUrl[tabName];
		var post = tabPost[tabName];
		
		
		if($(boxData).children('.boxContent').is('div')) {
			//Loader for the slider boxes
			//$(boxData).children('.boxContent').load('template.php?text=Funkar');
			$(boxData).children('.boxContent').children('table'). // Fade away the old visible content
			hide(200, 
				function() {
					$(boxData).children('.boxContent').remove(); // Remove all previous loaded content
					$.ajax({
						type: 'post',
						url: url,
						data: post,
						cache: false, 
						success: function(content){
							var box = $(boxData).append('<div class="boxContent"></div>'). // Create a new div for the fetch content
								children('.boxContent').addClass('boxActive');
							
							$(box).css('display', 'none').html(content).show(100); // First hide it then fill it with data and last show it
							
							var nextImage = $(boxData).children('.boxNextContent').children('.nextContentButton');
							
							if($(boxData).children('.boxContent').children('table').is('.last')) {
								if($(nextImage).is(':visible')) {
									$(nextImage).fadeOut('slow');
								}
							} else {
								if($(nextImage).is(':hidden') && $(boxData).children('.boxContent').children('table').is('table')) {
									$(nextImage).fadeIn('slow');
								}							
							}
						}
					});
				}
			);			
			
			var prevImage = $(boxData).children('.boxPrevContent').children('.prevContentButton'); // The image that slides previous loaded content
			if( ($(prevImage).is(':visible')) ){ // If it's visible
				$(prevImage).fadeOut('slow'); // We hide it, because there is no previous loaded content, this is new content
			}
			
		} else {
			//Loader for normal boxes that only wants to change the data and doesn't have any sliders
			$.ajax({
				type: 'post',
				url: url,
				data: post,
				cache: false, 
				success: function(content){
					$(boxData).html(content);
				}
			});
		}
    });
   	$('.showTrailerLink').click(function (e){
		e.preventDefault();
		var id = $(this).attr('id');
		var productId = id.split('_')[1];
		$.ajax({
			type: 'post',
			url: '/ajax/trailerModal.php',
			data: 'productId='+productId,
			cache: false,
			success: function(data){
				$(data).modal({
					close: false,
					overlayId: 'contactModalOverlay',
					containerId: 'contactWideModalContainer',
					iframeId: 'contactModalIframe'
					//onOpen: fader.open,
					//onClose: fader.close
				});
			}
		});
	});

});
