﻿//this is the default page that ajax requests will be sent to
//this url will change depending if the UserID field is set
//by asp.net or not
var protocol = window.location.protocol;
var host = window.location.host;
var path = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/"));
var url = protocol+"//"+host+path+"/";
var DOWNLOAD_URL = url+"snapDownload/";
var POST_URL = url+"app/public/service.ashx";

var SnapSite = url;


if (UserID != "0")
{
    POST_URL = url+"app/public/app_service.ashx";
    
    if (protocol == "https:")
    {
        
        POST_URL = url+"app/public/secure_service.ashx";

    }
    
}


function isIE()
{
    
    return (navigator.appName.indexOf("Microsoft") > -1);

}

function bVersion()
{
	return navigator.appVersion;
}	


var changed = false;

var callbacks = new Array();

var callID = 0;

function CallItem()
{
    this.Callback = null;
    this.CallID = 0;
}

function start()
{
  
    begin();
    initMenu();

}

function initMenu()
{

}


$(document).ready(start);


function onFormSubmit()
{


}


function showFAQ()
{
	
	var settings = getDetailsSettings();
	settings.contentOffset = 20;
	settings.bottomPadding = 40;
	settings.titleImage = "common/images/faq.png";
	
	//create an iframe
	var frame = create("IFrame");
	frame.width = 450;
	frame.height = 600;
	frame.marginWidth = 0;
	frame.marginHeight = 0;
	frame.scrolling = "yes";
	frame.frameBorder = 0;
	
	frame.src = "common/faq/index.html";
	
	var holder = create("div");
	holder.appendChild(frame);
	
	
    popupContent(holder, "FAQ", -50, settings);


}


var savedPage = "";
function saveBeforeNav(page)
{
    if (changed)
    {
        savedPage = page;
        var wconfirm = window.confirm("Would you like to save your changes before continuing?");
        if (wconfirm)
        {
            changed = false;
            save(onSavedBeforeNav);
        }
        else
        {
			window.location = page;
        }
   
   }
   else
   {
        window.location = page;
   }
}

function onSavedBeforeNav(data)
{

    window.location = savedPage;
}

function begin()
{
    //override this function in the control's javascript page


}

function save(callback)
{
    
    //each control has a save function
    //if you pass a callback to it, the save
    //will pass it to the com(packet, callback)
    //function

}

function logout()
{
    var packet = new Object();
    packet.UserID = UserID;
    packet.ClassName = "App";
    packet.MethodName = "Logout";

    
    com(packet, onLogout);
    

}

function onLogout(data)
{

    if (data != "")
    {
		window.location = data;
	}
	else 
	{
		window.location = "Default.aspx";
	}

}



function checkout()
{
    //to checkout, the production must have the following:
    //at least one message
    //a voice talent selection
    //a number of words greater than 0
    //if any of the messages have music
    //  there must be a MusicTrack for the production

    //first check messages
    if (production.GetMessageCount() <= 0)
    {
        alert("Your order does not contain any messages. Please add messages to your order before checking out.");
    }
    else if (production.WordCount <= 0)
    {
        alert("Your order does not contain any words. Please write something before checking out.");
    }
    else if (production.Voice == null)
    {
        alertVoice();
       
    }
    else if (production.Voice.VoiceTalentID == 0)
    {
        alertVoice();
    }
    else 
    {
        //now check music
        var hasMusic = !(production.MusicTrack == null);
        
        //check the messages to see if they selected to play music
        if (!hasMusic)
        {
			//do any of there messages have music selected?
			hasMusic = ((production.GeneralMusic + production.OnholdMusic) > 0);
           
            if (hasMusic)
            {
                //wconfirm = window.confirm("You chose to have music play on the following messages: "+musicMessage+"\nWould you like to choose a music track for these messages now?");
                wconfirm = window.confirm("You have chosen to play music in your production, but you haven't selected a music track. Would you like to select one now?");
                if (wconfirm)
                {
                    openMusic();
                }
            }   
            else
            {
                continueCheckout();            
            }
            
        }
        else
        {
            continueCheckout();      
        }
        
    }
    
}

function alertVoice()
{
    var wconfirm = window.confirm("You must select a voice talent for this order. Would you like to select one now?");
    if (wconfirm)
    {
        selectVoice();
    }
}

function continueCheckout()
{
    if (changed)
    {

        saveBeforeContinue(toCheckout);
    }
    else
    {
        toCheckout();
    }  
}

function toCheckout(data)
{
    //this production is ready to checkout
    var packet = getPacket("App", "CheckoutReady");
    
    var param = new Object();
    param.ProductionID = production.ProductionID;
    
    packet.Param = param;
    
    com(packet, onCheckoutReady);
    
}

function onCheckoutReady(data)
{
    
    window.location = "Checkout.aspx";

}

function getPacket(className, methodName)
{
    var packet = new Object();
    packet.UserID = UserID;
    packet.ClassName = className;
    packet.MethodName = methodName;
    
    return packet;

}

//sends the JSONPacket object to asp.net
//pass the resultFunction to receive the data 
//from the callback
function com(packet, resultFunction)
{
    callID++;
    var citem = new CallItem();
    citem.CallID = callID;
    citem.Callback = resultFunction;
    callbacks.push(citem);
    
    packet.CallID = callID;
    
    //callbacks.push(resultFunction);//add the callback function to the list
    $.post(POST_URL, { jsonData: JSON.stringify(packet) }, onCallback);
    

}

//data will be of type JSONResult
//check the result for errors, if it's
//good pass the data to the callback function
function onCallback(data)
{
     var jresult = JSON.parse(data);
    
    if (jresult.IsSuccess)
    {
        //find the correct callback with the callID

        var item = getCallback(Number(jresult.CallID));
        
        if (item != null)
        {
            item.Callback(jresult.Data);
        }
    
      
   }
   else
   {
        if (jresult.Message == "Your session has expired.")
        {
            window.location = "Default.aspx";
        }
        else
        {
            alert("Error: "+jresult.Message);
        }
        
        onServerError();
        
   }
   

}

function onServerError()
{

}


function getCallback(id)
{

    var index = -1;
    for(var i=0; i < callbacks.length; i++)
    {
        if (Number(callbacks[i].CallID) == id)
        {
            index = i;
        }
    }

    if (index > -1)
    {
        var item = callbacks[index];
        callbacks.splice(index, 1);
        return item;
    }
    
    return null;

}

/* PRODUCTION DETAILS */

function viewDetails(prod, top)
{
    
   
    var holder = create("div");
    
    holder.appendChild(createRow("Order Name: ", prod.Title, "n/a"));
    
    var packname = prod.PackageName;
    if (prod.PackageType == "package")
    {
		packname = prod.SnapPackage.Name;
	}
    holder.appendChild(createRow("Package: ", packname, "$"+prod.GetBasicPrice().toFixed(2)));
    
    holder.appendChild(createRow("Included Words: ", prod.GetStandardWords(), "n/a"));
    
    var addWords = prod.GetWordPrice()-prod.GetBasicPrice();
	
	if ((prod.SnapPackage != null) && (prod.SnapPackage.OnholdMessages == 1 && prod.SnapPackage.GeneralMessages == 0))
	{
		var onholdPrice = prod.GetOnholdPriceDescription();
		if (onholdPrice != "")
		{
			holder.appendChild(createRow("Package Upgrade: ", onholdPrice, "$"+(prod.GetMinutePrice()-prod.GetBasicPrice()).toFixed(2)));
			
		}
		
		var addMinutes = prod.GetPackageAdditionalMinutes();
		if (addMinutes > 0)
		{
			holder.appendChild(createRow("Additional Minutes: ", addMinutes, "$"+(addMinutes*25).toFixed(2)));
			
		}
	}
	else 
	{
		var addWordsTxt = "n/a";
		if (addWords > 0)
		{
			addWordsTxt = "$"+addWords.toFixed(2);
		}
	    
		holder.appendChild(createRow("Additional Words: ", prod.GetAdditionalWords(), addWordsTxt));
	    
	}
	
    holder.appendChild(createRow("Total Words: ", prod.WordCount, "n/a"));
    
    var voice = "None Selected";
    if (prod.Voice != null)
    {
        if (prod.Voice.VoiceName != "")
        {
            voice = prod.Voice.VoiceName;
        }
    }
    
    holder.appendChild(createRow("Voice Talent: ", voice, "n/a"));
    
    var music = "None Selected";
    var musicPrice = "n/a";
    if (prod.MusicTrack != null)
    {
        if (prod.MusicTrack.MusicName != "")
        {
            music = prod.MusicTrack.GetName();
            musicPrice = "$"+prod.GetMusicPrice().toFixed(2);
            if (prod.PackageType == "package")
            {
				if (prod.SnapPackage.Music > 0)
				{
					musicPrice = "n/a";
				}
            }
        }
    }
    
    holder.appendChild(createRow("Music Track: ", music, musicPrice));
    
    holder.appendChild(createRow("Music General: ", prod.GeneralMusic, "n/a"));

    holder.appendChild(createRow("Music Onhold: ", prod.OnholdMusic, "n/a"));
    
    var includeProof = prod.Proofreading;

    
    if (prod.PackageType == "proof")
    {
		includeProof = false;
	}
	
	if (prod.PackageType == "package")
	{
		if (prod.Proofreading)
		{
			includeProof = (!prod.SnapPackage.Proofreading);
		}
	}
    
    if (includeProof)
    {
		holder.appendChild(createRow("Proofreading: ", "Yes", "$"+prod.GetProofPrice().toFixed(2)));
    }

    
    if (prod.GetLocationsDisplay() > 1)
    {
        holder.appendChild(createRow("Locations: ", prod.GetLocationsDisplay(), "$"+prod.GetLocationsPrice().toFixed(2)));
    }
    
    var delTxt = "n/a";
    var delType = "Standard";
    if (prod.Delivery == "expedited")
    {
		delTxt = "$"+prod.GetDeliveryPrice().toFixed(2)+"**";
		delType = "RUSH";
	}
	
	holder.appendChild(createRow("Delivery: ", delType, delTxt));
    
    if (prod.InsertMessages)
    {
        holder.appendChild(createRow("Message Insertion: ", "Yes", "$"+prod.GetInsertionPrice().toFixed(2)));
    }
    
    var tPrice = prod.GetTotalPrice();
    var displayTotal = tPrice.toFixed(2);
    if ((prod.TotalPaid > 0) && (prod.TotalPaid < tPrice))
    {
		holder.appendChild(createRow("Discount: ", (((tPrice-prod.TotalPaid)/tPrice)*100).toFixed(0)+"%", "$"+(tPrice-prod.TotalPaid).toFixed(2)));
		displayTotal = prod.TotalPaid.toFixed(2);
    }
    
    
    var totalRow = create("div", "totalRow");
        var totalTitle = create("div", "colTotalTitle");
            var totalTitleSpan = create("span");
            totalTitleSpan.innerHTML = "Total: ";
        totalTitle.appendChild(totalTitleSpan);
    totalRow.appendChild(totalTitle);
        var totalPrice = create("div", "colTotal");
            var totalPriceSpan = create("span");
            totalPriceSpan.innerHTML = "$"+displayTotal;
        totalPrice.appendChild(totalPriceSpan);
    totalRow.appendChild(totalPrice);
    
    holder.appendChild(totalRow);
    
    
    
    var noteRow = create("div", "noteRow");
        var colNote = create("div", "colNote");
        if (prod.Delivery == "expedited")
        {
			colNote.innerHTML = "**$25.00 for first 75 words, $10 per 75 words therafter.";
		}
		else 
		{
			colNote.innerHTML = "&nbsp;";
		}
    noteRow.appendChild(colNote);
    
    holder.appendChild(noteRow);
    
	var settings = getDetailsSettings();
	settings.titleImage = "app/content/images/orders/order_details.png";
    popupContent(holder, "Order Details", top, settings);

}

function createRow(title, info, price)
{

    var row = create("div", "row");
        var colTitle = create("div", "colTitle");
            var titleSpan = create("span");
            titleSpan.innerHTML = title;
        colTitle.appendChild(titleSpan);
    row.appendChild(colTitle);
        var colInfo = create("div", "colInfo");
            var infoSpan = create("span");
            infoSpan.innerHTML = info;
        colInfo.appendChild(infoSpan);
    row.appendChild(colInfo);
        var colPrice = create("div", "colPrice");
            var priceSpan = create("span");
            priceSpan.innerHTML = price;
        colPrice.appendChild(priceSpan);
    row.appendChild(colPrice);
    
    return row;

}



