$(document).ready(function() {
	Cufon.replace('.offertabs li a');	
	Cufon.replace('ul#topnav li a');	
	
	$('.tbNewMember .trInput input').focus(function(){
		var offset=$(this).offset();
		var nleft=$(this).width()+offset.left+20;
		var ntop=offset.top;
		$(this).parent().find('span').css({'left':nleft,'top':ntop}).fadeIn('500');
	});
	
	$('.tbNewAdvertiser .trInput input').focus(function(){
		var offset=$(this).offset();
		var nleft=offset.left;
		var ntop=$(this).height()+offset.top+20;
		$(this).parent().find('span').css({'left':nleft,'top':ntop}).fadeIn('500');
	});
	
	$('.trInput input').blur(function(){
		$(this).parent().find('span').fadeOut('100');
	});
	
	$("ul#topnav li").hover(function() { //Hover over event on list item
		$(this).css({'background': '#000','opacity':'0.8','filter':'alpha(opacity=80)'}); //Add background color and image on hovered list item
		//$("ul#topnav li span").css({'background': '#000','opacity':'1','filter':'alpha(opacity=100)'});
		$(this).find("span").css({'background': '#000','opacity':'1','filter':'alpha(opacity=50)'}).show(); //Show the subnav
	}, function() { //on hover out...
		$(this).css({ 'background' : 'none','opacity':'1','filter':'alpha(opacity=100)'}); //Ditch the background
		$(this).find("span").hide(); //Hide the subnav
	} );

	$('.trInput').find('span').append("<div class='inputHint-arrow-border'></div><div class='inputHint-arrow'></div>");
	$("ul#topnav li:has(span)").find("a:first").append("&nbsp;&nbsp;<img src='templates/rwdpalace/images/arrowdown.png' style='margin-top:7px;position:absolute;'>&nbsp;&nbsp;");
	$(".offertab_content").hide(); //Hide all content
	$("ul.offertabs li:first").addClass("active").show(); //Activate first tab
	$(".offertab_content:first").show(); //Show first tab content
	$('#regMember').addClass('selectedReg');
	//On Click Event
	$(".offertabs li").live("click",function() {
		
	$(".offertabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".offertab_content").hide(); //Hide all tab content
		Cufon.replace('.offertabs li a');	
		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});
	
	$('a.poplight[href^=#]').click(function() {
    var popID = $(this).attr('rel'); //Get Popup Name
    var popURL = $(this).attr('href'); //Get Popup href to define size

    //Pull Query & Variables from href URL
    var query= popURL.split('?');
    var dim= query[1].split('&');
    var popWidth = dim[0].split('=')[1]; //Gets the first query string value

    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="adPopupClose"><img src="templates/rwdpalace/images/close_pop.png" class="adImgPopupClose" title="Close Window" alt="Close" /></a>');

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;

    //Apply Margin to Popup
	
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });

    //Fade in Background
    $('body').append('<div id="adFade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#adFade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 

    return false;
});

	//Close Popups and Fade Layer
	$('a.adPopupClose, #adFade').live('click', function() { //When clicking on the close or fade layer...
		if ($(this).hasClass('noclickfade')){
		}
		else{
			$('#adFade , .adPopup').fadeOut(function() {
				$('#adFade, a.adPopupClose').remove();  //fade them both out
			});
		}
		return false;
	});

	$('#adTitle').keydown(function(){
		printRemainingTitleSize(this,'adTitleRSize');
	});
	
	$('#adTitle').keyup(function(){
		printRemainingTitleSize(this,'adTitleRSize');
	});

	$('#adDesc').keydown(function(event){
		printRemainingDescSize(this,event,'adDescRSize');
	});	
	
	$('#adDesc').keyup(function(event){
		printRemainingDescSize(this,event,'adDescRSize');
	});
	
	$('#showingtime').change(function(){
		changeAdClass();
		checkToPurchase('');
	});
	
	$('#limit').change(function(){
		var value=$(this).val();
		if (value=='0'){
			$('#limitvalue').hide();
		}
		else{
			$('#limitvalue').show().focus();
		}		
	});
	
	$('#country').change(function(){
		var value=$(this).val();
		if (value=='0'){
			$('#setupfee').hide();
			$('#country2').hide();
		}
		else{
			$('#setupfee').show();
			$('#country2').show();
		}		
		checkToPurchase('');
	});
	
	$('#ecountry').change(function(){
		var value=$(this).val();
		if (value=='0'){
			$('#esetupfee').hide();
			$('#ecountry2').hide();
                       
		}
		else{
			$('#esetupfee').show();
			$('#ecountry2').show();
                       
		}		
		checkToPurchase('Edt');
	});
	
	
	$("#addCr").keyup(function(){
		checkToPurchase('');
	});
	
	$("#addCr").keydown(function(){
		checkToPurchase('');
	});
	
	$("#addCr").focus(function(){
		checkToPurchase('');
	});
	
	$("#addCr").blur(function(){
		checkToPurchase('');
	});
	
	$('#addAdsDesc').click(function(){
		checkToShowDesc(this,'');
		checkToPurchase('');
	});
	
	$('#useCoupon').click(function(){
		checkToShowCoupon(this,'');
		//checkToPurchase('');
	});
	
	$('#adCoupon').keydown(function(){
		$('#adCouponAvailable').html('');
	});
	
	$('#checkCoupon').click(function(){
		checkCoupon('');
	});
	
	$(".onlyNum").keydown(function(event) {
		numericKeyDown(this,event);
	});
	//edit
	$('#adTitleEdt').keydown(function(){
		printRemainingTitleSize(this,'adTitleRSizeEdt');
	});
	
	$('#adTitleEdt').keyup(function(){
		printRemainingTitleSize(this,'adTitleRSizeEdt');
	});
	
	$('#adDescEdt').keydown(function(event){
		printRemainingDescSize(this,event,'adDescRSizeEdt');
	});	
	
	$('#adDescEdt').keyup(function(event){
		printRemainingDescSize(this,event,'adDescRSizeEdt');
	});
	
	$('#addcredit').change(function(){
		var value=$(this).val();
		if (value=='0'){
			$('#addCrEdt').hide();
		}
		else{
			$('#addCrEdt').show().focus();
		}		
	});
	
	$('#limitEdt').change(function(){
		var value=$(this).val();
		if (value=='0'){
			$('#limitvalueEdt').hide();
		}
		else{
			$('#limitvalueEdt').show().focus();
		}		
	});
	
	$("#addCrEdt").keyup(function(){
		checkToPurchase('Edt');
	});
	
	$("#addCrEdt").keydown(function(){
		checkToPurchase('Edt');
	});
	
	$("#addCrEdt").focus(function(){
		checkToPurchase('Edt');
	});
	
	$("#addCrEdt").blur(function(){
		checkToPurchase('Edt');
	});
	
	$('#useCouponEdt').click(function(){
		checkToShowCoupon(this,'Edt');
		//checkToPurchase('');
	});
	
	$('#adCouponEdt').keydown(function(){
		$('#adCouponAvailableEdt').html('');
	});

	
	$('#checkCouponEdt').click(function(){
		checkCoupon('Edt');
	});
	
	//add
	$("#addCrAdd").keyup(function(){
		checkToPurchase('Add');
	});
	
	$("#addCrAdd").keydown(function(){
		checkToPurchase('Add');
	});
	
	$("#addCrAdd").focus(function(){
		checkToPurchase('Add');
	});
	
	$("#addCrAdd").blur(function(){
		checkToPurchase('Add');
	});
	
	$('#addAdsDescEdt').click(function(){
		checkToShowDesc(this,'Edt');
		checkToPurchase('Edt');
	});
	
	$('#useCouponAdd').click(function(){
		checkToShowCoupon(this,'Add');
		//checkToPurchase('');
	});
	
	$('#checkCouponAdd').click(function(){
		checkCoupon('Add');
	});
	
	$('#adCouponAdd').keydown(function(){
		$('#adCouponAvailableAdd').html('');
	});

});

function changeAdClass(){
		var cls=$('#showingtime').attr("selectedIndex");
		var clsval=$('#showingtime').val();
		var creditRatio;
		if (cls=='0'){
			$('#adcclass').val('A');
			creditRatio=$('#ratioCreditClassA').val();
		}
		else
		if (cls=='1'){
			$('#adcclass').val('B');
			creditRatio=$('#ratioCreditClassB').val();
		}
		else
		if (cls=='2'){
			$('#adcclass').val('C');
			creditRatio=$('#ratioCreditClassC').val();
		}
		else
		if (cls=='3'){
			$('#adcclass').val('D');
			creditRatio=$('#ratioCreditClassD').val();
		}
		$('#adcreditinfo').html('1 visitor with '+clsval+' second need '+creditRatio+' link ads credit');
}

function checkToPurchase(id){
	var remaining=parseInt($('#remainingCr'+id).val());
	var add=parseInt($('#addCr'+id).val());
	var priceRatio,creditRatio,cost;
	var prodpackage=parseInt($('#productPackage'+id).val());
		if (id.length>0){
			priceRatio=$('#ratioClass').val();
			creditRatio=$('#ratioCreditClass').val();
		}
		else{
			var cls=$('#showingtime').attr("selectedIndex");
			if (cls=='0'){
				priceRatio=$('#ratioClassA').val();
				creditRatio=$('#ratioCreditClassA').val();
			}
			else
			if (cls=='1'){
				priceRatio=$('#ratioClassB').val();
				creditRatio=$('#ratioCreditClassB').val();
			}
			else
			if (cls=='2'){
				priceRatio=$('#ratioClassC').val();
				creditRatio=$('#ratioCreditClassC').val();
			}
			else
			if (cls=='3'){
				priceRatio=$('#ratioClassD').val();
				creditRatio=$('#ratioCreditClassD').val();
			}
		}
	var addCost=0;
	var setupFee=0;
	if ($('#addAdsDesc'+id).is(':checked')){
		addCost=parseInt($('.adsDescCost').val());
	}
	var value=$(this).val();
	if (value=='Non Targeted Country'){

	}
	else{
		setupFee=parseInt($('#setupFee').val());
	}	
	add=add+addCost+setupFee;
	var classcredit=roundNumber(remaining/creditRatio,2);
	var needed=roundNumber(add-classcredit,2);
	var cost=priceRatio/prodpackage;
	if (add>classcredit){
		var total=roundNumber(needed*cost,2);
		$('#crPrice'+id).val($('.currency').val()+total);
		$('#crPriceH'+id).val($('.currency').val()+total);
		$('#crDetail'+id).html("(credit balance = "+remaining+")<br>"+add+"-"+classcredit+"="+needed+" credit needed");
		$('#exceedCr'+id).val("1");
		$('#adSubmitBtn'+id).hide();
		$('#purchasePopUp'+id).show();
		if ($('#useCoupon'+id).is(':checked')){
			checkCoupon(id);
		}
	}
	else{
		$('#purchasePopUp'+id).hide();
		$('#adSubmitBtn'+id).show(); 
		$('#exceedCr'+id).val("0");
	}
	var popMargTop = ($('.adPopup').height() + 80) / 2;
    var popMargLeft = ($('.adPopup').width() + 80) / 2;
	$('.adPopup').css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });
}

function checkToShowDesc(element,id){
	if ($(element).is(':checked')){
			$('#descPopUp'+id).show();
	}
	else
	$('#descPopUp'+id).hide();
}

function checkToShowCoupon(element,id){
	if ($(element).is(':checked')){
			$('#adCouponSpan'+id).show();
			checkCoupon(id);
	}
	else{
		$('#adCouponSpan'+id).hide();
		$('#crPrice'+id).val($('#crPriceH'+id).val());
		$('#adCouponUse'+id).html('');
		$('#adCouponAvailable'+id).html('');
	}
}

function checkCoupon(id){
	var code=$('#adCoupon'+id).val();
	var price=$('#crPriceH'+id).val();
	var username=$('.username').val();
	if (code.length>0){
		$.post("includes/ajax/checkData.php",{adCoupon : code, thisProduct : "link", thisTarget: "member", cost : price, username : username},function(data){
			if (data.result=='ok'){
				$('#adCouponAvailable'+id).html('Available!');				
				$('#crPrice'+id).val($('.currency').val()+roundNumber(data.cost,2));
				$('#adCouponH'+id).val(code);
				$('#adCouponUse'+id).html(' (You are using Coupon Code : '+code+')');
			}
			else
			if (data.result=='error'){
				$('#adCouponAvailable'+id).html(data.error);		
				$('#crPrice'+id).val(price);
				$('#adCouponH'+id).val('');
				$('#adCouponUse'+id).html('');
			}
		},"json");
	}
}

function printRemainingTitleSize(element,rsizeid){
	var title=$(element).val();
	var titleSize=parseInt($('.adsTitleChar').val());
	var count=titleSize-parseInt(title.length);
	element.value=element.value.substring(0, titleSize);
	$('#'+rsizeid).html(count);
}

function printRemainingDescSize(element,event,rsizeid){
	var desc=$(element).val();
	var size=parseInt($('.adsDescChar').val());
	var count=size-parseInt(desc.length);
	if (count<0){
		event.preventDefault(); 
	}
	else{
		$('#'+rsizeid).html(count);
	}
	element.value=element.value.substring(0, size);
}

function showPopUp(id,width){
	 var popID = id; //Get Popup Name
     var popWidth = width;
		var noclickfade="";
    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) });
	if ($('#' + popID).hasClass('noclosebtn')){
		noclickfade="class='noclickfade'";
	}
	else{
	$('#' + popID).prepend('<a href="#" class="adPopupClose"><img src="templates/rwdpalace/images/close_pop.png" class="adImgPopupClose"></a>');
	}
	var popMargTop = ($('#' + popID).height() + 80) / 2;
		var popMargLeft = ($('#' + popID).width() + 80) / 2;
		var half=$(window).height()/2;
		if (popMargTop>half){
			popMargTop=half-20;
		}
		$('#' + popID).css({
				'margin-top' : -popMargTop,
				'margin-left' : -popMargLeft
		});
		$('body').append('<div id="adFade"></div>'); //Add the fade layer to bottom of the body tag.
		$('#adFade').css({'filter' : 'alpha(opacity=60)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
		return false;
}

function checkBeforeDeleteAd(credit){
	if (parseInt(credit)>0){
		alert('You must retract all remaining credits to delete this ad!');
	}
	else
	if (parseInt(credit)==0){
		return confirm('Are you sure you want to delete this ad?');
	}
	return false;
}

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return parseFloat(newnumber); // Output the result to the form field (change for your purposes)
}
