﻿
var newUrl = "";

var layoutHeight = 0;
var layoutWidth = 0;

//this var is to account for the startup script that gets registered on existingorders
//if someone clicks "back" the script is maintained and it executes, but we only want it to 
//fire if someone has clicked the "advertise here" button
var clickedBuy = false;

$(document).ready(function()
{ 
    var url = window.location.toString();
    newUrl = url.replace("/profile/","/home/");
//    pubId = url.substring(url.indexOf("a=") + 2);
//    
//    //get rid of any additonal query string on end
//    if (pubId.indexOf("&") != -1){
//        pubId = pubId.substring(0,pubId.indexOf("&"));
//    }
    
    buildCal();
   
    
    $("div[id*=buyHereLink]").click(function(){
       
       clickedBuy = true;
       
       if (accountId != pubAccountId){
          
           if (contactId == ""){
                //grab the scope from the url
                var url = window.location.toString();
                var f = url.indexOf("/profile/")
                if (f == -1) { f = url.length; }
                url = url.substring(0, f);
                var g = url.lastIndexOf("/");
                var scope = url.substring(g + 1, f);
        
                window.location = "/login/login.aspx?p=" + pubId + "&s=" + scope;            
                
           }
           else{
               if (hasDates){
                   from = this;
                   checkForExistingDeals();
               }
               else{
                    showOverlay();
                    $("#noDatesMessage").fadeIn("slow");
               }
           }
            
          
       }
       else{
           alert("Sorry, you cannot buy an ad from yourself.");
       }
       
     
    });
    
    $("#viewPrices").click(function(){
//       $("#viewLayout").css("backgroundColor","#000");
//       $("#viewPrices").animate( { backgroundColor:"#2f7ba5" },500);
//      
//       $("#priceArrow").fadeIn("slow");
//       
//       $("#layoutArrow").hide();
//       $("#layout").hide();
//       $("#priceArea").fadeIn("slow");
       
    });
    
    $("#viewLayout").click(function(){
      
        $("#window").css("top","120px");
        var winHeight = parseInt(layoutHeight) + 85;
        var winWidth = parseInt(layoutWidth) + 85;
        var marginLeft = winWidth / 2;
        $("#window").css("margin-left","-" + marginLeft + "px");
        $("#window").css("left","50%");
        $("#window").css("height",winHeight+"px"); //0
        $("#window").css("width",winWidth +"px");
        $("#windowBottom").css("height",(winHeight -50)+"px");//-50
        $("#windowBottomContent").css("height",(winHeight -50)+"px");//-50
        $("#windowContent").css("height",(winHeight -45)+"px");//-45
        $("#windowContent").css("width",(winWidth-27)+"px"); //-27
        $("#windowTopContent").html("Layout");
      
        $("#vistaIFrame")[0].src = "/apps/profile/layoutView.aspx?p=" + pubId;
       
        if($('#window').css('display') == 'none') {
//            $(this).TransferTo(
//                {
//                    to:'window',
//                    className:'transferer2', 
//                    duration: 500,
//                    complete: function()
//                    {
//                        $('#window').show();
//                    }
//                }
//            );
              $('#window').show('slow');
        }
        showOverlay();
        this.blur();
        return false;
      
    
    });
    
    $("a[id*=heading]").click(function(){
        var rateCard = this.id.toString().substring(7);
        $("a[id*=heading]").css("font-weight","normal");
        $(this).css("font-weight","bold");
        $("div[id*=group]").hide();
        $("#" + rateCard + "group").fadeIn("slow");
        
    
    });
    $("#policyLink").click(function(){
        $("#policyPopup").fadeIn("slow");
    });
    
    $("#closePolicyPopup").click(function(){
        $("#policyPopup").fadeOut("slow");
    
    });
    $("#sendMessageButton").click(function(){
        $("#noDatesMessage").fadeOut("slow");
        $("#window").css("margin-left","-200px");
        $("#window").css("left","50%");
        $("#window").css("top","220px");
        $("#window").css("height","270px");
        $("#window").css("width","400px");
        $("#windowBottom").css("height","220px");
        $("#windowBottomContent").css("height","220px");
        $("#windowContent").css("height","215px");
        $("#windowContent").css("width","373px");

        //id of the view detail link is the transid

        $("#windowTopContent").html("Send Message");
        $("#vistaIFrame")[0].src = '/apps/ordercenter/NewMessage.aspx?p=' + pubId;

        if($('#window').css('display') == 'none') {
//            $(this).TransferTo(
//                {
//                    to:'window',
//                    className:'transferer2', 
//                    duration: 500,
//                    complete: function()
//                    {
//                        $('#window').show();
//                    }
//                }
//            );
              $('#window').show('slow');
        }
        //showOverlay();
        this.blur();
        return false;

    });
    
    $("#closeNoDatesPrompt").click(function(){
        hideOverlay();
        $("#noDatesMessage").fadeOut("slow");
    });
  
    getLayoutDimensions();

});

function executeRedirect(){
    
    if (clickedBuy){
        parent.redirectToBuyProcess(); 
    }
}

function checkForExistingDeals(){

    //GetDeals(int buyer, int seller) {
 
    var theData = "{\"buyer\":" + contactId + ",\"seller\":" + pubId + "}";
    sendObject(theData,'DealController','GetDeals',continueOrStartNew,'{}');
    
}

function getLayoutDimensions(){

    var theData = "{\"pubId\":" + pubId + "}";
    sendObject(theData,'MyInkoController','GetLayoutDimensions',saveDimensions,'{}');
}

function saveDimensions(msg){
    var dim = eval(msg.d);
    layoutWidth = dim[0].width;
    layoutHeight = dim[0].height;
    
    if (layoutWidth != "0" || layoutHeight != "0"){
            $("#layoutButton").show();
    }
   
}

function continueOrStartNew(msg){
    //alert(msg.d);
     if (msg.d != '[]'){
        //dealList = eval(msg.d);
        showExistingDealWindow();
    }
    else{
    
       var theData = "{\"buyerContactId\":" + contactId + ",\"sellerContactId\":null,\"buyerAccountId\":null,\"sellerAccountId\":" + pubAccountId + "\,\"dealName\":\"\"}";
       sendObject(theData,'OrdersController','CreateDeal',setSession,'{}');
    }

}

function setSession(msg){
  
    var url = window.location.toString();
    newUrl = url.replace("/profile/","/home/");
    //get rid of existing query string
    if (newUrl.indexOf("?") != -1){
        newUrl = newUrl.substring(0,newUrl.indexOf("?"));
    }
    newUrl += "?d=" + msg.d;
    window.location.href = newUrl;

}

function showExistingDealWindow(){
    $("#window").css("margin-left","-235px");
    $("#window").css("left","50%");
    $("#window").css("top","150px");
    $("#window").css("height","425px");
    $("#window").css("width","470px");
    $("#windowBottom").css("height","375px");
    $("#windowBottomContent").css("height","375px");
    $("#windowContent").css("height","370px");
    $("#windowContent").css("width","443px");

    //id of the view detail link is the transid

    $("#windowTopContent").html("Outstanding Orders");
    $("#vistaIFrame")[0].src = '/apps/home/ExistingOrders.aspx?p=' + pubId;

    if($('#window').css('display') == 'none') {
//        $(from).TransferTo(
//            {
//                to:'window',
//                className:'transferer2', 
//                duration: 500,
//                complete: function()
//                {
//                    $('#window').show();
//                }
//            }
//        );
          $('#window').show('slow');
    }
    showOverlay();
    from.blur();
    return false;
    
    

}

function buildCal(){

   
    
    var currDate = new Date();
    var startMonth = currDate.getMonth();
    var startYear = currDate.getFullYear();
    $('#month1')[0].innerHTML  = buildCalendar(startMonth,startYear);   
    if (startMonth == 11) { startYear++; startMonth = 0;} else startMonth++;
    $('#month2')[0].innerHTML  = buildCalendar(startMonth,startYear);   
    if (startMonth == 11) { startYear++; startMonth = 0;} else startMonth++;
    $('#month3')[0].innerHTML  = buildCalendar(startMonth,startYear); 
    if (startMonth == 11) { startYear++; startMonth = 0;} else startMonth++;
    $('#month4')[0].innerHTML  = buildCalendar(startMonth,startYear); 
    
   
    getPublicationDates();
}
function buildCalendar(monthNumber, yearNumber, namingContainer, addClickHandler)
{   
//alert("month"+monthNumber+"year"+yearNumber);
    if (buildCalendar.arguments.length == 2)
        namingContainer = ""; 

    if (buildCalendar.arguments.length == 3)
        addClickHandler = false;
    
    // start on the first day of the month.
    var m_names = new Array("January", "February", "March", 
        "April", "May", "June", "July", "August", "September", 
        "October", "November", "December");

    var startDate = new Date((monthNumber+1) + "/01/" +  yearNumber);
    var StartDOW = startDate.getDay();
    var html = new String("");
    var dayCounter = new Number(0);
    var totalDays = new Number(0);
    totalDays = (32 - new Date(yearNumber, monthNumber, 32).getDate());
    html += "<div class='monthContainerSmall' style=''>";
    
    html += "<div class='monthLabel'><table><tr><td width='120px' align='center'>" + m_names[monthNumber] + "</td></tr></table></div>";
    for (var weeks = 0; weeks <6; weeks++)
    {
        html += "<div class='weekrowDateSmall'>"
        for (var days = 0; days <7; days++)
        {
            dayCounter++ ;
            var offSet = dayCounter - StartDOW;
            var dayString = (offSet <= 0 || offSet > totalDays ? "&nbsp;" : offSet.toString());
            html += "<div class='normalDateSmall' " + 
                " " +
                " id='" + namingContainer + 
                (dayString == "&nbsp;" ? "empty_" + dayCounter.toString() : padIt((monthNumber+1).toString()) + "-" + padIt(dayString) + "-" + yearNumber) 
                + "'  >" + dayString + "</div>";
               
        }
        html += "<div style='clear:both; height:1px;'></div>";
        html += "</div>";
    }
    html += "</div>";

    return html;
    
}
function padIt(unit){
    if (unit.length == 1){
        unit = "0" + unit;
        
    }
    
    return unit;

}
function bindCalendar(PubDates, namingContainer, bindOptions)
{   
    
    
   // alert(PubDates.Dates[0]["pubdate"]);
    // bindoptions 1- publication dates only, 2 - submission and publication dates
    if (bindCalendar.arguments.length == 1)
        namingContainer = "";
        
    if (bindCalendar.arguments.length == 2)
        bindOptions = 2
    
    var element;
    var dateToCheck;
    var todaysDate = new Date();
    for (var i = 0; i < PubDates[0].Dates.length; i++)
    {
       // publication date
       element  = $('#' + namingContainer + PubDates[0].Dates[i]["pubdate"])[0]

       if (element)
       {    
            //see if date earlier than today's date, if so, not available
            dateToCheck = new Date(PubDates[0].Dates[i]["pubdate"].replace(/-/g,'/'));
            if (dateToCheck > todaysDate){
                element.style.background = "url(/images/caldaywhiteSmall.png)";
            }
       }
    }
    for (var i = 0; i < PubDates[1].SpecialEdDates.length; i++)
    {
       // publication date
       element  = $('#' + namingContainer + PubDates[1].SpecialEdDates[i]["pubdate"])[0]
       if (element)
       { 
            element.style.background = "url(/images/caldayspecialSmall.png)";
       }
       
      
    }
}
function dayselectHandler(domElement)
{

  if (domElement.style.background == "") 
  {
    alert("Please select a valid publication date");
    return;
  }
  
  if (domElement.style.background.indexOf("caldaywhiteSmall.png") > -1 )
  {
    var dateSelected = domElement.id.toString();
    var exists = selectedDaysArray.indexOf(dateSelected);
    if (exists == -1){
        //alert(dateSelected);
        selectedDaysArray.push(dateSelected);
       
    }
    domElement.style.background = "url(/images/calselredSmall.png)";
    return;
  }
  
  
  if (domElement.style.background.indexOf("calselredSmall.png") > -1) 
  {
  
    var dateSelected = domElement.id.toString();
    
    var toRemove = getIndexToRemove(selectedDaysArray,dateSelected);
    selectedDaysArray.splice(toRemove,1);
    
   
    domElement.style.background = "url(/images/caldaywhiteSmall.png)";
    return;
  }
}

function getPublicationDates(){
   
     $.ajax({
        type: "POST",
        url: "/bll/CalendarController.aspx/GetEternalCalendar",
        data: "{\"accountId\":\"" + pubAccountId + "\",\"days\":125}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) 
        {
            eval(msg.d);
            bindCalendar(PubDates);
            //get already selected dates
           // getExistingDates();
            
           
        },
        error: function(xhr,msg,e)
        {  
            //alert("Sorry!  An error occured.  Please contact us at support@tapinko.com"); //alert(xhr.responseText);          
        }
    });


}


function sendObject(arg, toController, method, successCallback, failureCallback) {
  
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/bll/" + toController + ".aspx/" + method,
        data: arg,
        dataType: "json",
        success: successCallback,
        error: function(a, b, c) { }//alert("Sorry!  An error occured.  Please contact us at support@tapinko.com"); }//alert(a.responseText);  }

    });

}


