﻿var flashlogoImage = "<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='4'><tr><td width='100%' valign='middle' align= 'center' style='height:200px' height='100%'><p>"

+"<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"
			+"id='Y3' width='40' height='40'"
			+"codebase='http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab'>"
			+"<param name='movie' value='images/loader/loader.swf' />"
			+"<param name='quality' value='high' />"
			+"<param name='bgcolor' value='#ffffff' />"
			+"<param name='allowScriptAccess' value='always' />"			
	+"<embed src='images/loader/loader.swf' quality='high' bgcolor='#ffffff'"	
				+"width='40' height='40' name='Y3' align='middle'"
				+"play='true'"
				+"loop='false'"
				+"quality='high'"
				+"allowScriptAccess='always'"
				+"type='application/x-shockwave-flash'"				
				+"pluginspage='http://www.adobe.com/go/getflashplayer'>"
			+"</embed>"
	+"</object>"
+ "</p></td><tr></table>";

var calculateImpressionsLoading = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"
			+"id='Y3' width='65' height='15'"
			+"codebase='http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab'>"
			+"<param name='movie' value='images/loader/loading.swf' />"
			+"<param name='quality' value='high' />"
			+"<param name='bgcolor' value='#ffffff' />"
			+"<param name='allowScriptAccess' value='always' />"			
	+"<embed src='images/loader/loading.swf' quality='high' bgcolor='#ffffff'"	
				+"width='65' height='15' name='Y3' align='middle'"
				+"play='true'"
				+"loop='false'"
				+"quality='high'"
				+"allowScriptAccess='always'"
				+"type='application/x-shockwave-flash'"				
				+"pluginspage='http://www.adobe.com/go/getflashplayer'>"
			+"</embed>"
	+"</object>";
//+ "</p></td><tr></table>";

var calculateImpressionsLoading1 = "<img  alt='images/loader/calculating02.gif' src='images/loader/calculating02.gif' width='65' height='15'/>";
var NOSPublishers=0;
var tmpImpressions=0; 
var SelectedPublishers=new Array();     
var shownPublisherPages=null;//new Array(parseInt($(\"#hiddenNoOfRecords\").val())); \n"
var prevAmount=0; 
var modeGetter=true; 
var gA=0;
var inputCheck=true; 
var iCalculater=0; 
var validImpressionSet=false;
//var opentag;
var countVisited = 0 ;
var previousMinimumBudget = new Array();
var statusC = true;

function setEPData(iMode)
{
if (iMode!="nuller"){//if(iMode=="CPM" ||iMode=="CPC"){
$.ajax({
                 type: "POST",
                 url: "AdvertiserData.aspx?getEPData="+iMode+"&date="+new Date(),//b='+budget+"&a="+amount,
                 success: function(response)
                  {
                  if(response!="invalid"){
                     setEPDataResponse(iMode,response);
                     }
                  }
                 });
                 }
}
function setEPDataResponse(iMode,response)
{
SelectedPublishers=response.split(",");
                     //alert(response);
                     validateCampaignModification(iMode);
                     validateGrandTotal();
}

function CloseDiv(id , min)
{

     var s="";
     var tally = 0;tallystr = "";
     var validated = 1 ;
     var PublisherID = 0 ;
     var j=0,totalBudgetForThisSelector=0,i=0;
     var tempid = 0 ;
     for(j= SelectedPublishers.length ; j>0;j--)
         {
             makeO=SelectedPublishers[j-1].split("_");
             PublisherID = makeO[2];
             if(validated == 1)
             {
                 tempid = PublisherID ;
                 validated ++;
              }
             if(tempid == PublisherID)
             {
               tallystr = makeO[3];
               tally += parseInt(tallystr);
             }
         }
         if(SelectedPublishers.length >= 0)
         {
             if(SelectedPublishers.length == 0)
             {
               opentag = true;
               $("#"+id).hide(2000);
             }
             else if(min > tally)
             {
                openDialog("Budget should be greater than minimum budget");
                opentag = false;
                return;
             }
             else
             {
                opentag = true;
                $("#"+id).hide(2000);
             }
        }
        else
        {
                $("#"+id).hide(2000);
        }
}

function openDiv(id , min)
{


     statusC = checkStatusOfError();
      if(statusC == true)
       {
          if(SelectedPublishers.length >= 0)
             {
               if(SelectedPublishers.length == 0)
                {
                     opentag = true;
                     for(var i=0;i<5;i++)
                            {
                               if(document.getElementById("CloseDiv"+i)!=null)
                               {
                                    if(document.getElementById("CloseDiv"+i)!=document.getElementById(id))
                                    {
                                        $("#CloseDiv"+i).hide(2000,function(){ $("#"+id).show(1000,function(){}) } );
                                    }
                               }    
                            }
                     $("#"+id).show(1000,function(){});
                }
              else
                 {
                    opentag = true;
                    for(var i=0;i<5;i++)
                      {
                          if(document.getElementById("CloseDiv"+i)!=null)
                          if(document.getElementById("CloseDiv"+i)!=document.getElementById(id))
                          $("#CloseDiv"+i).hide(2000,function(){$("#"+id).show(1000,function(){})});
                      }
                    $("#"+id).show(1000,function(){});
                 }
            }
        else
        {
            for(var i=0;i<5;i++)
            {
                if(document.getElementById("CloseDiv"+i)!=null)
                if(document.getElementById("CloseDiv"+i)!=document.getElementById(id))
                $("#CloseDiv"+i).hide(2000,function(){$("#"+id).show(1000,function(){})});
            }
            $("#"+id).show(1000,function(){});
        }
      }
      else
      {
          openDialog("Budget should be greater than minimum budget for selected publisher ");return;
      }
}

function checkStatusOfError()
{
   // return opentag;
     var validated = 1 ;
     var tally = 0;tallystr = "",minimumBudget = "" ;
     var PublisherID = 0 ;
     var j=0,totalBudgetForThisSelector=0,i=0;
     var tempid = 0 ;
     if(SelectedPublishers.length > 0)
     {
     
     for(j = SelectedPublishers.length ; j>0;j--)
         {
             makeO=SelectedPublishers[j-1].split("_");
             PublisherID = makeO[2];
             if(validated == 1)
             {
                   tempid = PublisherID ;
                 // Giving Ajax Call For Retriving MinimumBudget
                    if(isMozilla())
                    {
                        var oXMLHTTP=new XMLHttpRequest();
                    }
                    else
                    {
                        var oXMLHTTP=new ActiveXObject( "Microsoft.XMLHTTP" );
                    }
                    if(tempid != "undefined" || tempid != 0)
                    {
                        var pl =  SelectedPublishers.length ;
                        var sURL = "_AjaxAdvertiser.aspx?PID=" + tempid +"&PL="+ pl;
                        oXMLHTTP.open( "GET", sURL, false );
                        oXMLHTTP.send(null);
                        oXMLHTTP.onreadystatechange=function()
                        {
                            alert(oXMLHTTP.readyState);
                            alert(oXMLHTTP.status);
                            if(oXMLHTTP.readyState == 4 && oXMLHTTP.status==200)
                            {
                               //alert(oXMLHTTP.responseText)
                               //minimumBudget = oXMLHTTP.responseText;
                            }
                        }
                    }   
                   minimumBudget = oXMLHTTP.responseText;
                   validated ++;
              }
             if(tempid == PublisherID)
             {
               tallystr = makeO[3];
               tally += parseInt(tallystr);
             }
         }
         if(tally < minimumBudget)
         {
           openDialog("Budget should be greater than minimum budget for selected publisher "); return;
           return false;
         }
         else
          {
           return true;
          }
        }
        else
        { 
          return true;
        }    
}

function callPage(url_)
{

     statusC = checkStatusOfError();
      if(statusC == true)
       {
         if(url_!="selected")
         {
            $("#ChannelPublisherContent").html(flashlogoImage);
            $.ajax
            ({
                 url:url_+"&date="+new Date(),
                 success: function(response) 
                 {           
                     $("#ChannelPublisherContent").html(response);
                     //$("#ChannelPublisherContent").html(shownPublisherPages[parseInt($("#CurrentPage").val())]);
                     validatePreviousSelectedPublisherDisplay();
                     changeSelect(); 
                 }
             }); 
           }
       }
      else
      {
        openDialog("Budget should be greater than minimum budget for selected publisher ");return;
      }        
}

function btnCampainDetailBack()
{
    statusC = checkStatusOfError();
      if(statusC == true)
       {
        try{
             $("#CampaignChannelPublisher").hide(showTime,function(){ $("#CampaignDetails").show(showTime);});  
                $("#CampaignChannelPublisher").hide(showTime); 
               }catch(Error){}
       }
       else
       {
         openDialog("Budget should be greater than minimum budget for selected publisher ");     return;
       }
}

function CampaignUserLogin(id)
{
if(SelectedPublishers.length<=0)
{
  openDialog("Please select at least 1 publisher.");    return;
}
else if(SelectedPublishers.length>=1)
{
      statusC = checkStatusOfError();
      if(statusC == true)
       {
            var cname="",sdate="",edate="",datastring="",strImpressionMode="",strLandingPageURL="";
            cname=$("#txtCampaignName").val();
            sdate=$("#startDate").val();
            edate=$("#endDate").val();    
            strLandingPageURL=$("#txtLandingPageURL").val();
            var s=document.getElementById("rbCPM").checked;//s=document.getElementById("rbCPC").checked;//alert(s);
            if(s)strImpressionMode="CPM";else strImpressionMode="CPC";
            datastring=cname+"x;D;x"+sdate+"x;D;x"+edate+"x;D;x"+strImpressionMode+"x;D;x"+strLandingPageURL+"x;D;x"+SelectedPublishers;
           
                $.ajax({
                         type: "POST",  
                         data: datastring,
                         url: 'AdvertiserData.aspx?'+"&date="+new Date(),//b='+budget+"&a="+amount,
                         success: function(response)
                          {
                              if(response=="certainty")
                              {
                                window.location="CampaignUpload.aspx";
                              }
                              else if(response=="Error")
                              {
                                openDialog("Error at server <br/> Please try after some time");
                              }
                          }
                         });
       }
       else
       {
         openDialog("Budget should be greater than minimum budget for selected publisher ");     return;
       }
  }
}

function getJumperSelect(channel,strImpressionMode,nor,cpage,d)
{
   statusC = checkStatusOfError();
  if(statusC == true)
   {

        $.ajax({
                 url:"_AjaxAdvertiser.aspx?channel="+channel+"&impressionMode="+strImpressionMode+"&CurrentPage="+cpage+"&nor="+nor+"&PublisherJumper="+d,
                 success: function(response)
                  {
                  $("#PublisherJumper").html('');
                  $("#PublisherJumper").html(response).show(showTime);
                  }
              });
    }
    else 
    {
       openDialog("Budget should be greater than minimum budget for selected publisher "); return;
    }         
}

function isValidURL(url)
{
    if (!/(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i.test(url)) 
    {
    $('#lblLandingPageURL').html('Invalid URL');return false;
    }
    $('#lblLandingPageURL').html();
    return true;
}


function publisherData(pdata,operation)
{
    if(operation=="add")
    {
    }
    else if(operation=="remove")
    {
    }
}
function publisherChecked(p,t)
{
    var s=p;//.id;
    var make={};make=s.split("_");
    var impressions=0;
    var Type = document.getElementById('CheckType').value;
    //alert(Type);
    impressions=$("#lbl_"+make[1]+"_"+make[2]).html();
    budget=$("#txt_"+make[1]+"_"+make[2]).val();
    var chk=$("#"+p).attr("checked");
    if(chk)
    {
        if(budget=="")
        {
                $("#lblErrorMsg_"+make[1]+"_"+make[2]).val("At least 1000 impressions"); 
                $("#lbl_"+make[1]+"_"+make[2]).html("At least 1000 impressions");
                //openDialog("At least 1000 impressions");
                 $("#"+p).attr("checked",false);publisherChecked(p,false);return;
        }
        else if(parseInt(impressions)<1000 && ( Type == "cpm" || Type == "CPM"))
        {
            if(parseInt(impressions)==0){
            $("#lblErrorMsg_"+make[1]+"_"+make[2]).val("At least 1000 impressions"); 
            $("#lbl_"+make[1]+"_"+make[2]).html("At least 1000 impressions");
            }
            $("#lbl_"+make[1]+"_"+make[2]).html("At least 1000 impressions");                           
            $("#"+p).attr("checked",false);
            //publisherChecked(p,false);
            /**********************************************************/
            var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
            if(parseInt(impressions)>0)
            { 
               if(budget=="")budget=prevAmount;              
               var pdata="pData_"+make[1]+"_"+make[2]+"_"+parseFloat(budget)+"_"+parseInt(impressions)+"_"+parseInt($("#hiddenOriginalCap_"+make[2]).val())+"_"+$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html();
               availableImpressions =parseInt(availableImpressions)+parseInt(impressions);
               //if(availableImpressions=="NaN"){}else{}
               
               if(removeItem(SelectedPublishers ,pdata)){
                 if(NOSPublishers>0)NOSPublishers--; 
                 if(availableImpressions<=parseInt($("#hiddenOriginalCap_"+make[2]).val()))
                 {
                   //$("#lbl_ImpCap_"+make[2]).html(availableImpressions).show();
                 }          
                 }
             }
             if($("#txt_"+make[1]+"_"+make[2]).val()==""){
            $("#lblErrorMsg_"+make[1]+"_"+make[2]).html("At least 1000 impressions"); 
            $("#lbl_"+make[1]+"_"+make[2]).html("At least 1000 impressions");             
            }             
             $("#lbl_"+make[1]+"_"+make[2]).html("At least 1000 impressions");
             validateImpressionCapacity(make,budget,impressions);
             validateGrandTotal();
            /***********************************************************/
            return;
        }
        else if(impressions=="Out of inventory")
        {
            //openDialog("Cant select this publisher as requested impressions are out of inventory");	 
             //$("#lbl_"+make[1]+"_"+make[2]).val("out of inventory");                 
            //$("#"+p).attr("checked",false);
            //publisherChecked(p,true);
            //return;
        }
        else if(impressions=="Invalid Amount")
        {
           //openDialog("Cant select this publisher as requested amount is invalid");	
            $("#lbl_"+make[1]+"_"+make[2]).val("Invalid amount"); 
           $("#"+p).attr("checked",false);publisherChecked(p,false);return;
        }
        else if(impressions=="invalid")
        {
           //openDialog("Cant select this publisher as requested amount is invalid");	
            $("#lbl_"+make[1]+"_"+make[2]).html("Invalid amount");  
           $("#"+p).attr("checked",false);publisherChecked(p,false);return;
        }
        else if(impressions=="Enter amount")
        {
           //openDialog("Cant select this publisher \n Enter Amount");
            $("#lbl_"+make[1]+"_"+make[2]).html("Enter Amount first");  	
           $("#"+p).attr("checked",false);publisherChecked(p,false);return;
        }  
        else if(impressions=="" || impressions=="Impressions")
        {
            //openDialog("Cant select this publisher as no budget mentioned");
             $("#lbl_"+make[1]+"_"+make[2]).val("Please enter budget first");  
            $("#"+p).attr("checked",false);publisherChecked(p,false);return;	
        }
        else if(isNaN(impressions))
        {
           //openDialog("Cant select this publisher as Invalid Impressions");
            $("#lbl_"+make[1]+"_"+make[2]).html("Invalid Impressions");  
            $("#"+p).attr("checked",false);publisherChecked(p,false);return;	
        }
        else
        {            
            var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
//            if(parseInt(availableImpressions)-parseInt(impressions)<0||parseInt(availableImpressions)<=0)
//            {
//             //openDialog("Cant select this publisher as Insufficient impressions");
//             //$("#lbl_"+make[1]+"_"+make[2]).html("out of inventory"); 
//             //$("#"+p).attr("checked",false);
//             //publisherChecked(p,false);
//             //return;	
//            }
//            else
//            {
             var pdata="pData_"+make[1]+"_"+make[2]+"_"+parseFloat(budget)+"_"+parseInt(impressions)+"_"+parseInt($("#hiddenOriginalCap_"+make[2]).val())+"_"+$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html();
            if(detectItem(SelectedPublishers ,pdata))NOSPublishers++;
             
             var makeO={};//make=pdata.split("_");1
              var makeR={};
              makeR=pdata.split("_");
              var j=0,totalBudgetForThisSelector=0,totalImpressionsForThisSelector=0;
              while (j < SelectedPublishers.length)
               {
                 makeO=SelectedPublishers[j].split("_");  
                  if(makeO[2]==makeR[2])// if (originalArray[j] == itemToDetect)
                   {  
                     totalBudgetForThisSelector+=parseFloat(makeO[3]);
                     totalImpressionsForThisSelector+= parseInt(makeO[4]);
                    }         
                     j++;                     
               }
                var remainingImpressions=parseInt(availableImpressions)-parseInt(impressions);
                remainingImpressions=parseInt($("#hiddenOriginalCap_"+make[2]).val())-totalImpressionsForThisSelector;
            //$("#lbl_ImpCap_"+make[2]).html(remainingImpressions).show();
            }
         //}
    }
    
    else // if(!chk) 
    {
    var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
            if(parseInt(impressions)>0)
            { 
               if(budget=="")budget=prevAmount;              
               var pdata="pData_"+make[1]+"_"+make[2]+"_"+parseFloat(budget)+"_"+parseInt(impressions)+"_"+parseInt($("#hiddenOriginalCap_"+make[2]).val())+"_"+$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html();
               availableImpressions =parseInt(availableImpressions)+parseInt(impressions);
               //if(availableImpressions=="NaN"){}else{}
               
               if(removeItem(SelectedPublishers ,pdata)){
                 if(NOSPublishers>0)NOSPublishers--;
                 
                  var makeO={};//make=pdata.split("_");1
              var makeR={};makeR=pdata.split("_");
              var j=0,totalBudgetForThisSelector=0,totalImpressionsForThisSelector=0;
              while (j < SelectedPublishers.length)
               {
                 makeO=SelectedPublishers[j].split("_");  
                  if(makeO[2]==makeR[2])// if (originalArray[j] == itemToDetect)
                   {  
                     totalBudgetForThisSelector+=parseFloat(makeO[3]);
                     totalImpressionsForThisSelector+= parseInt(makeO[4]);
                    }         
                     j++;  
               }
               var remainingImpressions=parseInt($("#hiddenOriginalCap_"+make[2]).val())-totalImpressionsForThisSelector;
                 if(availableImpressions<=parseInt($("#hiddenOriginalCap_"+make[2]).val()))
                 {
                 
                   //$("#lbl_ImpCap_"+make[2]).html(availableImpressions).show();
                 }  
                 if( remainingImpressions<=parseInt($("#hiddenOriginalCap_"+make[2]).val()))
                 {
                 
                   //$("#lbl_ImpCap_"+make[2]).html(remainingImpressions).show();
                 } 
                         
                 }
             }
             
              
    }
 validateGrandTotal();
}
function validateImpressionCapacity(make,budget,impressions)
{
    var pdata="pData_"+make[1]+"_"+make[2]+"_"+parseFloat(budget)+"_"+parseInt(impressions)+"_"+parseInt($("#hiddenOriginalCap_"+make[2]).val())+"_"+$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html();
            if(detectItem(SelectedPublishers ,pdata))NOSPublishers++;
             
             var makeO={};//make=pdata.split("_");1
              var makeR={};makeR=pdata.split("_");
              var j=0,totalBudgetForThisSelector=0,totalImpressionsForThisSelector=0;
              while (j < SelectedPublishers.length)
               {
                 makeO=SelectedPublishers[j].split("_");  
                  if(makeO[2]==makeR[2])// if (originalArray[j] == itemToDetect)
                   {  
                     totalBudgetForThisSelector+=parseFloat(makeO[3]);
                     totalImpressionsForThisSelector+= parseInt(makeO[4]);
                    }         
                     j++;                     
               }
             var remainingImpressions=parseInt($("#hiddenOriginalCap_"+make[2]).val())-totalImpressionsForThisSelector;
             //$("#lbl_ImpCap_"+make[2]).html(remainingImpressions).show();
}
function validateGrandTotal()
{
gA=0;
      var k=0;
      while (k < SelectedPublishers.length)
       {
          makeO=SelectedPublishers[k].split("_");
          if(makeO.length>0){
              if(parseFloat(makeO[3])>0.0){ 
                  gA+=parseFloat(makeO[3]);//+ parseFloat(make[3]);//alert(gA);
              }
          }
          k++;
       }
      $("#lblGTotal").html('');      
      $("#lblGTotal").html(gA);
}
  function validatePreviousSelectedPublisherDisplay()
  {
    if(SelectedPublishers.length>0)
    {
        var j=0;
        var spliceArr=new Array();
        var AvaliableImpressionsArr=new Array();
        while(j<SelectedPublishers.length)
        {
            var pdata=SelectedPublishers[j];            
            var make={};make=pdata.split("_");
            if(make.length>0)
            {
                var lblCap=$("#lbl_ImpCap_"+make[2]).html();
                var loopBack=true;
                if(lblCap!=null)
                {
                    var currentImpressionsAvailable=$("#lbl_ImpCap_"+make[2]).html();
                    if(parseInt(currentImpressionsAvailable)==parseInt(lblCap))
                    {
                     for(k=0;k<SelectedPublishers.length;k++)
                     {
                         var kdata=SelectedPublishers[k];
                         var make2={};make2=kdata.split("_");                     
                         if(make2[2]==make[2])
                         {
                             $("#lbl_"+make2[1]+"_"+make2[2]).html(make2[4]);
                             $("#cbx_"+make2[1]+"_"+make2[2]).attr("checked",true);                
                             $("#txt_"+make2[1]+"_"+make2[2]).attr("value",make2[3]);
                             j++;loopBack=false;
                             AvaliableImpressionsArr.push(make2);
                         }
                     }
                    }
                    else
                    {
                     spliceArr.push(j);
                    }
                }
                if(loopBack)j++;
            }
        }
        if(spliceArr.length>0)splicePublishers(spliceArr);
        validatePreviousSelectedPublisherDisplayAvaliableImpressions(AvaliableImpressionsArr);
    }
  }
  function validatePreviousSelectedPublisherDisplayAvaliableImpressions(AvaliableImpressionsArr)
  {
    for(var k=0;k<AvaliableImpressionsArr.length;k++)
    {
        var make=AvaliableImpressionsArr[k];
        var currentImpressions=$("#lbl_ImpCap_"+make[2]).html();
        var toBSubtracted=$("#lbl_"+make[1]+"_"+make[2]).html();
        var newVal=parseInt(currentImpressions)-parseInt(toBSubtracted);
        $("#lbl_ImpCap_"+make[2]).html(newVal);
    }
  }
  function splicePublishers(spliceArr)
  {
  var j=0;
    while(j<spliceArr.length)
    {
     SelectedPublishers.splice(spliceArr[j],1);
     NOSPublishers--;
     j++;
    }
    openDialog("Some selected publisher are now selected since their respective impressions are sold\n Please reselect the publisher on the basis of remaining impreesions.\n Thanks");
  }
  function detectItem(originalArray, itemToDetect)
   {   
      var j = 0;
      var itemPresent=false;  
      var makeO={};//make=pdata.split("_");1
      var makeR={};makeR=itemToDetect.split("_");
      while (j < originalArray.length)
       {
       makeO=originalArray[j].split("_");  
          if(makeO[1]==makeR[1] && makeO[2]==makeR[2])// if (originalArray[j] == itemToDetect)
           {  
             itemPresent= true;  
          }         
             j++;
             
      }   
      if (!itemPresent)
      {
      originalArray[originalArray.length]=itemToDetect;//alert("item added");
      var make={};make=itemToDetect.split("_");
      gA=0;
      var k=0;
      while (k < originalArray.length)
       {
          makeO=originalArray[k].split("_"); 
          gA+=parseFloat(makeO[3]);//+ parseFloat(make[3]);//alert(gA); 
          k++;
       }
      
      $("#lblGTotal").html('');
      //alert($("#lblGTotal").html());
      $("#lblGTotal").html(gA);
      }
      return !itemPresent;
   }
      //remove item (string or number) from an array
  
      function removeItem(originalArray, itemToRemove)
       {  
          var j = 0; 
           var itemRemoved=false; 
           var makeO={};//make=pdata.split("_");
           var makeR={};makeR=itemToRemove.split("_");
          while (j < originalArray.length)
           {
              makeO=originalArray[j].split("_");
              if(makeO[1]==makeR[1] && makeO[2]==makeR[2])//if (originalArray[j] == itemToRemove)
              {  
                 originalArray.splice(j, 1);
                 itemRemoved=true; 
                 //var make={};make=itemToRemove.split("_");
                // gA=parseFloat(gA)- parseFloat(make[3]);//alert(gA);
                 //$("#lblGTotal").html('');
                 //alert($("#lblGTotal").html());
                 //$("#lblGTotal").html(gA);
              }
              j++; 
               
          }
          if(itemRemoved==false)
          {
          //alert("Item was not present");
          } //return originalArray;
          //var make={};make=itemToDetect.split("_");
      gA=0;
      var k=0;
      while (k < originalArray.length)
       {
          makeO=originalArray[k].split("_"); 
          gA+=parseFloat(makeO[3]);//+ parseFloat(make[3]);//alert(gA); 
          k++;
       }
      $("#lblGTotal").html('');      
      $("#lblGTotal").html(gA);
          return itemRemoved;
      }
      function openDialogBox(id)
      {
         var ztagid="#Ztag"+id;
         var msg=$(ztagid).val();
         openDialog(msg) ;
      }
function openDialog(msg) 
{
    $.ui.dialog.defaults.bgiframe = true;
    $("#dialogPopup").dialog({title: '(!) Zimblee ', autoOpen: true,modal: true,closeOnEscape: true,hide: 'fold'});
    $("#dialogPopup").dialog('option', 'position', 'center');
    $("#lblDialogPopup").html(msg);
    $("#dialogPopup").dialog("open");//.hide(5000,function(){$("#dialogPopup").dialog("close");});
    //$.scrollTo(dialogPopup,  1000);
}
function openDialogCloser(msg) 
{
 $.ui.dialog.defaults.bgiframe = true;
    $("#dialogPopup").dialog({title: '(!) Zimblee ', autoOpen: true,modal: true,closeOnEscape: true,hide: 'fold'});
    $("#dialogPopup").dialog('option', 'position', 'center');
    $("#lblDialogPopup").html(msg);
    $("#dialogPopup").dialog("open");//.hide(2000);
    //$.scrollTo(dialogPopup,  1000);
}
function openDialogOver(msg,e)
{
     var x = e.x;
     var y = e.y; 
    $("#dialogPopup").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
    $("#dialogPopup").dialog({position:['left',100],resizable:false  });    
    $("#dialogPopup").dialog({minHeight:0,minWidth:0,maxHeight:200,maxWidth:20,height:30, width:100});
    $("#lblDialogPopup").html(msg);
    $("#dialogPopup").dialog("open");//.animate({opacity: "show", top:x,left:y}, "slow");
    
}
$(document).ready(function(){
	$(".menu img").hover(function() {
	  $(this).next("em").animate({opacity: "show", top: "-75"}, "slow");
	}, function() {
	  $(this).next("em").animate({opacity: "hide", top: "-85"}, "fast");
	});

});
function CloseDialog()
{
   $("#dialogPopup").dialog("close").animate({opacity: "show"}, 5000);
}
function calculateImpressions(callerId, impressionValue)
{
if(modeGetter)
   {
       modeGetter=false;
       var make={};make=callerId.split("_");
       var makeImpressions={};makeImpressions=impressionValue.split(" ");
       var amount=0;amount=$("#txt_"+make[1]+"_"+make[2]).val();
       var budget=0;budget=impressionValue;//$("#hiddenBudgetpublishersPage_"+make[1]+"_"+make[2]).val();
       var impressionsCap=0;impressionsCap=$("#lbl_ImpCap_"+make[2]).text();
       var t=true;t=isNaN(amount);
       var datastring="b:"+budget+";a:"+amount+";ic:"+impressionsCap;
       
      
       var calculatedimpressions = 0 ;
       
       
        if($("#txt_"+make[1]+"_"+make[2]).val()!="" && !(t))
        {

             if(amount<=500000)
             {
                if(makeImpressions[1] == "CPM" || makeImpressions[1] == "cpm")
                {
                   var bArray={};bArray=budget.split(" ");
                   var unitpriceforCPM = parseInt(bArray[0]);
                   if(unitpriceforCPM > amount)
                   {
                      $("#lbl_"+make[1]+"_"+make[2]).html("Minimum 1000 impressions ");return;
                   }

                    /* We are calculating Impressions for CPM manually in this function and then sending to setResponse method ... */
                    calculatedimpressions = ( amount * 1000 ) / unitpriceforCPM ;
                    calculatedimpressions = parseInt(calculatedimpressions);
                }


                if(makeImpressions[1] == "CPC" || makeImpressions[1] == "cpc")
                {
                   var bArray={};bArray=budget.split(" ");
                   var unitpriceforCPC = parseInt(bArray[0]);
                   if(unitpriceforCPC > amount)
                   {
                      $("#lbl_"+make[1]+"_"+make[2]).html("Budget should be greater than CPC");return;
                   }
                   
                    /* We are calculating Impressions for CPC manually in this function and then sending to setResponse method ... */
                    calculatedimpressions = ( amount * 1 ) / unitpriceforCPC ;
                    calculatedimpressions = parseInt(calculatedimpressions);

                }

                var cpage=document.getElementById("CurrentPage").value;
                var makeDiv=make[1]+"_"+make[2];
                $("#lbl_"+make[1]+"_"+make[2]).html(calculateImpressionsLoading);//.show();              

                   /* We are calculating Impressions for CPC / CPM manually in this function and then sending to setResponse method ... */
                           r=calculatedimpressions;
                           setResponse(r,make,impressionsCap);
                           $("#txt_"+make[1]+"_"+make[2]).focus();
                           modeGetter=true;

//                 $.ajax({
//                     type: "POST",  
//                     data: datastring,
//                     url: '_AjaxAdvertiser.aspx?'+"&date="+new Date()+"&iCalculater="+iCalculater++,//b='+budget+"&a="+amount,
//                     success: function(response)
//                      {
//                          var  r=1;r=response;
//                           setResponse(r,make,impressionsCap);
//                           $("#txt_"+make[1]+"_"+make[2]).focus();
//                           modeGetter=true;
//                       }
//                 });



         }
         else
         {
           //openDialog("Can't accept budget above 5 lacs.");
           $("#lbl_"+make[1]+"_"+make[2]).html("Can't accept budget above 5 lacs")
         }
         }
        else
        {
          $("#lbl_"+make[1]+"_"+make[2]).html("Enter amount");//.show();//.fadeOut(5000);
        }
    }
    else
    {
        var make={};make=callerId.split("_");
        $("#lbl_"+make[1]+"_"+make[2]).html("Please keep patience");//.show();
        modeGetter=true;calculateImpressions(callerId, impressionValue);
    }
}

function setResponse(response,make,impressionsCap)
{      
var Type = document.getElementById('CheckType').value;
    if(response=="ofe")
             {
             //alert("Are you ritche rich??So rich??");
             $("#lbl_"+make[1]+"_"+make[2]).html("");//.show();             
             }
             else if(response=="cpc")
             {
               $("#lbl_"+make[1]+"_"+make[2]).html("CPC awaited");//.show();
             }
             else if(false)
             {
                $("#lbl_"+make[1]+"_"+make[2]).html(response+" impressions");//.show();
             }
             else 
             {
                if(response=="invalid")//>impressionsCap || response=="infinity")
                {
                     //openDialog("We do not have that much of inventory to sell");	                
                    $("#lbl_"+make[1]+"_"+make[2]).html("Out of inventory");//.show();
                }
                else
                {
                   //if($("#lbl_"+make[1]+"_"+make[2]+"_"+make[3]+"_"+make[4]).html()=="Out of inventory"){
                    //$("#lbl_"+make[1]+"_"+make[2]+"_"+make[3]+"_"+make[4]).html("Out of inventory").show().fadeOut(0);}
                 $("#lbl_"+make[1]+"_"+make[2]).html(response+" cnn");//.show();//.fadeIn(5001);
                 $("#lbl_"+make[1]+"_"+make[2]).html(response+" ");//.show();//.fadeIn(5001);  
                 if(parseInt(response)>=0)validImpressionSet=true;               
                 if( parseInt(response)>999 && ( Type == "cpm" || Type == "CPM"))
                 {
                 $("#cbx_"+make[1]+"_"+make[2]).attr("checked",true);
                 publisherChecked($("#cbx_"+make[1]+"_"+make[2]).attr("id"),true);
                 }
                 else if(Type == "cpc" || Type == "CPC")
                 {
                     $("#cbx_"+make[1]+"_"+make[2]).attr("checked",true);
                     publisherChecked($("#cbx_"+make[1]+"_"+make[2]).attr("id"),true);
                 }
                }
             }
            
}

function changeSelect()
{
             $('#publisherJumperSelect').attr("selectedIndex", 0);             
}
function getMode(callerId,value)
{
var make=callerId.split("_");//Int16 pid, int pos,string impressionMode
   var d=new Date();
   if(modeGetter)
   {
        modeGetter=false;
        $("#ModeExpress_"+make[1]+"_"+make[2]).html(flashlogoImage);
        $.ajax({
             url:"_AjaxAdvertiser.aspx?mode="+value+"&pid="+make[1]+"&pos="+make[2]+"&ModeExpress="+new Date(),
             success: function(response)
              {
                   $("#ModeExpress_"+make[1]+"_"+make[2]).html(response).show('slide'); 
                   modeGetter=true;         
              }
         });
     }
     else
     {     
        $("#"+callerId).attr("checked",false);
        openDialog("Please wait till we fetch data for the earliar request<br/> Press Esc... ");
     }
}
function getCampaignChannelPublisherDeatils(channel,strImpressionMode,nor,cpage)
{
   var d=new Date();
    $("#ChannelPublisherContent").html(flashlogoImage); 
    $.ajax({
         url:"_AjaxAdvertiser.aspx?channel="+channel+"&impressionMode="+strImpressionMode+"&CurrentPage="+cpage+"&nor="+nor+"&date="+new Date(),
         success: function(response)
          {
             $("#ChannelPublisherContent").html(response).show(showTime);
               validateCampaignModification(strImpressionMode);
               getJumperSelect(channel,strImpressionMode,nor,cpage,d);            
          }
     });
}
function getChannelDisplay()
{
 var d=new Date();
 $.ajax({
         url:"_AjaxAdvertiser.aspx?ChannelsDisplay="+new Date(),
         success: function(response)
          {
          $("#ChannelDisplay").html('');
          $("#ChannelDisplay").html(response).show(showTime);;
          //getJumperSelect(channel,strImpressionMode,nor,cpage,d);
          }
      });
}

function checkDigits(evt,callerId)
{
var make=callerId.split("_"); 
var tVal=$("#"+callerId).val();//  
   var isThisPublisherSelected=$("#cbx_"+make[1]+"_"+make[2]).attr("checked");
         if(isThisPublisherSelected)
         {
             $("#cbx_"+make[1]+"_"+make[2]).attr("checked",false);
             publisherChecked($("#cbx_"+make[1]+"_"+make[2]).attr("id"),false);
         }
         if(isNaN(tVal))
         {            
            //$("#"+callerId).val("");
            $("#lbl_"+make[1]+"_"+make[2]).html("Invalid Amount");//.show();
            //$("#"+callerId).val("");
         }
         else
         {
            $("#lbl_"+make[1]+"_"+make[2]).html("");//.show();//.fadeIn(5001); 
            calculateImpressions(callerId,$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html());
         }
  
}
function validatedPrevious(make,budget)
{
    //var s=p;//.id;
    //var make={};make=makeO.split("_");
    var impressions=0;
    impressions=$("#lbl_"+make[1]+"_"+make[2]).html();
    //budget=$("#txt_"+make[1]+"_"+make[2]).val();
    
    var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
            if(parseInt(impressions)>0)
            { 
               if(budget=="")budget=prevAmount;              
               var pdata="pData_"+make[1]+"_"+make[2]+"_"+parseFloat(budget)+"_"+parseInt(impressions)+"_"+parseInt($("#hiddenOriginalCap_"+make[2]).val())+"_"+$("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).html();
               availableImpressions =parseInt(availableImpressions)+parseInt(impressions);
               //if(availableImpressions=="NaN"){}else{}
               $("#lbl_ImpCap_"+make[2]).html(availableImpressions);//.show();
               removeItem(SelectedPublishers ,pdata);
                 if(NOSPublishers>0)NOSPublishers--;
              }
}
function isNumberKey(evt,callerId)
{
try{
    setTimeout(isNumberKeyWait(evt,callerId),1000);//1sec
    }catch(Error){}
}
function isNumberKeyWait(evt,callerId)
{
     var charCode = (evt.which) ? evt.which : event.keyCode
     var make=callerId.split("_");
     var asciii=String.fromCharCode(charCode);//event.getAscii()
     var tVal="";tVal=$("#"+callerId).val();//+asciii;
      clearTimeout();
     if(charCode==40 || charCode==38||charCode==37||charCode==39||charCode==36||charCode==35||charCode==45||charCode==33) return;
     if ( charCode > 31 && (charCode < 48 || charCode > 57) && (charCode<96 || charCode>105) && charCode!=46)
     {
        var l1=(tVal.length);
        var s1=tVal.substr(0, l1-1);
        $("#"+callerId).val(s1);
        $("#cbx_"+make[1]+"_"+make[2]).focus();
        //setTimeout("CloseDialog()",1550);
        if(s1.indexOf(".")!=-1)$("#"+callerId).val('');;
        if(s1.indexOf("-")!=-1)$("#"+callerId).val('');;
        if($("#"+callerId).val()=="")checkDigits(evt,callerId);
      }
       else if ( charCode==189)
        {
        var l1=(tVal.length);
        var s1=tVal.substr(0, l1-1);
        $("#"+callerId).val(s1);
        $("#cbx_"+make[1]+"_"+make[2]).focus();
       }
     else
     {
            if(charCode==46 || charCode==190 || charCode==110)
            {
                var l=(tVal.length);
                var s=tVal.substr(0, l-1);
                var m= s.indexOf(".");
                var arr= tVal.split(".");
                if(m==-1)
                {
                     //$("#lbl_"+make[1]+"_"+make[2]).html("");//.show();
                     $("#lbl_strImpressionMode_"+make[1]+"_"+make[2]).focus();
                     document.getElementById("cbx_"+make[1]+"_"+make[2]).focus();
                     checkDigits(evt,callerId);
                     return;
                 }
                 else
                 {
                      $("#"+callerId).val(s);
                 }

            }
            else // checking number ---- logic
               {

                  document.getElementById("cbx_"+make[1]+"_"+make[2]).focus();
                  checkDigits(evt,callerId);
               }
     } 
   }
   function checkFocus(callerId)
   {
   var make=callerId.split("_");
   $("#txt_"+make[1]+"_"+make[2]).focus();   
   }

function trim(str) {
    while (str.substring(0, 1) == ' ') {
        str = str.substring(1, str.length);
    }
    while (str.substring(str.length - 1, str.length) == ' ') {
        str = str.substring(0, str.length - 1);
    }
    return str;
}
function CampaignUploadUserAd()
{    
try{   
        $("#CampaignChannelPublisher").hide(showTime);
        $("#CampaignUpload").show(showTime);
        }catch(Error){}
}
/******************************************************/
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr,make){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		$("#"+make).html();
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		$("#"+make).html("The date format should be : mm/dd/yyyy.");
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		$("#"+make).html("Please enter a valid day");
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		$("#"+make).html("Please enter a valid 4 digit year between "+minYear+" and "+maxYear +".");
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		$("#"+make).html("Please enter a valid date");
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }

/***********************************************************/
function submitCampaignDetails(e)
{
     if(event.keyCode==13)clickCampaignDetail('a');
}
function clickCampaignDetail(a)
{          
    var b=false;   
    try{
    var campaignName=trim($("#txtCampaignName").val());
    var startDate=$("#startDate").val()
    var endDate=$("#endDate").val()
    var budget=$("#txtBudget").val();
    var todaysDate=new Date();
    if(Date.parse(startDate)<Date.parse(todaysDate))
    {
    $("#lblStartDate").html("Invalid date range!\nStart date cannot come before today's date\nToday is:"+todaysDate);
    return;
    }
        if(campaignName!="" && campaignName!="undefined" && startDate!="" && endDate!="")
        {
            if (Date.parse(startDate) <= Date.parse(endDate)) {
            b=isDate(startDate,"lblStartDate");
            if(b)b=isDate(endDate,"lblEndDate");
             //b=true;
            }else{
                  //alert("Invalid Date Range!\nStart Date cannot be after End Date!");
                   $("#lblStartDate").html('Invalid date range!\nStart date cannot be after end date');
                  }
                  if(b)
                  b=isValidURL($("#txtLandingPageURL").val());
                  var s = '';//$("#"+lblCamp).html();
                  s = document.getElementById('lblCamp').innerHTML;
                  if(b)
                  {
                   if(s!="Campaign name exists.")
                   {
                     b = true;
                   }
                   else
                   {
                    b = false;
                   }
                  }
                  else
                  {
                  b = false;
                  }
        }
        
        if(b)
        {
            var s=document.getElementById("rbCPM").checked;//s=document.getElementById("rbCPC").checked;//alert(s);
            var strImpressionMode="";
            if(s)strImpressionMode="CPM";else strImpressionMode="CPC";
            getChannelDisplay();
            getCampaignChannelPublisherDeatils(1,strImpressionMode,-200,0);
                
                // $("#ChannelPublisherContent").html(flashlogoImage);    
                $("#CampaignDetails").hide(showTime,function(){$("#CampaignChannelPublisher").show(showTime);}) ; 
                $("#dialogPopup").hide(showTime); 
                $("#CampaignDetails").hide(showTime) ;     
                $("#CampaignChannelPublisher").show(showTime);
        }
        else
        {
        if(campaignName==""){$("#lblCampaignName").html('Please enter valid Campaign name.');}
        if(startDate==""){$("#lblStartDate").html('Please enter valid Campaign start date.');}
        if(endDate==""){$("#lblEndDate").html('Please enter valid Campaign end date.');}
        if(!(isValidURL($("#txtLandingPageURL").val()))){$("#lblLandingPageURL").html('Invalid URL.');}
         
        }
        validateCampaignModification(strImpressionMode);
    
    }catch(Error){}
}
function validateCampaignModification(strImpressionMode)
{
        if(SelectedPublishers.length>0)
        {
            var s=SelectedPublishers[0];
            if(s!=""){
            var make={};make=s.split("_");
            var moder={};moder=make[6].split(" ");
                if(strImpressionMode==moder[1])
                {
                    validatePreviousSelectedPublisherDisplay(); 
                    $("#lblGTotal").html(gA);               
                }
                else
                {
                    NOSPublishers=0;
                    tmpImpressions=0;
                    SelectedPublishers=new Array();
                    shownPublisherPages=null;//new Array(parseInt($("#hiddenNoOfRecords").val()));
                    prevAmount=0;
                    modeGetter=true;
                    gA=0;
                    inputCheck=true;
                    iCalculater=0;
                    validImpressionSet=false;
                    $("#lblGTotal").html(gA);
                }
             }
        }
        else 
        {
            NOSPublishers=0;
            tmpImpressions=0;
            SelectedPublishers=new Array();
            shownPublisherPages=null;//new Array(parseInt($("#hiddenNoOfRecords").val()));
            prevAmount=0;
            modeGetter=true;
            gA=0;
            inputCheck=true;
            iCalculater=0;
            validImpressionSet=false;
            $("#lblGTotal").html(gA);
        }
}
function getCampaignChannelPublisherDetailsLinkClick(channel)
{
var s=document.getElementById("rbCPM").checked;//s=document.getElementById("rbCPC").checked;//alert(s);
            var strImpressionMode="";
            if(s)strImpressionMode="CPM";else strImpressionMode="CPC";
            getCampaignChannelPublisherDeatils(channel,strImpressionMode,-1,0);
            $("#ChannelPublisherContent").html(flashlogoImage).show(showTime);;
}

function callback()
{
}
function ClearError(Clearid)
{
    if(Clearid!=""||Clearid!=undefined)
    {
    //var i=document.getElementById(Clearid);
      $("#"+Clearid).html('');
    }
    else
    {
       // alert('clearing errors');
    }
}

function checkbudget()
{
    if (isNaN(document.getElementById("txtBudget").value))
    {
     document.getElementById("txtBudget").value="";
     alert("only digits");
    }
}
	
function getStartDate()
	 {
	   try{
	   //var n=$(document).ready(function(){$("#startDate").datepicker();});
	   $(document).ready(function(){	   
		        $("#startDate").datepicker({minDate: 1, maxDate: '+24M +10D',onSelect: function(dateText, inst)
		                                                                    {
		                                                                    try{	                                                             
                                                                             var d=new Date(dateText);
                                                                             $("#endDate").datepicker('option', 'minDate', new Date(dateText));		                                                             
                                                                             //document.getElementById("endDate").value="";
                                                                             $("#endDate").val('');
                                                                             $("#endDate").focus();
                                                                             }catch(Error){ ;}
		                                                                    }
		        });
		                                                             
		                            
        });
		}catch(Error){}
}
$(document).ready(function setStartDate(dateText, inst)
{
   
});
	
	function getEndDate() {
	try{
	        var s=document.getElementById("startDate").value;
	        //alert(s);
	        if(s=="")
	        {
	        $("#lblEndDate").html('Please enter Campaign start date first.');
	        //alert("Please select start date first");
	        $("#txtCampaignName").focus();
	        $("#startDate").focus();
	        //document.getElementById("txtCampaignName").focus();
	        }
	        else{
	        var d=new Date(s);
		        $("#endDate").datepicker({minDate: d, maxDate: '+24M +10D',onSelect: function(dateText, inst)
		                                                                    {
		                                                                    try{
                                                                             $("#txtLandingPageURL").focus();
                                                                             }catch(Error){ }
		                                                                    }
		        });
		        }
		}catch(Error){}
	}
	
	var secs
    var timerID = null
    var timerRunning = false
    var delay = 1000

    function InitializeTimer(divID,calculatedValue) {
        // Set the length of the timer, in seconds
        secs = 2
        StopTheClock()
       return StartTheTimer(divID,calculatedValue)
    }

    function StopTheClock() {
        if (timerRunning)
            clearTimeout(timerID)
        timerRunning = false
    }

    function StartTheTimer(divID,calculatedValue) {
        if (secs == 0) {
            StopTheClock()
            // Here's where you put something useful that's
            // supposed to happen after the allotted time.
            // For example, you could display a message:
            //alert("You have just wasted 10 seconds of your life.")
            $("#"+divID).html(calculatedValue).show();
            return true;
        }
        else {
            self.status = secs
            secs = secs - 1
            timerRunning = true
            var callBackFun="StartTheTimer("+divID+","+calculatedValue+")";
            timerID = self.setTimeout(callBackFun, delay);
            //timerID = self.setTimeout("StartTheTimer()", delay);
        }
    }
    
    function publisherCheckedOld(p,t)
{
    var s=p.id;
    var make={};make=s.split("_");
    var impressions=0;
    impressions=$("#lbl_"+make[1]+"_"+make[2]+"_"+make[3]+"_"+make[4]).html();
    if(p.checked)
    {
        if(impressions=="Out of inventory")
        {
            openDialog("Cant select this publisher as requested impressions are out of inventory");	                
            p.checked=false;return;
        }
        else if(impressions=="Invalid Amount")
        {
           openDialog("Cant select this publisher as requested amount is invalid");	
           p.checked=false;return;
        } 
        else if(impressions=="" || impressions=="Impressions")
        {
            openDialog("Cant select this publisher as no budget mentioned");
            p.checked=false;return;	
        }
        else
        {            
            var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
            if(parseInt(availableImpressions)-parseInt(impressions)<0||parseInt(availableImpressions)<=0)
            {
             openDialog("Cant select this publisher as insufficient impressions");
             p.checked=false;return;	
            }
            else
            {
                var remainingImpressions=parseInt(availableImpressions)-parseInt(impressions);
             //$("#lbl_ImpCap_"+make[2]).html(remainingImpressions).show();
             NOSPublishers++;
            }
         }
    }
    else
    {
    var availableImpressions=0;
            availableImpressions=$("#lbl_ImpCap_"+make[2]).html();
            if(parseInt(impressions)>0)
            {
               availableImpressions =parseInt(availableImpressions)+parseInt(impressions);
              // $("#lbl_ImpCap_"+make[2]).html(availableImpressions).show();              
             }
              if(NOSPublishers>0)NOSPublishers--;
    }
    
}

function isAjax()
{
var xmlHttp;
try
  {
  // Internet Explorer
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  return xmlHttp;
  }
catch (e)
  {
  // Firefox, Opera 8.0+, Safari
  try
    {
    xmlHttp=new XMLHttpRequest();
    return xmlHttp;
    }
  catch (ex)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      return xmlHttp;
      }
    catch (exx)
      {
      alert("ajax not supported");
         return null;
      }
    }
  }
}

function isMozilla()
{
  var xmlHttp;
  try
   {
    // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        //var array=navigator.userAgent.split

        if(navigator.userAgent.indexOf("Firefox")!=-1)
        {
            var versionindex=navigator.userAgent.indexOf("Firefox")+8
            if (parseInt(navigator.userAgent.charAt(versionindex))>=1)
            {
               //alert("You are using Firefox 1.x or above");
               return true;
            }
        }
        return false;
   }
   catch (e)
   {
   }
}