function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

function strstr( haystack, needle, bool ) {
    var pos = 0;
    haystack += '';
    pos = haystack.indexOf( needle );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}
	window.onload = function(){
		$('form').each(function(){ this.reset();});
		$('input[value="Add this"]').removeAttr("disabled");
		$('input[value="Remove"]').attr("disabled","disabled");
	}
	function UpdateAllCosts(thisID){
		id = $(thisID).parent().parent().find("input:eq(0)").attr("id");
		UpdateDICost(id);
		var section = $("#"+id).attr("class");
		CalculateTotalDCost(section);
	}
	$(document).ready(function(){
      Init();
	});
	function Init(){
		$("input.NumericOnly").numeric();
		$("input.Days").numeric('Ä');
		$("input.Months").numeric('Ä');
		$("input.Days, input.Impressions").bind("blur", function(){
			var minVal = ($(this).attr("minVal")!=undefined)?$(this).attr("minVal"):0;
			var maxVal = ($(this).attr("maxVal")!=undefined)?$(this).attr("maxVal"):99999999;
			var currVal = ($(this).val()) ? parseInt($(this).val()) : 0;
			var Type = ($(this).hasClass("Impressions")) ? "impressions" : "days";
			if($(this).hasClass("Months")) Type = "months";
			var Units = ($(this).hasClass("Impressions")) ? "Lacs" : "";
			if(currVal > maxVal){
				$(this).val(maxVal);
				UpdateAllCosts(this);
				alert("The number of "+Type+" cannot be greater than "+maxVal+" "+Units);
			} else if(currVal < minVal){
				$(this).val(minVal);
				UpdateAllCosts(this);
				alert("The number of "+Type+" cannot be less than "+minVal+" "+Units);
			}else{
				UpdateAllCosts(this);
			}
		});
		$("input.Days, input.Impressions").bind("keyup", function(){
			UpdateAllCosts(this);
		});
		$("input.Days").bind("keyup",function(){
		   var thisID = $(this).attr('id');
		   var impressionsID = thisID.replace('_days','_impressions');
		   var daysVal = $(this).val();
		   var impressionsMaxVal = daysVal;
		   $('#'+impressionsID).attr('maxval',impressionsMaxVal);
		});
	}
/////////////////
	function EnableDays(id, section){
		var cbid = $(id).children(":first").attr("id");
		if($(id).children(":first").is(':checked')){
			$("#"+cbid+"_days").removeAttr("disabled");
			var nid = $(id).children(":first").attr("id");
			UpdateDICost(nid);
			$(id).next(".TextData").show();
		}else{
			$("#"+cbid+"_cost").html("");
			$("#"+cbid+"_days").attr("disabled","disabled");
			$(id).next(".TextData").hide();
		}
		CalculateTotalDCost(section);
	}
	function EnableDaysRadio(id, section){
		var cbid = $(id).children(":first").attr("id");
		var pid = $(id).parent().parent().parent().parent().attr("id");
		if($(id).children(":first").is(':checked')){
			$("#"+pid+" .Days").attr("disabled","disabled");
			$("."+section+"Costs").html("");
			$(id).next(".TextData").hide();
			$("#"+cbid+"_days").removeAttr("disabled");
			var nid = $(id).children(":first").attr("id");
			UpdateDICost(nid);
			$(id).next(".TextData").show();
		}
		CalculateTotalDCost(section);
	}
/////////////////
	function CalculateTotalDViews(section){
		var IndiView = 0;
		$("#"+section+"FormData .Impressions").each(function(i){
			if(!$(this).attr("disabled")){
				var ThisView = parseFloat($(this).val());
				IndiView = IndiView + ((isNaN(ThisView))?0:(ThisView));
			}
		});
		$('#Total'+section+'View').html(roundNumber(IndiView, 2));
	}
	function CalculateTotalDCost(section){
		var IndiCost = 0;
		$("."+section+"Costs").each(function(i){
			var ThisCost = parseFloat($(this).html().replace(/,/g,''));
			IndiCost = IndiCost + ((isNaN(ThisCost))?0:(ThisCost));
		});
		$('#Total'+section+'Cost').html(number_format(roundNumber(IndiCost, 2)));
		if ($('#Total'+section+'View').length > 0) CalculateTotalDViews(section);
	}
	function UpdateDICost(id){
		var cbid = id;
		var ThisCost = $("#"+cbid).attr("cost");
		var Days = $("#"+cbid+"_days").val();
		var Impressions = ($("#"+cbid+"_impressions").length != 0 )? $("#"+cbid+"_impressions").val() : 1;
		var Cost = parseFloat(ThisCost) * parseFloat(Days)* parseInt(Impressions);
		display_cost = number_format(roundNumber(((isNaN(Cost))?0:(Cost)), 2));
		$("#"+cbid+"_cost").html(display_cost);
	}
	function EnableImpressionsNDays(id, section){
		var cbid = $(id).children(":first").attr("id");
		if($(id).children(":first").is(':checked')){
			$("#"+cbid+"_impressions").removeAttr("disabled");
			$("#"+cbid+"_days").removeAttr("disabled");
			var nid = $(id).children(":first").attr("id");
			UpdateDICost(nid);
			$(id).next(".TextData").show();
		}else{
			$("#"+cbid+"_cost").html("");
			$("#"+cbid+"_impressions").attr("disabled","disabled");
			$("#"+cbid+"_days").attr("disabled","disabled");
			$(id).next(".TextData").hide();
		}
		CalculateTotalDCost(section);
	}
	var TotalFinalCost = 0;
	var TotalFinalViews = 0;
	function AddThis(id, self){
	   var browser=navigator.appName;
      var b_version=navigator.appVersion;
      var version=parseFloat(b_version);
	   //Total Cost
	   var newID = $('#'+id+' .HiddenSpan').text();
	   if($('#Total'+newID+'Cost').text()==0){
	      alert("Please Make a Selection!");
	      return;
	   }
	   var TotalCost = parseFloat($('#'+id+' .CostID').html().replace(/,/g,''));
	   TotalFinalCost += TotalCost;
	   var Title = $('#'+id+' .HiddenSpan').html();
	   var TitleNew = Title.replace(/_/g, " ");
	   var CartCostData = '<div id="'+Title+'CostCart"><h3>'+TitleNew+'</h3><table width="100%"><tr><td>Price (INR)</td><td align="right"><span class=".CartIndiCost">'+number_format(TotalCost)+'</span></td></tr></div>'
	   if($('#cart').text() == "No items in your cart"){
	      $('#cart').html(CartCostData);
	   }else{
	      $('#cart').append(CartCostData);
	   }
	   //TotalViews
	   if($('#'+id+' .ViewID').html() != null){
	      var TotalViews = parseFloat($('#'+id+' .ViewID').html());
	      TotalFinalViews += TotalViews;
	      var Title = $('#'+id+' .HiddenSpan').html();
	      var TitleNew = Title.replace(/_/g, " ");
	      var CartViewsData = '<div id="'+Title+'ViewsCart"><h3>'+TitleNew+'</h3><table width="100%"><tr><td>Views (Lacs)</td><td align="right"><span class=".CartIndiViews">'+TotalViews+'</span></td></tr></div>'
	      if($('#viewsCart').text() == "No items in your cart"){
	         $('#viewsCart').html(CartViewsData);
	      }else{
	         $('#viewsCart').append(CartViewsData);
	      }
	      $("#FinalViewsDisplay").text(TotalFinalViews);
	   }
      $("#FinalCostDisplay").text(number_format(TotalFinalCost));
	   //////////
	   var DataOld = $('#'+id).html();
	   $('#'+id+' input:checked').each(function(){
	      $(this).attr('checkud','checked');
	   });
	   if(browser=="Microsoft Internet Explorer"){
	      $('#'+id+' input').each(function(){
	          var currVal = $(this).val();
	          $(this).removeAttr('value');
	          $(this).val(currVal);
	      });
	   }else{
	      $('#'+id+' input').each(function(){
	          var currVal = $(this).val();
	          $(this).removeAttr('value');
	          $(this).attr('valud', currVal);
	      });
	   }

	   var Data = $('#'+id).html();
	   Data = Data.replace(/checkud=/g,"checked=");
	   Data = Data.replace(/CHECKUD=/g,"CHECKED=");
	   if(browser!="Microsoft Internet Explorer"){
	      Data = Data.replace(/valud=/g,"value=");
	      Data = Data.replace(/VALUE=/g,"VALUE=");	      
	   }
	   var NewDiv = '<div id="'+id+'_Submission" style="display: none;">'+Data+'</div>';
	   var NewDiv2 = '<div id="'+id+'_Submission2" style="visibility: hidden">'+Data+'</div>';
	   $('#'+id).html(Data);
	   $("#SubmissionForm").append(NewDiv);
      $('#'+id).block({ 
            message: '<center>Selection Locked<br /><input class="Remove InputButton" type="button" value="Change Selection" onclick="RemoveThis(\''+id+'\', this)" /></center>', 
            css: { border: '2px solid #888' } 
      });
      $('#'+id+' .blockOverlay').fadeTo(0, 0.65);
	}
	function RemoveThis(id, self){
	   var TotalCost = parseFloat($('#'+id+' .CostID').html().replace(/,/g,''));
	   TotalFinalCost -= TotalCost;
	   var Title = $('#'+id+' .HiddenSpan').html();
	   if($('#'+id+' .ViewID').html() != null){
   	   var TotalViews = parseFloat($('#'+id+' .ViewID').html());
   	   TotalFinalViews -= TotalViews;
   	   $("#FinalViewsDisplay").text(TotalFinalViews);
	   }
	   $('#'+Title+'CostCart').remove();
	   $('#'+Title+'ViewsCart').remove();
	   $('#'+id+"_Submission").remove();
	   if($('#cart').text() == ""){
	      $('#cart').html("<span>No items in your cart</span>");
	   }
	   if($('#viewsCart').text() == ""){
	      $('#viewsCart').html("<span>No items in your cart</span>");
	   }
	   $('#'+id+' .Overlay').css('display', 'none'); 
	   $('#'+id+' .Overlay').html("");
	   $("#FinalCostDisplay").text(number_format(TotalFinalCost));
	   $('#'+id).unblock(); 
	   Init();
	}
////////////
