﻿//////////////////////////// ClientState Object /////////////////////////////////////////////////

var ClientState = {  data : {

            Command : null,
            Args : []
        },
        
        callbackpage : null,
        bundle : null,
        offers : null,
        browser : null,
        
        initialize : function(callback)
        {
            this.data.Command = '';
            this.data.Args = new Array();
            this.callbackpage = callback;
            this.offers = new Hash();
            this.browser = navigator.appName;
        },
        
        clearArgs : function()
        {
            this.data.Args = new Array();
        },
                
        notifyCommand : function( callback )
        {
              var xmlHttpRequest = this.getTransport();
              if( xmlHttpRequest != null )
              {
                  xmlHttpRequest.onreadystatechange = function()
                  {
                      if(( xmlHttpRequest.readyState == 4 ) && ( xmlHttpRequest.status == 200 ) )
                      {
						  if( xmlHttpRequest.responseText != "ERROR!")
								callback( xmlHttpRequest );
						  else
								location.href = "/Verification.aspx";
                      }
                      else if(( xmlHttpRequest.readyState == 4 ) && ( xmlHttpRequest.status == 500 ) )
                      {
                          //alert( 'Error: ' + xmlHttpRequest.statusText + '. Unable to complete request at this time. ');
                          location.href = "/Verification.aspx";
                      }
                      else if(( xmlHttpRequest.readyState == 4 ) && ( xmlHttpRequest.status == 408 ) )
                      {
                          alert("Your session has expired. Press ok to reload your information.");
                          location.href = "Dispatch.aspx?action=500";
                      }
                      else if(( xmlHttpRequest.readyState == 4 ) && ( xmlHttpRequest.status != 200 ) )
                      {
                          //alert( 'Error ' + xmlHttpRequest.status + ' : ' + xmlHttpRequest.statusText);
                          location.href = "/Verification.aspx";
                      }
                  }
                  
                  xmlHttpRequest.open( 'post', this.callbackpage, true );
                  xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                  xmlHttpRequest.send("AJAX=true&AjaxEventArgs=" + ClientState.data.toJSON() );
              }
              else
              {
                  alert( "Your browser doesn't support Ajax." ); 
              }
        },
        
        getTransport : function()
        {
            return Try.these(
                function() { return new XMLHttpRequest(); },
                function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
                function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
                function() { return null; }
            )
        }
};
     
//////////////////////////// Lightbox Object /////////////////////////////////////////////////

    function Lightbox(id)
    {
        this.id = id;
        
        this.Top = 40;
        this.Left = 40;
        this.Width = 400;
        this.Height = 225;
        this.Shadow = true;
        this.Modal = true;
        this.Draggable = false;
        this.DragGrip = "";
        this.InnerHTML = "";
        this.Overflow = "auto";
        this.Background = "#FFFFFF";
        this.Content = "Details";
        this.offsetX = 0;
        this.offsetY = 0;
        this.browser = null
        
        this.messageBox = null;
        this.shadowBox = null;
        this.mask = null;
        
        this.initialize = function()
        {
               this.InnerHTML = '<center><img src="App_Themes/DigitalLanding/images/ajax-loader.gif" /><br />Loading...</center>';
               this.offsetX = (document.documentElement.scrollLeft/screen.width) + this.Left;
               this.offsetY = document.documentElement.scrollTop + this.Top;

        }
        this.createOverlay = function()
        {
            var lightbox = document.createElement('div');
            lightbox.id = 'light' + this.id;
            lightbox.style.position = 'absolute';
            lightbox.style.width = '100%';
            lightbox.style.height = '100%';
            lightbox.style.top = 0;
            lightbox.style.left = 0;
            lightbox.style.backgroundColor = "#AAAAAA";
            lightbox.style.visibility = "visible";
            lightbox.style.filter = "alpha(opacity=0);";
            lightbox.style.opacity = "0.0";
            lightbox.style.display = "none";
            lightbox.style.zIndex = 100;
            
            return lightbox;
        }
        this.createShadow = function()
        {            
            var dropshadow = document.createElement('div');
            dropshadow.id = "shadow" + this.id;
            dropshadow.style.position = 'absolute';
            dropshadow.style.width = this.Width;
            dropshadow.style.height = this.Height;
            dropshadow.style.top = (this.offsetY + 1) + "px";
            dropshadow.style.left = (this.offsetX + 1) + "%";
            dropshadow.style.backgroundColor = "#000000";
            dropshadow.style.visibility = "visible";
            dropshadow.style.filter = "alpha(opacity=75);";
            dropshadow.style.zIndex = 101;
            dropshadow.style.display = "none";

            return dropshadow;
        }
        this.createMessageBox = function()
        {
            var messageBox = document.createElement('div');
            messageBox.id = "messageBox" + this.id;
            messageBox.style.position = 'absolute';
            messageBox.style.width = this.Width;
            messageBox.style.height = this.Height;
            messageBox.style.top =  this.offsetY + "px";
            messageBox.style.left = this.offsetX + "%";
            messageBox.style.backgroundColor = this.Background;
            messageBox.style.visibility = "visible";
            messageBox.style.borderWidth = "1px";
            messageBox.style.borderColor = "#000000";
            messageBox.style.borderStyle = "solid";
            messageBox.style.overflow = this.Overflow;
            messageBox.style.zIndex = 102;
            messageBox.style.display = "none";
            
            if(( this.Content == "Details" ) || (this.Content == "Article" ) )
            {
                    messageBox.innerHTML = '<div id="pop-nav" class="cf" style="position:relative;width:688px;">' +
	                                       '<div id="print"><a id="print_link" href="javascript:void(0);"><img src="App_Themes/DigitalLanding/images/icon-print.gif" border="0" align="absmiddle" /> Print Page</a></div>' +
	                                       '<div id="close"><a id="close_link" href="javascript:void(0);"><img src="App_Themes/DigitalLanding/images/icon-close.gif" width="14" align="absmiddle" height="13" border="0" />Close Window</a></div>' +
	                                       '<div id="grip" style="height:10px;cursor:move;"></div>' +
                                           '</div>' +
                                           '<div id="pop-wrapper" class="cf" style="position:relative;width:700px;height:550px;overflow:auto;">' +
	                                       '<div id="details-wrapper" style="position:relative;"></div></div>';
	               this.DragGrip = "grip";
	        }
	        else
	        {
                    messageBox.innerHTML = '<div id="pop-nav" class="cf" style="position:relative;cursor:move;width:' + (this.Width - 12) + 'px;overflow:hidden;">' +
	                                       '<div id="close"><a id="close_link" href="javascript:void(0);"><img src="App_Themes/DigitalLanding/images/icon-close.gif" width="14" align="absmiddle" height="13" border="0" />Close Window</a></div>' +
                                           '</div>' +
                                           '<div class="cf" style="width:' + this.Width + 'px;height:' + this.Height + 'px;">' +
	                                       '<div id="details-change"></div></div>';
	               this.DragGrip = "pop_nav";
	        }
            
                        
            return messageBox;
        }
        this.ShowMask = function()
        {
            var FFOpacity = "0.5";
            var IEOpacity = "alpha(opacity=50);";
            this.mask = this.createOverlay();
            if( this.Modal )
            {
                this.mask.filter = IEOpacity;
                this.mask.opacity = FFOpacity;
            }
            document.body.appendChild( this.mask );
            Effect.BlindDown( this.mask.id, {scaleFrom:0,scaleTo:100,duration:0.5,queue:{position:'end',scope:'first'}});
            Event.observe( this.mask, "click", this._hide );
        }
        this.ShowMessageBox = function()
        {
            this.messageBox = this.createMessageBox();
            var h = this.Height;
            var w = this.Width;
            document.body.appendChild( this.messageBox );
            Effect.BlindDown( this.messageBox, {scaleFrom:0,scaleTo:100,duration:0.5,queue:{position:'end',scope:'second'}});
            if( this.Shadow )
            {
                this.shadowBox = this.createShadow();
                document.body.appendChild( this.shadowBox );
                Effect.BlindDown( this.shadowBox, {scaleFrom:0,scaleTo:100,duration:0.5,queue:{position:'end',scope:'third'}});
            }
            
            if( this.Draggable )
            {
                new Draggable( this.messageBox.id, {revert:false,handle:this.DragGrip,zindex:102});
                if( this.Shadow ) new Draggable( this.shadowBox.id, {revert:false,handle:this.DragGrip,zindex:101});
            }
            this.Update();
            
        }
        this.Show = function()
        {
            this.initialize();
            this.ShowMask();
            this.ShowMessageBox();
        }
        this.Close = function()
        {
			try
			{
				if( this.messageBox != null ) document.body.removeChild( this.messageBox );
				if( this.shadowBox != null ) document.body.removeChild( this.shadowBox );
				if( this.mask != null ) document.body.removeChild( this.mask );
            }
            catch(ex){}
        }
        this._hide = function(event)
        {
            if(event) Event.stop(event);
            this.CloseDetail(event);
        }
        this.Update = function()
        {
			if((this.Content == "Article" ) || (this.Content == "Details" ))
				$('details-wrapper').innerHTML = this.InnerHTML;
			else
				$('details-change').innerHTML = this.InnerHTML;
        }
        this.CloseRef = function()
        {
            return 'close_link';
        }
    }


//////////////////////////// Global Variables //////////////////////////////////////////////////////

var box;
var box2;
var topCategory = null;
var focused;
var article;
var htmlPage;
var offer = new Object();

/////////////////////////// Javascript Methods ////////////////////////////////////////////////////


///////////Basic UI Effects///////////

//Expand div element indicated by id.
function Expand( id )
{
    try 
    { 
        new Effect.SlideDown( id, { scaleContent:false,scaleFromCenter:false,duration:0.3 } );
    }
    catch (e) {}
}

//Collapses div element indicated by id.
function Collapse( id )
{
    try 
    { 
        new Effect.SlideUp( id, { scaleContent:false,scaleFromCenter:false,duration:0.3 } ); 
    }
    catch (e) {}
}

//Highlights div element indicated by id.
function Highlight( id )
{
	try 
	{
		new Effect.Highlight( id, { startcolor:'#ffffdb', endcolor:'#ffffff', restorecolor:'#ffffff' } );
	}
	catch( e ) {}
}

///////////Print Functionality///////////

//Open the print page and display the selected offer details.
function PrintDetail(event)
{
    box.Close();
    window.open('Print.aspx?type=details&id=' + offer.id);
}

//Open the print page and display the selected bundle details.
function PrintBundleDetail(event)
{
    box.Close();
    window.open('Print.aspx?type=bundle&id=' + offer.id);
}

//Open the print page and display the selected learning center article.
function PrintArticle(event)
{
    box.Close();
    window.open('Print.aspx?type=article&issue=' + article);
}

//Open the print page and display the selected company information.
function PrintInfo( event )
{
	box.Close();
    window.open('Print.aspx?type=info&page=' + htmlPage);
}

///////////Litebox Calls///////////

//Display selected offer details.
function ShowDetail(id)
{
	if( focused != null )
	{
		focused.Close();
	}
	
    box = new Lightbox('details1');
    box.Left = 25;
    box.Height = 597;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Show();
    focused = box;
    
    offer.id = id;
    Event.observe( $(box.CloseRef()), 'click', CloseDetail );
    Event.observe( $('print_link'), 'click', PrintDetail );
    showDetails_Begin( id );
}

//Ajax call for offer details.
function showDetails_Begin(id)
{
    ClientState.clearArgs();
    ClientState.data.Args.push(id);
    ClientState.data.Command = "showDetails";
    ClientState.notifyCommand( showDetails_End );
}

//Ajax callback function for offer details.
function showDetails_End(transport)
{
    if( box != null )
    {
        box.InnerHTML = transport.responseText;
        box.Update();
    }
}

//Display selected bundle details in a litebox.
function showBundleDetails(id)
{
    box = new Lightbox('details0');
    box.Left = 25;
    box.Height = 598;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Show();
    focused = box;
    
    offer.id = id;
    Event.observe( $(box.CloseRef()), 'click', CloseDetail );
    Event.observe( $('print_link'), 'click', PrintBundleDetail );
    showBundleDetails_Begin(id);
}

//Ajax call for bundle details.
function showBundleDetails_Begin(id)
{
    ClientState.clearArgs();
    ClientState.data.Command = "showBundleDetails";
    ClientState.data.Args.push( id );
    ClientState.notifyCommand( showBundleDetails_End );
}

//Ajax callback for bundle details.
function showBundleDetails_End( transport )
{
    if( box != null )
    {
        box.InnerHTML = transport.responseText;
        box.Update();
    }
}

//Diplay company info in a litebox.
function showCompanyInfo(file,e)
{
	if( focused != null )
	{
		focused.Close();
	}
	
    box = new Lightbox('Info1');
    box.Left = 25;
    box.Height = 611;
    box.Width = 701;
    box.Modal = true;
    box.Shadow = false;
    box.Draggable = true;
    box.Content = "Article";
    box.Show();
    htmlPage = file;
    focused = box;
	Event.observe( $(box.CloseRef()), 'click', CloseDetail );
	Event.observe( $('print_link'), 'click', PrintInfo );
    
    showCompanyInfo_Begin(file);
}

//Ajax call for company information.
function showCompanyInfo_Begin( file )
{
    ClientState.clearArgs();
    ClientState.data.Args.push(file);
    ClientState.data.Command = "showCompanyInfo";
    ClientState.notifyCommand( showCompanyInfo_End );
}

//Ajax callback function for company information.
function showCompanyInfo_End( transport )
{
	if( box != null )
	{
		box.InnerHTML = transport.responseText;
		box.Update();
	}
}

//Display selected learning center article in a litebox.
function showArticle(uri)
{
	if( focused != null )
	{
		focused.Close();
	}
	
     box = new Lightbox('article1');
     box.Left = 25;
     box.Height = 602;
     box.Width = 701;
     box.Modal = false;
     box.Shadow = false;
     box.Draggable = true;
     box.Content = "Article";
     box.Show();
     
     focused = box;
     article = uri;
     Event.observe( $(box.CloseRef()), 'click', CloseDetail );
     Event.observe( $('print_link'), 'click', PrintArticle );
     showArticle_Begin( uri );
}

//Ajax call for learning center article.
function showArticle_Begin(uri)
{
    ClientState.clearArgs();
    ClientState.data.Args.push(uri);
    ClientState.data.Command = "showArticle";
    ClientState.notifyCommand( showArticle_End );
}

//Ajax callback for learning center.
function showArticle_End(transport)
{
    if( box != null )
    {
        box.InnerHTML = transport.responseText;
        box.Update();
    }
}

//Closes the current litebox.
function CloseDetail(event)
{
	if( focused != null )
	{
		focused.Close();
		focused = null;
	}
}

//Collapses the category element indicated by the id.
function hideCategory(id)
{
    Collapse( id );
}

//Displays the category element indicated by the id.
function showCategory(id)
{
    Expand(id);
}

function updateAtAGlance_Begin()
{
    ClientState.clearArgs();
    ClientState.data.Command = "updateAtAGlance";
    ClientState.notifyCommand( updateAtAGlance_End );
}

function updateAtAGlance_End( transport )
{
    var div = $("AtAGlancePanel");
    div.innerHTML = transport.responseText; 
}


function updatePriceSummary_Begin()
{
    ClientState.clearArgs();
    ClientState.data.Command = "updatePriceSummary";
    ClientState.notifyCommand( updatePriceSummary_End );
}

function updatePriceSummary_End(transport)
{
    $("priceSummaryDiv").innerHTML = transport.responseText;
}

function updateOfferBuilder_Begin()
{
    ClientState.clearArgs();
    ClientState.data.Command = "updateOfferBuilder";
    ClientState.notifyCommand( updateOfferBuilder_End );
}

function updateOfferBuilder_End(transport)
{
    $("offer_builder").innerHTML = transport.responseText;
}



function showOfferBuilderSummary()
{
    updateOfferBuilder_Begin();
}

function showOfferBuilderDetail()
{
    ClientState.clearArgs();
    ClientState.data.Command = "showOfferBuilderDetail";
    ClientState.notifyCommand( showOfferBuilderDetail_End );
}

function showOfferBuilderDetail_End(transport)
{
    $("offer_builder").innerHTML = transport.responseText;
}

////////////////////////////////////////////////SearchPanelControl.ascx////////////////////////////////////////////////////

function PhoneTabOver(e)
{
	var element = Event.element(e);
	switch( element.id )
	{
		case "areaInput" :
			if( element.value.length == 3 )
			{
				$("prefixInput").focus();
			}
			break;
		case "prefixInput":
			if( element.value.length == 3 )
			{
				$("suffixInput").focus();
			}
			break;
		case "suffixInput":
			if( element.value.length == 4 )
			{
				$("emailInput").focus();
			}
			break;
		default :
			break;
	}
}
    
 function SwapPanels()
 {
     if ( $("phone").style.display == "block" )
     {
         $("address").style.display = "block";
         $("phone").style.display = "none";
         $("swapLink").innerHTML = "Use Phone Number";
     }
     else
     {
         $("address").style.display = "none";
         $("phone").style.display = "block";
         $("swapLink").innerHTML = "Use Address Instead";
     }
 }
     
function IsValid()
{
    var valid = true;
    if( $("phone").style.display == "block" )
    {
        if( (isNaN($("areaInput").value) || ($("areaInput").value.length < 3)) || 
            (isNaN($("prefixInput").value) || ($("prefixInput").value.length < 3)) || 
            (isNaN($("suffixInput").value) || ($("suffixInput").value.length < 4)) )
        {
            $("phoneMarker").style.display = "inline";
            valid = false;
        }
    }
    else
    {
        if( $("addressInput").value == "" )
        {
            $("addressMarker").style.display = "inline";
            valid = false;
        }
        else
        {
            $("addressMarker").style.display = "none";
        }
        
        var zipCode = $("zipCodeInput").value.replace(" ","");
        if((zipCode.length < 5 ) || ( isNaN(zipCode)))
        {
            $("zipCodeMarker").style.display = "inline";
            valid = false;
        }
        else
        {
            $("zipCodeMarker").style.display = "none";
        }
    }
    
    if(( $("emailMarker").style.display == "block" ) && ( $("emailInput").value == "" ) )
    {
		valid = false;
    }
    
    return valid;
}

function SubmitAddress()
{
    if( IsValid() )
    {
        var querystring = "";
        if( $("phone").style.display == "block" )
        {               
              querystring = "phone=" + $("areaInput").value + "-" + $("prefixInput").value + "-" +$("suffixInput").value + 
                            "&email=" + $("emailInput").value;
        }
        else
        {
              querystring = "address=" + $("addressInput").value + "&apt=" + $("apartmentInput").value + "&zip=" + $("zipCodeInput").value + "&email=" + $("emailInput").value;
              querystring = querystring.replace("#","");
        }
        
        CallDispatch( querystring );
    }
    else if(( $("emailMarker").style.display == "block" ) && ( $("emailInput").value == "" ))
    {
		alert("Please enter a valid email.");
    }
    else if( $("phone").style.display == "block" )
    {
        alert("Please enter a valid phone number.");
    }
    else
    {
        alert("Please enter a valid address and zip code.");
    }
}
     
function CallDispatch(querystring)
{
    location.href = "http://direct.digitallanding.com/Dispatch.aspx?promoid=8001001&" + querystring; 
}

function NotMyAddress_Begin()
{
    ClientState.clearArgs();
    ClientState.data.Command = "notMyAddress";
    ClientState.notifyCommand( NotMyAddress_End );
    
    box2 = new Lightbox('AddressBox1')
    box2.Width = 275; 
    box2.Height = 230;
    box2.Modal = true;
    box2.Shadow = false;
    box2.Content = "Default";
    box2.Show();
    Event.observe( $(box2.CloseRef()), 'click', CloseDetail );
    
    focused = box2;
}

function NotMyAddress_End( transport )
{
    box2.InnerHTML = transport.responseText;
    box2.Update();
}
