﻿///////////Basic UI Effects///////////

//Expand div element indicated by id.
function Expand( id )
{
    try 
    {
        new Effect.SlideDown( id, { scaleContent:false,scaleFromCenter:false,scaleTo:100,duration:0.3 } );
    }
    catch (e) {}
}

//Collapses div element indicated by id. 
function Collapse( id )

{
    try 
    { 
        new Effect.SlideUp( id, { scaleContent:false,scaleFromCenter:false,scaleTo:100,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 ) {}
}

function CloseLightbox(event)
{
	if( box != null )
		box.Close();
}

//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);
}

// Displays the wait indicator.   
function DisplayWait()
{
	var divWait = $('divWait');
	if(divWait)
	{
		if(navigator.userAgent.toLowerCase().indexOf("msie 6") != -1)
		{
			//divWait.parentNode.style.width = "200px";
			divWait.style.position = "absolute";
			divWait.style.top = (document.body.parentNode.scrollTop + 200) + "px";
		}
		
		divWait.style.zIndex = 200;
		divWait.style.display = "block";
	}
}

// Hides the wait indicator. 
function HideWait()
{
	var divWait = $('divWait');
	if(divWait)
		divWait.style.display = "none";
}

////////////////////////////////////////////////Event Handling////////////////////////////////////////////////
//var verbose = true;

function OnError( ajaxResponse )
{
	var error = ajaxResponse.Error;
	
	if( showAjaxErrors )
		alert( error.Message + "\n" + error.Type + "\n" + error.StackTrace );
}

function OnPreRequest( ajaxRequest )
{
	DisplayWait();
}

function OnPostRequest( ajaxRequest )
{
	//Not implemented
}

function OnPreCallback( ajaxResponse )
{
	HideWait();
}
///////////Litebox Calls///////////
var DETAILS_LINK_TYPE =
{
	OfferNameLink:1,
	SelectedOfferNameLink:2,
	OfferDetailLink:3,
	SelectedOfferDetailLink:4,
	BonusDetailLink:5,
	SelectedBonusDetailLink:6,
	OfferFeaturesLink:7,
	BonusFeaturesLink:8
}
////////////////////////////////////////////////Light box////////////////////////////////////////////////////
var box = null;

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.iframe = null;
    
    this.initialize = function()
    {
           this.InnerHTML = '<center><img src="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 + 20;
        dropshadow.style.top = (this.offsetY + 20) + "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="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="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 if( this.Content == "BazaarVoice" )
        {
                messageBox.innerHTML = '<div id="pop-nav" class="cf" style="position:relative;width:' + (this.Width - 12) + 'px;">' +
                                       '<div id="close"><a id="close_link" href="javascript:void(0);"><img src="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:500px;overflow:auto;">' +
                                       '<div id="details-change"></div></div>';
               this.DragGrip = "grip";
        }
        else if( this.Content == "Phone" )
        {
                messageBox.innerHTML = '<div id="pop-nav" class="cf" style="position:relative;width:' + (this.Width - 12) + 'px;">' +
                                       //'<div id="close"><a id="close_link" href="javascript:void(0);"><img src="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 class="cf" style="width:' + this.Width + 'px;height:' + this.Height + 'px;">' +
                                       '<div id="details-phone"></div></div>';
               this.DragGrip = "grip";
        }
        else
        {
                messageBox.innerHTML = '<div id="pop-nav" class="cf" style="position:relative;width:' + (this.Width - 12) + 'px;">' +
                                       '<div id="close"><a id="close_link" href="javascript:void(0);"><img src="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 class="cf" style="overflow:hidden;width:' + this.Width + 'px;height:' + this.Height + 'px;">' +
                                       '<div id="details-change"></div></div>';
               this.DragGrip = "grip";
        }
        
                    
        return messageBox;
    }
    
    this.createIframe = function()
    {
		var iframe = null;
		if(Prototype.Browser.IE)
		{
			iframe = document.createElement("iframe");
			iframe.style.zIndex = 99;
			iframe.style.position = "absolute";
			iframe.style.width = this.Width + "px";
		    iframe.style.height = (this.Height + 3) + "px";
	        iframe.style.top =  this.offsetY + "px";
			iframe.style.left = this.offsetX + "%";
			iframe.style.display = "none";
		}
		
		return iframe;
    }
    
    this.ShowMask = function()
    {
        var FFOpacity = "0.5";
        var IEOpacity = "alpha(opacity=50);";
        if( this.Modal )
        {
			this.mask = this.createOverlay();
            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();
        this.iframe = this.createIframe();
        var h = this.Height;
        var w = this.Width;
        document.body.appendChild( this.messageBox );
        if(this.iframe)
        {
			document.body.appendChild(this.iframe);
			new Effect.Parallel(
				[	new Effect.BlindDown( this.iframe, {sync:true,scaleFrom:0,scaleTo:100,queue:{position:'end',scope:'second'}}),
					new Effect.BlindDown( this.messageBox, {sync: true, scaleFrom:0,scaleTo:100,queue:{position:'end',scope:'second'}}) ],
	        { duration:0.5 }
	        )
	        
		}
		else
	        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 );
			if(this.iframe) document.body.removeChild(this.iframe);
        }
        catch(ex){}
    }
    this._hide = function(event)
    {
        if(event) Event.stop(event);
        CloseBox(event);
    }
    this.Update = function()
    {
		var container;
		if((this.Content == "Article" ) || (this.Content == "Details" ))
			container = $('details-wrapper');
		else if( this.Content == "Phone" )
			container = $('details-phone');
		else
			container = $('details-change');
			
		if(container)
			container.innerHTML = this.InnerHTML;
    }

    this.CloseRef = function()
    {
        return 'close_link';
    }
}

//Closes the current litebox.
function CloseBox(event)
{
	if( box != null )
	{
		box.Close();
		box = null;
	}
}

////////////////////////////////////////////////Global Functions////////////////////////////////////////////////////

var customizationGroups = new Hash();
var customizationGroupToOpen = null;

function RegisterCustomizationGroup( group )
{
    customizationGroups.set(group, new Hash());
    if (customizationGroupToOpen == null) customizationGroupToOpen = group;
}

var chosenOfferID = null;
var chosenArticle = null;

//Open the print page and display the selected offer details.
function PrintDetailEvent(event)
{
    box.Close();
    window.open('Print.aspx?type=details&id=' + chosenOfferID);
}

//Open the print page and display the selected learning center article.
function PrintArticleEvent(event)
{
    box.Close();
    window.open('Print.aspx?type=article&issue=' + chosenArticle);
}

//Open the print page and display the selected company information.
function PrintInfoEvent( event )
{
	box.Close();
    window.open('Print.aspx?type=info&page=' + chosenArticle);
}

function NotMyAddressEvent( event )
{
    box = new Lightbox('AddressBox1')
    box.Width = 275; 
    box.Height = 230;
    box.Modal = true;
    box.Shadow = false;
    box.Content = "Default";
    box.Show();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    
    RenderSearchPanelControl(Lightbox_Callback);
}

function StartOverEvent(event)
{
    box.Close();
	box = null;
    NotMyAddressEvent( event )
}

function OfferDetailEvent( offerID, source )
{
	if( box != null )
		box.Close();
		
	chosenOfferID = offerID;
    box = new Lightbox('details1');
    box.Left = 25;
    box.Height = 597;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Show();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    Event.observe( $('print_link'), 'click', PrintDetailEvent );
    
	RenderOfferDetails( offerID, source, Lightbox_Callback );
}

function ArticleEvent( file )
{
	if( box != null )
		box.Close();

	chosenArticle = file;
    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();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    Event.observe( $('print_link'), 'click', PrintArticleEvent );
    
    RenderArticleHTML( file, Lightbox_Callback );
}

function CompanyInfoEvent( file, event )
{
	if( box != null )
		box.Close();

	chosenArticle = file;
    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();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    Event.observe( $('print_link'), 'click', PrintInfoEvent );
     
	RenderCompanyInfo( file, Lightbox_Callback );
}

function MySelectionDetailsEvent(event)
{
	RenderMySelectionDetailControl(RenderMySelectionControl_Callback);
}

function MySelectionSummaryEvent(event)
{
	RenderMySelectionSummaryControl(RenderMySelectionControl_Callback);
}

function Lightbox_Callback( ajaxResponse )
{
    if( box != null )
    {
		if( !ajaxResponse.HasError )
		{
			box.InnerHTML = ajaxResponse.Output;
			box.Update();
		}
		else
		{
			box.InnerHTML = ACCELLER_AJAX_LIGHTBOX_ERROR;
			box.Update();
		}
    }
    else
		alert( ACCELLER_AJAX_LIGHTBOX_ERROR );
}

function RenderMySelectionControl_Callback( ajaxResponse )
{
	if( !ajaxResponse.HasError )
	{
		var div = $("offer_builder");
		if( div != null )
		{
			div.innerHTML = ajaxResponse.Output;
		}
    }
}


function RenderAtAGlanceControl_Callback( ajaxResponse )
{
	if( !ajaxResponse.HasError )
	{
		var div = $("AtAGlancePanel");
		if( div != null )
		{
			div.innerHTML = ajaxResponse.Output;
		}
	}
}

//////////////////////////SCHEDULING///////////////////////////
var scheduleControl;

function ChooseScheduleEvent( Type, ProviderID, OfferID, e )
{
	scheduleControl = Event.element(e); 
	var value = scheduleControl.value;

    ChooseSchedule( Type, ProviderID, OfferID, value, ChooseSchedule_Callback);
    
    return true;
}

function ChooseSchedule_Callback( ajaxResponse )
{
	if(ajaxResponse.HasError)
	{
	    alert('Error: ' + ajaxResponse.Error.Message);
	    scheduleControl.selectedIndex = 0;
	}
	else
	{
	    MarkComplete('scheduling', ValidateGroup('scheduling') );
    }

	var div = $("phScheduleSummary");
	if ( div != null ) div.innerHTML = ajaxResponse.Output;
}

function ValidateScheduling ()
{
    var isValid = true;
    
    if (scheduleControls)
    {
        var index = 0;
        var length = scheduleControls.length;
        
        for (index; (index < length) && (isValid == true); index++)
        {
            if ($(scheduleControls[index]).value == "-1") isValid = false;
        }
    }
    else
        isValid = false;

    return isValid;
}

////////////////////////////////////////////////SearchPanelControl.ascx////////////////////////////////////////////////////
function NewPhoneTabOver( currentEvent, elementLength, nextElement )
{
	var element = Event.element(currentEvent);
	var chr = currentEvent.charCode || currentEvent.keyCode;

	if(chr == 9 || chr == 16) return; //ignore tab and shift key
	if( element.value.length == elementLength )
	{
    	var input = $(nextElement);
    	if (input != null) {
       	    input.focus();
	        if(input.select)
		        input.select();
		}
	}
}
function PhoneTabOver(e)
{
	var element = Event.element(e);
	var chr = e.charCode || e.keyCode;
	if(chr == 9 || chr == 16) return; //ignore tab and shift key
	switch( element.id )
	{
		case "areaInput" :
			if( element.value.length == 3 )
			{
				selectInput("prefixInput");
			}
			break;
		case "prefixInput":
			if( element.value.length == 3 )
			{
				selectInput("suffixInput");
			}
			break;
		case "suffixInput":
			if( element.value.length == 4 )
			{
				selectInput("emailInput");
			}
			break;
		default :
			break;
	}
}

function selectInput(inputID)
{
	var input = $(inputID);
	input.focus();
	if(input.select)
		input.select();
}
    
 function SwapPanels()
 {
     if ( $("phone").style.display == "block" )
     {
         $("address").style.display = "block";
         $("phone").style.display = "none";
         $("swapLink").innerHTML = SEARCH_PANEL_USE_PHONE_TEXT;
     }
     else
     {
         $("address").style.display = "none";
         $("phone").style.display = "block";
         $("swapLink").innerHTML = SEARCH_PANEL_USE_ADDRESS_TEXT;
     }
 }
     
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";
        }
        
        if( $("apartmentInput").value != "" )
        {
			var apt = $("apartmentInput").value;
			if(( apt.indexOf("!") > -1 ) || ( apt.indexOf("@") > -1 ) || ( apt.indexOf("#") > -1 )|| ( apt.indexOf("$") > -1 )|| ( apt.indexOf("%") > -1 ) 
				|| ( apt.indexOf("^") > -1 )|| ( apt.indexOf("&") > -1 )|| ( apt.indexOf("*") > -1 ) || ( apt.indexOf("(") > -1 ) || ( apt.indexOf(")") > -1 )
				|| ( apt.indexOf("-") > -1 )|| ( apt.indexOf("=") > -1 )|| ( apt.indexOf("+") > -1 )|| ( apt.indexOf("?") > -1 )|| ( apt.indexOf("/") > -1 ) )
			{
				valid = false
				$("aptMarker").style.display = "inline";
			}
			else
				$("aptMarker").style.display = "none";
        }
        else
        {
			$("aptMarker").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";
        }
    }
    
    var emailinput = $("emailInput");    
    if(( $("emailMarker").style.display == "block" ) && ( emailinput.value == "" ) )
    {
		valid = false;
    }
    
    if(emailinput.value != "" && !(emailRegex.test(emailinput.value)))
    {
		valid = false;
    }
    
    return valid;
}

var emailRegex = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;

function SubmitAddress()
{
    //GEMINI DL-3927
    var phoneNumber = $("areaInput").value + "-" + $("prefixInput").value + "-" +$("suffixInput").value;
    
	var emailInput = $("emailInput");
    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(emailInput.value != "" && !(emailRegex.test(emailInput.value)))
    {
		alert(INVALID_EMAIL);
    }
    else if(( $("emailMarker").style.display == "block" ) && ( $("emailInput").value == "" ))
    {
		alert(SEARCH_PANEL_INVALID_EMAIL);
    }
    else if( $("phone").style.display == "block" )
    {
        alert(GENERAL_INVALID_PHONE_NUMBER);
    }
    else
    {
        alert(SEARCH_PANEL_INVALID_ADDRESS_ZIPCODE);
    }
    
    

    
}
     
function CallDispatch(querystring)
{
    location.href = "http://direct.digitallanding.com/Dispatch.aspx?" + querystring + "&PromoId=7006159";
}

///////////////////////////////////////////////Dispatch.aspx///////////////////////////////////////////////

var validation_counter = 0;

function ClosePhoneEntryEvent()
{
	box.Close();
	box = null;
	ValidateCustomerInformation(ValidateCustomerInformation_Callback);
}

function UpdatePhoneEvent(e)
{
	var phone = $("npa").value + $("nxx").value + $("suffix").value;
	UpdatePhone( phone, UpdatePhone_Callback );
	box.Close();
}

function ValidateInfo(phone,address,apt,zip)
{
	if((phone != "") && ( phone.length != 10 ))
	{
		alert(GENERAL_INVALID_PHONE_NUMBER);
		return false;
	}
	else if( address == "" )
	{
		alert(GENERAL_INVALID_ADDRESS);
		return false;
	}
	else if( zip == "" )
	{
		alert(GENERAL_INVALID_ZIPCODE);
		return false;
	}
	else
		return true;
}

function ResubmitEvent(e)
{	
	var phone = "";
	var address = "";
	var apt = "";
	var zip = "";
	
	if( $("phoneNumberInput") != null )
		phone = $("phoneNumberInput").value;
	if( $("addressInput") != null )
		address = $("addressInput").value;
	if( $("apartmentInput") != null )
		apt = $("apartmentInput").value;
	if( $("zipCodeInput") != null )
		zip = $("zipCodeInput").value;
		
	if (ValidateInfo(phone,address,apt,zip))
	{
		ResubmitCustomerInformation(phone,address,apt,zip, ResubmitCustomerInformation_Callback);
		box.Close();
	}
}

function IsPhoneRequired_Callback( ajaxResponse )
{
	if( (!ajaxResponse.HasError) && ( eval(ajaxResponse.Output) ) )
	{
		if( box != null )
			box.Close();
			
		box = new Lightbox("PhoneEntry1");
		box.Top = 80;
		box.Width = 350; 
		box.Height = 275;
		box.Modal = false;
		box.Shadow = true;
		box.Content = "Phone";
		box.Show();
		//Event.observe( $(box.CloseRef()), 'click', ClosePhoneEntryEvent );
		
		RenderPhoneEntryControl(RenderPhoneEntryControl_Callback);
	}
	else
	{
		ValidateCustomerInformation( ValidateCustomerInformation_Callback );
	}
}

function RenderPhoneEntryControl_Callback(ajaxResponse)
{
	if( !ajaxResponse.HasError )
	{
		box.InnerHTML = ajaxResponse.Output;
		box.Update();
	}
}

function UpdatePhone_Callback( ajaxResponse )
{
	if( !ajaxResponse.HasError )
		ValidateCustomerInformation( ValidateCustomerInformation_Callback );
}

function ValidateCustomerInformation_Callback(ajaxResponse)
{
	if( ajaxResponse.HasError )
	{
		if(( ajaxResponse.Error.Type == "AddressNormalizationException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else if(( ajaxResponse.Error.Type == "PhoneResolutionException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else if(( ajaxResponse.Error.Type == "AddressPhoneMismatchException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else
			location.href = "/Verification.aspx?type=address";
	}
	else
	{
		if( eval(ajaxResponse.Output) )
			GetCategories(false, GetCategories_Callback);
		else
			location.href = "/Verification.aspx?type=address";
	}

}

function RenderCustomerInfoControl_Callback( ajaxResponse )
{
	if( !ajaxResponse.HasError )
	{
		if( box != null )
			box.Close();
			
		box = new Lightbox("PhoneEntry1");
		box.Top = 80;
		box.Width = 350; 
		box.Height = 275;
		box.Modal = false;
		box.Shadow = true;
		box.Content = "Phone";
		box.Show();
		
		box.InnerHTML = ajaxResponse.Output;
		box.Update();
		validation_counter++;
	}	
}

function ResubmitCustomerInformation_Callback( ajaxResponse )
{
	if ( !ajaxResponse.HasError )
	    // GEMINI : DL-4186 (Roberto Mardeni)
		// GetCategories(true, GetCategories_Callback);
		GetCategories(false, GetCategories_Callback);
		// END OF GEMINI : DL-4186 (Roberto Mardeni)
	else
		location.href = "/Verification.aspx?type=address";
}

function GetCategories_Callback( ajaxResponse )
{
	if( ajaxResponse.HasError )
	{
	    //Add a counter to avoid endless loop.
		if(( ajaxResponse.Error.Type == "AddressNormalizationException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else if(( ajaxResponse.Error.Type == "PhoneResolutionException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else if(( ajaxResponse.Error.Type == "AddressPhoneMismatchException" ) && (validation_counter == 0))
			RenderCustomerInfoControl( RenderCustomerInfoControl_Callback );
		else
			location.href = "/Verification.aspx?type=address";
	}
	else if( (!ajaxResponse.HasError )) //&&( eval( ajaxResponse.Output ) ) )
	{
		var response = eval( "( " + ajaxResponse.Output + " )" );
		if(response.Status == "3")
		{
			location.href = "/Verification.aspx?type=address";
		}
		else if(response.Code == "10") //one click offer succeeded
		{
			location.href = "/PlaceOrder.aspx";
		}
		else
		{
			location.href = "/ShowOffers.aspx";
		}
	}
	else
	{
		location.href = "/Verification.aspx?type=none";
	}
}

///////////////////////////////////////////////ShowOffers.aspx///////////////////////////////////////////////

var chosenCategory;
var topCategory;
var Page = {
		Categories : new Hash()
	};

function OpenCategory( category )
{
	$(category + "_CategoryInfo").style.display = "none";
	$("close" + category).style.display = "block";
	$("title" + category).style.display = "block";
	Expand(category + "Offers");
}

function CloseCategory( category )
{
	Collapse( category + "Offers" );
	$(category + "_CategoryInfo").style.display = "block";
	$("close" + category).style.display = "none";
	$("title" + category).style.display = "none";
}

function ChooseBundleEvent(bundleID, event)
{
	ChooseBundle(bundleID,ChooseBundle_Callback);
}

function ShowOffersEvent(event)
{
    var element = Event.element(event);
    var category = element.id.replace("show", "");
    chosenCategory = Page.Categories.get( category );
    if( chosenCategory.HTML == null )
    {
        RenderOfferControl(chosenCategory.Type,chosenCategory.ID,RenderOfferControl_Callback.bind(window, chosenCategory));
    }
    else
    {
		OpenCategory(category);
    }
}

function CloseOffersEvent(event)
{
    var element = Event.element(event);
    var category = element.id.replace("close","");
    if( $(category + "_CategoryInfo").style.display == "none" )
    {
		CloseCategory( category );
    }
}

function RemoveOfferEvent( offerID, type )
{
   // Expand( type + "Category" );
    if( type != "Bundle" )
    {
		$("chkWant" + type ).disabled = false;
		RemoveOffer( offerID, RemoveOffer_Callback );
	}
	else
	{
		RemoveBundle( offerID, RemoveOffer_Callback );
	}
}

function ChooseOfferEvent(offerID, type, categoryID, event)
{
	chosenCategory = Page.Categories.get(type);
	ChooseOffer( offerID, categoryID, ChooseOffer_Callback );
    if( $("BundleCategory") != null )
    {
          if( $("BundleCategory").style.display == "none" )
               Expand("BundleCategory");
    }
}

function ChooseOffer_Callback( ajaxResponse )
{
	if( ( !ajaxResponse.HasError ) && (eval(ajaxResponse.Output) ))
	{
		if( chosenCategory != null )
		{
			var chbx = $("chkWant" + chosenCategory.Type);
		// GEMINI DL-3918
			chbx.checked = false;
			chbx.disabled = true;
			toggleCategories();
			hideCategory(chosenCategory.Type + "Category");
			chosenCategory.Visible = false
			scroll(0,0);
		}
		
		RenderMySelectionSummaryControl(RenderMySelectionControl_Callback);
		RenderAtAGlanceControl(RenderAtAGlanceControl_Callback);
	}
	else
	{
		alert( SHOWOFFERS_UNABLETOCHOOSE );
	}
}

function RenderOfferControl_Callback( category, ajaxResponse )
{
	if(category == null)
		category = chosenCategory;
		
	if( ajaxResponse.HasError )
	{
		alert( SHOWOFFERS_OFFERSUNAVAILABLE );
	}
	else
	{
		if( category != null )
		{
			category.HTML = ajaxResponse.Output;
			$(category.Type + "Offers").innerHTML = category.HTML;
			OpenCategory( category.Type );
		}
	}	
}

function ChooseBundle_Callback( ajaxResponse )
{
	if( ajaxResponse.HasError ) 
	{
		alert( SHOWOFFERS_UNABLETOCHOOSE );
	}
	else
	{
		location.href = "/PlaceOrder.aspx";
	}
}

function RemoveOffer_Callback( ajaxResponse )
{
    toggleCategories();
	if( ajaxResponse.HasError )
	{
		alert( ajaxResponse.Error.Message );
	}
	else
	{
		RenderMySelectionSummaryControl(RenderMySelectionControl_Callback);
		RenderAtAGlanceControl(RenderAtAGlanceControl_Callback);
	}
}

function showBundlesEvent(e)
{
    var category = "Bundle";
    chosenCategory = Page.Categories.get( category );
    
    if ( chosenCategory != null) 
    {
        if( chosenCategory.HTML == null )
            RenderOfferControl(chosenCategory.Type,chosenCategory.ID,RenderOfferControl_Callback.bind(window, chosenCategory));
        else
		    OpenCategory(category);
		   
		var div = $( category + "Category" );
		if (div != null)
		{
		    if(div.scrollIntoView) div.scrollIntoView(true);
		    setTimeout('Highlight(' + div.id + ')', 300);
		    setTimeout('Highlight(' + div.id + ')', 1000);
		}
    }
}

//GEMINI DL-3734
function PlaceOrder(e)
{
	ValidateSelection(ValidateSelection_Callback);
}

function ValidateSelection_Callback( ajaxResponse )
{
	if( ajaxResponse.HasError )
	{
	    var error = ajaxResponse.Error;
		alert( error.Message + "\n" + error.Type + "\n" + error.StackTrace );
	}
	else
	{
		var result = eval( "(" + ajaxResponse.Output + ")" );
		if (result.Status == 1)
		{
		    location.href = "/PlaceOrder.aspx";
		}
		else
		{
		    alert(result.Message); 
		}
	}
}

///////////////////////////////////////////////PlaceOffer.aspx///////////////////////////////////////////////

function chooseCustomization( group, customizationID, choiceID, e )
{
	var customization = customizationGroups.get(group).get(customizationID);
	var element = Event.element(e);
    var isValid = validateCustomization( group, customization, choiceID );
    if( isValid )
    {
		if(( customization.Type == "Checkbox" ) || ( customization.Type == "Radio" ))
		{
			if( element.checked )
				ChooseCustomization(Object.toJSON(customization), choiceID, ChooseCustomization_Callback);
			else
				RemoveCustomization(Object.toJSON(customization), choiceID, ChooseCustomization_Callback);
		}
		else 
		{
			if( customization.Value != "" )
			{
				if( customization.Validate && customization.ComparisonCount < 1 )
				{
					customization.ComparisonCount++;
					CompareCustomization( customizationID, choiceID, escape(customization.Value), CompareCustomization_Callback.bind(window, customization, choiceID) );
				}
				else
				{
					//letting it through, regardless of validation, mark the choice valid, no errors
					if(customization.validationErrors)
						customization.validationErrors.set(choiceID, false);
					ChooseCustomization(Object.toJSON(customization), choiceID, ChooseCustomization_Callback);
				}
			}
			else
			{
				RemoveCustomization(Object.toJSON(customization), choiceID, ChooseCustomization_Callback);
				if(customization.validationErrors)
					customization.validationErrors.unset(choiceID);
			}
		}
		
		//UpdateChildCustomizations( group, customization, choiceID );
    }

    //MarkComplete(group, ValidateGroup(group) );

    
	return isValid;
}

function CompareCustomization_Callback( customization, choiceID, ajaxResponse )
{
	if( ajaxResponse.HasError )
	{
	
	}
	else
	{
		if(!customization.validationErrors)
			customization.validationErrors = new Hash();
			
		var result = eval( "(" + ajaxResponse.Output + ")" );
		if( result.Status != 1 )
		{
			if(!result.Message)
				result.Message = customization.Name + CUSTOMIZATION_ERR_INVALID;
			alert( result.Message );
			customization.validationErrors.set(choiceID, true);
			SetTextboxError(customization, document.getElementById(choiceID));
			
		}
		else //success
		{
			customization.validationErrors.set(choiceID, false);			
		}
	}
}

function ChooseCustomization_Callback( ajaxResponse )
{
	if(ajaxResponse.HasError)
	{
	
	}
	else
	{
		var div = $("AtAGlance");
		div.innerHTML = ajaxResponse.Output;
		MySelectionDetailsEvent(); 
		Highlight("pricesummary"); 
	}
}

function chooseDropDownCustomization( group, customization, e )
{
    var element = Event.element(event);
	var index = element.selectedIndex;
	var selectedItem = element.options[index];
	var choiceID = selectedItem.id;
	chooseCustomization( group, customization, choiceID, e);
	return true;
}

function MoveToNext( group )
{
	Collapse( "div" + group );
	
	var keys = customizationGroups.keys();
	var index = 0;
	var length = keys.length;
	var current = -1;
	for( index; index < length; ++index )
	{
		if( keys[index] == group )
			current = index;
	}

	if ( current < (length - 1) )
	{
		Expand( "div" + keys[current + 1] );
	}
}

function OpenOptionsPanel( name )
{
	if(!customizationGroups) return;
	
	var keys = customizationGroups.keys();
	var i = 0;
	var length = keys.length;
	
	for( i; i < length; i++ )
	{	
		if( ($("div" + keys[i]).style.display == "block" ) || ($("div" + keys[i]).style.display == "" )  )
		{
			Collapse("div" + keys[i]);
			if( keys[i] != "checkout" )
			{
				$("div" + keys[i] + "Expand").style.display = "block";
				$("div" + keys[i] + "Close").style.display = "none";
			}
		}
	}
	
	var divcheckout = $("divcheckout");
	if(( name != "divcheckout" ) && divcheckout && ( (divcheckout.style.display == "block" ) || (divcheckout.style.display == "") ))
	{
		Collapse("divcheckout");
	}
	
	if( $(name).style.display == "none" )
	{
		Expand(name);
		if( name != "divcheckout" )
		{
			$(name + "Expand").style.display = "none";
			$(name + "Close").style.display = "block";
		}
	}
}

function PreviousGroup( group )
{
	var keys = customizationGroups.keys();
	var index = 0;
	var length = keys.length;
	var previous = "";
	var last = "";
	
	for( index; index < length; index++ )
	{
		if( keys[index] == group )
			previous = last;
		
		last = keys[index]
	}
	
	if( previous != "" )
		OpenOptionsPanel( "div" + previous );	
}

function ResetCustomization( customization )
{
	if( customization.Type == "Checkbox" )
	{
		customization.Selected = 0;
	}
	else if( customization.Type == "Dropdown" )
	{
		$(customization.ID).selectedIndex = -1;
	}
	
	if( !customization.TopLevel )
	{
		$("div" + customization.ID).style.display = "none";
		customization.Visible = false;
	}
	
	customization.Value = "";
	
	var j = 0;
	var l = customization.Choices.length;
	var element = null;
	for( j; j < length; ++j )
	{
		element = $(customization.Choice[j])
		if( element != null )
		{
			switch( customization.Type )
			{
				case "Checkbox" :
					element.checked = false;
					break;
				case "Radio" :
					element.checked = false;
					break;
				case "Text" :
					element.value = "";
					break;
				default :
					break;	
			}
		}
	}
}

/*
function UpdateChildCustomizations( group, customization, choiceID )
{
	var child = null;
	var choiceDependents = eval( "(" + $(choiceID + "_ChoiceInfo").innerHTML + ")" );
	var current = null;
	var queue = new Array();
	var length = 0;
	var i = 0;
	
	queue.push( customization );
	length = queue.length;
	
	while( length > 0 )
	{
		current = queue.pop();
		if(!current || !current.Children) { length=0; continue; }
		length = current.Children.length;
		for( i; i < length; ++i )
		{
			child = customizationGroups.get(group).get(current.Children[i]);
			if( child != null ) 
			{
				queue.push( child );
				ResetCustomization(child);
			}
		}
		length = queue.length;
	}
	
	length = choiceDependents.Items.length;
	for( i = 0; i < length; ++i )
	{
		$("div" + choiceDependents.Items[i]).style.display = "block";
		customization.Visible = true;
	}
}
*/
function validateCustomization( group, customization, choice )
{	
	var element;
	if( customization.Type == "Checkbox" )
	{
		return ValidateCheckboxCustomization( customization, choice );
	}
	else if (customization.Type =="Radio")
	{
		element = $(choice);
		customization.Value = element.value;
		return element.checked;
	}
	else if( customization.Type == "Text" )
	{
		element = $(choice);
		customization.Value = element.value;
		return true;
		//GEMINI:DL-3138
		/*
		var result = validateTextBox(customization);
		if (result)
		{
		    return result;
		}
		else
		{
			if (customization.ValidationMessage)
				alert(customization.ValidationMessage);
			else
				alert(customization.Name + CUSTOMIZATION_ERR_VALIDATION_PREFIX);
		}
		*/
	}
	else if( customization.Type == "Dropdown" )
	{
		element = $(customization.ID);
		var index = element.selectedIndex;
		customization.Value = element.options[index].value;
		return true;
	}
	else
	{
		customization.Value = choice;
		return true;
	}
	
}

//GEMINI:DL-3138
function validateTextBox (customization)
{
	if (customization.Value == '')
	{
		return true;
	}
	else
	{
		if (customization.ValidationRule != null) 
		{
		    var regExp = new RegExp(customization.ValidationRule);
		    var resultOfValidation = regExp.exec(customization.Value);
		    
		    if (resultOfValidation == null)
		    {
		        return false;
		    }
		    else
		    {
		        //Validation passed on.
		        return true;
		    }
		}
		else
		{
		    //Not validation rule provided.
		    return true;
		}
	}
}

function ValidateCheckboxCustomization( customization, choice )
{
	var checkbox = $(choice);
	if( checkbox.checked )
	{
		if( customization.Selected < customization.Maximum )
		{
			customization.Selected++;
			return true;
		}
		else
		{
			checkbox.checked = false;
			alert(CUSTOMIZATION_ERR_CHECKBOX_VALIDATION_EXACT_PREFIX + customization.Maximum + CUSTOMIZATION_ERR_CHECKBOX_VALIDATION_SUFFIX);
			return false;
		}
	}
	else
	{
		if(( customization.Selected <= customization.Minimum )&&(customization.Required))
		{
			alert(CUSTOMIZATION_ERR_CHECKBOX_VALIDATION_MINIMUM_PREFIX + customization.Minimum + CUSTOMIZATION_ERR_CHECKBOX_VALIDATION_SUFFIX);
		}
		customization.Selected--;
		return true;
	}
}

//Gemini DL-3766
//Rewrite of the complete function 
function ValidateGroup( group )
{
	var isValid = true;
	var isGroupValid = true;
	
	if (group == 'educationInformation' || group == 'employmentInformation' || group == 'financialInformation' || group == 'identityInformation' || group == 'incomeInformation' || group == 'residencyInformation')
	    isValid = true;
	else if (group == 'scheduling')
	    isValid = ValidateScheduling();
	else 
	{
	    customizationGroups.get(group).each( function(pair) {
			customization = pair.value;
			if(customization.Required && customization.Visible)
			{
				isValid = isValid && ValidateGroupCustomization(group, customization);
			}
		} );
    }
     	
	return isValid;
}



function ValidateGroupCustomization(group, customization)
{
	switch(customization.Type)
	{
		case "Label":
			return true;
		case "Radio":
			return (customization.Value!="");
		case "Checkbox":
			return ( customization.Selected >= customization.Minimum ) && ( customization.Selected <= customization.Maximum );
		case "Text":
			return ValidateTextboxChoices(customization);
		case "Compound":
			return ValidateCompoundChoices(group, customization);
		case "Dropdown":
			return ($(customization.ID).selectedIndex > 0);
		default:
			return true;
	}	   
}

function ValidateTextboxChoices(textboxCustomization)
{
	var count = 0;
	for(var i=0; i<textboxCustomization.Choices.length; i++)
	{
		var choiceID = textboxCustomization.Choices[i];
		var choice = $(choiceID);
		if(choice.value == "")
			continue;
		count++;
		var choiceHasError = false;
		if(textboxCustomization.validationErrors)
			choiceHasError = textboxCustomization.validationErrors.get(choiceID);
		if(choiceHasError)
		{
			alert(textboxCustomization.Name + CUSTOMIZATION_ERR_INVALID);
			SetTextboxError(textboxCustomization, choice);
			try { choice.focus(); } catch(e) {  };
			return false;
		}
	}
	
	var validCount = (count >= textboxCustomization.Minimum && count <= textboxCustomization.Maximum);
	
	return validCount;
}

function ValidateCompoundChoices(group, customization)
{
	var count = 0;
	for(var i=0; i<customization.Children.length; i++)
	{
		var childCustomization = customizationGroups.get(group).get(customization.Children[i]);
		if(!childCustomization) continue;
		
		//looking for number filled in and valid
		if(ValidateGroupCustomization(group, childCustomization))
		{
			count++;
		}
	}
	
	var validCount = (count >= customization.Minimum && count <= customization.Maximum);	
	
	return validCount;
}

function SetTextboxError(customization, choice)
{
	choice.style.color="#FF0000";
	if(!customization.ErrorHandlers)
		customization.ErrorHandlers = new Hash();
	var handler = ResetTextboxError.bind(window, customization, choice)
	customization.ErrorHandlers.set(choice.id, handler );
	Event.observe(choice, 'keypress', handler);
}

function ResetTextboxError(customization, textbox)
{
	textbox.style.color = "#000000";
	Event.stopObserving(textbox, 'keypress', customization.ErrorHandlers.get(textbox.id));
}

function ValidateAllGroups()
{
	var areValid = true;
	var found = false;
	customizationGroups.each( function( pair ) {
		var group = pair.key;
		if(( group != "checkout" ) && ( group != "creditcard" ))
			if( !ValidateGroup(group) )
			{
				areValid = false;
				if( !found )
				{
					OpenOptionsPanel("div" + group);
					found = true;
				}
			}
	});
	return areValid;
}

//For reverse compatibility
function checkRequired()
{
	return ValidateAllGroups();
}

function ShowChoiceDetails(id)
{
    $(id + "_details").style.display = ($(id + "_details").style.display == "block" ? "none" : "block");
}

function MarkComplete( group, visible )
{
	$( 'img' + group ).style.display = (visible) ? "block" : "none";
}

function VerifyComplete(group)
{
    if ( $('img' + group) != null ) {
        return ($( 'img' + group ).style.display == "block"); // if exists return the validation result

    } else if ( (group == 'creditCard') && ($("billingCheckImage") != null) ) {
        return ($("billingCheckImage").style.display == "block");
    } else {
        return true;  // if not exists
    }
    
    
}

function VerifyAllComplete()
{
    var isValid = '';
    var changed = false;
    
    if (!VerifyComplete('educationInformation'))
    {
        isValid = 'Education Information';
        changed = true;
    }
        
    if (!VerifyComplete('employmentInformation'))
    {
        if (changed) 
            isValid = isValid + ' and Employment Information';
        else 
            isValid = isValid + ' Employment Information';
        changed = true;
    }
        
    if (!VerifyComplete('financialInformation'))
    {
        if (changed) 
            isValid = isValid + ' and Financial Information';
        else 
            isValid = isValid + ' Financial Information';
        changed = true;
    }

    if (!VerifyComplete('identityInformation'))
    {
        if (changed) 
            isValid = isValid + ' and Identity Information';
        else 
            isValid = isValid + ' Identity Information';
        changed = true;
    }

    if (!VerifyComplete('residencyInformation'))
    {
        if (changed) 
            isValid = isValid + ' and Residency Information';
        else 
            isValid = isValid + ' Residency Information';
        changed = true;
    }

    if (!VerifyComplete('scheduling'))
    {
        if (changed) 
            isValid = isValid + ' and Scheduling Information';
        else 
            isValid = isValid + ' Scheduling Information';
        changed = true;
    }

    if (!VerifyComplete('creditCard'))
    {
        if (changed) 
            isValid = isValid + ' and Billing Information';
        else 
            isValid = isValid + ' Billing Information';
        changed = true;
    }

    return isValid;
}

function GroupCompleted( group )
{
    var isValid = false;
    var showMessage = false;
    
    if (group == 'educationInformation')
	    isValid = ValidateEducationInformation();
	else if (group == 'employmentInformation')
	    isValid = ValidateEmploymentInformation();
	else if (group == 'financialInformation')
	    isValid = ValidateFinancialInformation();
	else if (group == 'identityInformation')
	    isValid = ValidateIdentityInformation();
	else if (group == 'incomeInformation')
	    isValid = ValidateIncomeInformation();
	else if (group == 'residencyInformation')
	    isValid = ValidateResidencyInformation();
    else
    {
        isValid = ValidateGroup(group);
	    showMessage = true;
	}

	if(isValid)
	{
		MarkComplete( group, true );
		MoveToNext(group);
		$("div" + group + "Expand").style.display = "block";
		$("div" + group + "Close").style.display = "none";
	}
	else
	{
		MarkComplete( group, false );
		if (showMessage) alert( CUSTOMIZATION_ERR_REQD_MISSING );
	}
}

	
function UpdateCreditCardInfo_Begin(ccctrl)
{	
	UpdateCreditCardInfo( ccctrl.getJSON(), UpdateCreditCardInfo_End );
}
	
function UpdateCreditCardInfo_End( transport )
{
	
}

function ccControl(moID, yrID, stID, reID, reuseID, newID, reuse)
{
	this.monthID = moID;
	this.yearID = yrID;
	this.stateID = stID;
	this.ccTypeID = 'ddlCCType';
	this.firstNameID = 'txtCardholderFirst';
	this.lastNameID = 'txtCardholderLast';
	this.address1ID = 'txtCCAddress1';
	this.address2ID = 'txtCCAddress2';
	this.cityID = 'txtCCCity';
	this.zipID = 'txtCCZipCode';
	this.ccNumberID = 'txtCCNumber';
	this.cvvID = 'txtCCcvv';
	this.billingAddressChbxID = 'cbxBillingAddress';
	this.billingAddressID = 'billingAddress';
	this.relationshipID = reID;
	this.reuseCCDivID = reuseID;
	this.newCCDivID = newID;
	this.reuse = reuse;
	
	this.cleanup();
	
	this.inited = false;
}

ccControl.prototype.init = function()
{
	if(this.inited) return;
	
	this.month = $(this.monthID);
	this.year = $(this.yearID);
	this.state = $(this.stateID);
	this.cctype = $(this.ccTypeID);
	this.firstname = $(this.firstNameID);
	this.lastname = $(this.lastNameID);
	this.address1 = $(this.address1ID);
	this.address2 = $(this.address2ID);
	this.city = $(this.cityID);
	this.zip = $(this.zipID);
	this.number = $(this.ccNumberID);
	this.cvv = $(this.cvvID);
	this.billingAddressChbx = $(this.billingAddressChbxID);
	this.relationship = $(this.relationshipID);
	this.reuseCCDiv = $(this.reuseCCDivID);
	this.newCCDiv = $(this.newCCDivID);
	this.billingAddress = $(this.billingAddressID);
		
	Event.observe(window, 'unload', this.cleanup.bind(this));
	
	this.inited = true;
}


ccControl.prototype.cleanup = function()
{
	this.month = null;
	this.year = null;
	this.state = null;
	this.cctype = null;
	this.firstname = null;
	this.lastname = null;
	this.address1 = null;
	this.address2 = null;
	this.city = null;
	this.zip = null;
	this.number = null;
	this.cvv = null;
	this.billingAddressChbx = null;
	this.relationship = null;
	this.reuseCCDiv = null;
	this.newCCDiv = null;
}

ccControl.prototype.getJSON = function()
{
	this.init();
	
	var jsonObject = new Object();
	jsonObject.creditcardnumber = this.number.value;
	jsonObject.securitycode = (this.cvv)?this.cvv.value:'';
	jsonObject.expiration = (this.month.selectedIndex + 1) + '/01/' + this.year.options[ this.year.selectedIndex ].text;
	jsonObject.type = this.cctype.options[ this.cctype.selectedIndex ].text
	jsonObject.firstname = this.firstname.value;
	jsonObject.lastname = this.lastname.value;
	jsonObject.billingAddressChbx = this.billingAddressChbx.checked;
	jsonObject.address1 = this.address1.value;
	jsonObject.address2 = this.address2.value;
	jsonObject.city = this.city.value;
	var stateIdx = (this.state.selectedIndex>-1)?this.state.selectedIndex:1;
	jsonObject.state = this.state.options[ stateIdx ].text;
	jsonObject.zipcode = this.zip.value;
	jsonObject.relationship = this.relationship.value;
	
	return Object.toJSON(jsonObject)
}

ccControl.prototype.validate = function()
{
	this.init();
	
	if(this.reuse) return true;
	
	var today = new Date();
	var month = 0;
	var year = 0;
	
	if( this.cctype.selectedIndex == -1 )
	{
		alert( CRDT_CRD_ERR_TYPE );
		return false;
	}
	
	if( this.number.value == '' )
	{
		alert(CRDT_CRD_ERR_MISSING_NUMBER);
		return false;	
	}
	else if( !checkCreditCard( this.number.value, this.cctype.options[this.cctype.selectedIndex].text ) )
	{
		alert(CRDT_CRD_ERR_INVALID_NUMBER);
		return false;
	}
	
	if( this.month.selectedIndex == -1 )
	{
		alert(CRDT_CRD_ERR_EXP_MONTH);
		return false;
	}
	else
	{
		month = this.month.selectedIndex;
	}
	
	var cvvre = new RegExp("^\\d{3,4}$");
	if(this.cvv && this.cvv.value == '')
	{
		alert(CRDT_CRD_ERR_CVV);
		return false;
	}
	else if (this.cvv && !cvvre.test(this.cvv.value))
	{
	    alert(CRDT_CRD_ERR_CVV_INVALID);
		return false;
	}
	
	if( this.year.selectedIndex == -1 )
	{
		alert(CRDT_CRD_ERR_EXP_YEAR);
		return false;
	}
	else
	{
		year = this.year.options[this.year.selectedIndex].text;
		if( year < today.getFullYear() )
		{
			alert(CRDT_CRD_ERR_EXPIRED);
			return false;
		}
		else if(( year == today.getFullYear() ) && ( month <= today.getMonth() ))
		{
			alert(CRDT_CRD_ERR_EXPIRED);
			return false;
		}
	}
	
	if(( this.firstname.value == '' ) || ( this.lastname.value == '' ))
	{
		alert(CRDT_CRD_ERR_NAME);
		return false;
	}

	if( this.relationship && this.relationship.value == '' )
	{
	    alert(CRDT_CRD_ERR_RELATIONSHIP);
	    return false;
	}
	
	if (this.billingAddressChbx.checked == true)
	{
		return true;
	}
	
	if( (this.address1.value == '' ) || ( this.city.value == '' ) || ( this.state.selectedIndex == -1 ) || ( this.zip.value == '' ) )
	{
		alert(CRDT_CRD_ERR_ADDRESS);
		return false;
	}
	
	if( this.zip.value.length != 5 || isNaN(this.zip.value) )
	{
		alert(CRDT_CRD_ERR_ZIP);
		return false;
	}
	return true;
}

ccControl.prototype.CCValidate = function()
{
	if(this.validate())
	{
		$("billingCheckImage").style.display = "block";
		UpdateCreditCardInfo_Begin(this);
		MoveToNext("creditcard");
		$("divcreditcardExpand").style.display = "block";
		$("divcreditcardClose").style.display = "none";
	}
	else
	{
		$("billingCheckImage").style.display = "none";
	}

}

ccControl.prototype.clickBillingAddressChbx = function()
{
	this.init();
	if ( !this.billingAddressChbx.checked )
	{
		this.clearBillingAddress();
		this.billingAddress.style.display = "inline";
	} 
	else 
		this.billingAddress.style.display = "none";
}

ccControl.prototype.clearBillingAddress = function()
{
	this.init();

	this.address1.value = '';
	this.address2.value = '';
	this.city.value = '';
	this.zip.value = '';
	this.state.selectedIndex = -1;
}

ccControl.prototype.swapDiv =
function(reuse)
{
	this.init();
	
	this.reuse = reuse;
	this.reuseCCDiv.style.display = reuse?"":"none";
	this.newCCDiv.style.display = reuse?"none":"";
}
/*
function CheckDuplicateOrder_Begin(firstName, lastName, phone, phoneOptional, email)
{
	var callback = function(ajaxResponse) { CheckDuplicateOrder_Callback(ajaxResponse, firstName, lastName, phone, phoneOptional, email); }
    CheckDuplicateOrder(firstName, lastName, phone, phoneOptional, email, callback);
}
*/

ccControl.prototype.setCVV = 
function()
{
    this.init();
    
    var cvv_length = 3;
    
    if (this.cctype.options[ this.cctype.selectedIndex ].text == "American Express")
        cvv_length = 4;

    if (this.cvv.value.length > cvv_length)
        this.cvv.value = this.cvv.value.substr(0, cvv_length);
    
    this.cvv.maxLength = cvv_length;
}

function CheckDuplicateOrder_Begin(firstName, lastName, phone, phoneOptional, email, customerReferenceCode, actionToTake)
{
    var callback = function(ajaxResponse) 
    { 
	    CheckDuplicateOrder_Callback(ajaxResponse, firstName, lastName, phone, phoneOptional, email, customerReferenceCode, actionToTake); 
	}
    CheckDuplicateOrder(firstName, lastName, phone, phoneOptional, email, callback);
}
/*
function CheckDuplicateOrder_Callback(ajaxResponse, firstName, lastName, phone, phoneOptional, email)
{
    debug = true;
     if( ajaxResponse.Output == "ok" )
     {   
          SubmitOrder(firstName, lastName, phone, phoneOptional, email, SubmitOrder_Callback);
     }
     else
     {
          var str = PLACE_ORDER_DUP;
          str = str.replace("{0}", ajaxResponse.Output);
          var continueOrder = confirm(str);
          if( continueOrder == true )
          {
              SubmitOrder(firstName, lastName, phone, phoneOptional, email, SubmitOrder_Callback);     
          }
          else
          {
              lock(false);
          }
     }
}
*/


function CheckDuplicateOrder_Callback(ajaxResponse, firstName, lastName, phone, phoneOptional, email, customerReferenceCode, actionToTake)
{
     debug = true;
     
     if( ajaxResponse.Output == "ok" )
     {   
          if (actionToTake=="SubmitOrder")
          {
               // alert("CHDORDER_CB - SubmitOrder call  - reponse.ouutput == ok");
                SubmitOrder(firstName, lastName, phone, phoneOptional, email, customerReferenceCode, SubmitOrder_Callback);
          }
          else
          {
             if (actionToTake=="SaveOrder")
             {
                //alert("CHDORDER_CB - SaveOrder call - reponse.ouutput = ok");
                SaveOrder(firstName, lastName, phone, phoneOptional, email, SaveOrder_Callback);
             }
          }
     }
     else
     {
          var str = PLACE_ORDER_DUP;
          str = str.replace("{0}", ajaxResponse.Output);
          var continueOrder = confirm(str);
          if( continueOrder == true )
          {
              if (actionToTake=="SubmitOrder")
              {
                   // alert("CHDORDER_CB - SubmitOrder call  - reponse.ouutput = not ok");
                    SubmitOrder(firstName, lastName, phone, phoneOptional, email, customerReferenceCode, SubmitOrder_Callback);     
              }
              else
              { 
                    if  (actionToTake=="SaveOrder")
                    {
                      //  alert("CHDORDER_CB - SaveOrder call  - reponse.ouutput = not ok");
                        SaveOrder(firstName, lastName, phone, phoneOptional, email, SaveOrder_Callback);     
                    }
              }
          }
          else
          {
              lock(false);
          }
     }
}     

// COOKIE HELPERS
var transactionCookie = null;
function getTransactionCookie()
{
	if(!transactionCookie)
	{
		var cki = document.cookie.split(";");
		for(var i=0; i<cki.length; i++)
		{
			var idx = cki[i].indexOf("transaction=");
			if(idx == 0 || idx == 1) //check for idx 1 because IE7 seems to put a space in front
			{
				transactionCookie = cki[i];
				break;
			}
		}
	}

	return transactionCookie;	
}

function setOrderCompleteCookie()
{
	var cki = getTransactionCookie();
	if(cki)
		document.cookie = cki + "&orderComplete=1";
}

function isOrderComplete()
{
	var cki = getTransactionCookie();
	var c = cki.split("&");
	var vals;
	for(var i=0; i<c.length; i++)
	{
		var kvp = c[i].split("=");
		if(kvp[0] == "orderComplete")
			return (kvp[1] == "1");
	}
	
	return false;
}

function setAttachmentsComplete()
{
	var cki = getTransactionCookie();
	if(cki)
		document.cookie = cki + "&attachmentComplete=1";
}

function isAttachmentOrderComplete()
{
	var cki = getTransactionCookie();
	var c = cki.split("&");
	var vals;
	for(var i=0; i<c.length; i++)
	{
		var kvp = c[i].split("=");
		if(kvp[0] == "attachmentComplete")
			return (kvp[1] == "1");
	}
	
	return false;
}

function SubmitOrder_Callback(ajaxResponse)
{
	if(ajaxResponse.HasError)
	{
		alert(PLACE_ORDER_CANNOT_COMPLETE);
	}
	else
	{
		var aggregate = eval( "(" + ajaxResponse.Output + ")" );
		if( aggregate.Status == 1 )
		{
			setOrderCompleteCookie();
			location.href = "OrderConfirmation.aspx";
		}
		else
		{
			var result = null;
			var message = "";
			var i = 0;
			var len = aggregate.Results.length;
			for( i; i < len; i++ )
			{
				result = aggregate.Results[i];
				if( result.Status == 3 )
					message += "\n" + result.Message;
			}
			
			if( aggregate.Status == 2 )
			{
				alert(PLACE_ORDER_PARTIAL_DETAILS + message);
				location.href = "OrderConfirmation.aspx";
			}
			else
				alert(PLACE_ORDER_FAILURE_DETAILS + message);
		}
	}
	
	lock(false);

}

function SaveOrder_Callback(ajaxResponse)
{
	if(ajaxResponse.HasError)
	{
		alert(PLACE_ORDER_CANNOT_COMPLETE); 
	}
	else
	{
		var aggregate = eval( "(" + ajaxResponse.Output + ")" );
		if( aggregate.Status == 1 )
		{
                alert("The Order was saved");
		}
		else
		{
                alert("The order could not be saved");
		}
	}
	
	lock(false);

}

function RetrieveOrder_Callback(ajaxResponse)
{
	if(ajaxResponse.HasError)
	{
		alert(PLACE_ORDER_CANNOT_COMPLETE); 
	}
	else
	{
		var aggregate = eval( "(" + ajaxResponse.Output + ")" );
		if( aggregate.Status == 1 )
		{
                alert("The Order was retrieved");
		}
		else
		{
                alert("The order could not be retrieved");
		}
	}
	
	lock(false);
}


function TermsAndConditionsEvent(e)
{
     box = new Lightbox('AddressBox1')
     box.Left = 25;
     box.Height = 599;
     box.Width = 701;
     box.Modal = false;
     box.Shadow = false;
     box.Draggable = true;
     box.Content = "Details";
     box.Show();
     Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
     Event.observe( $('print_link'), 'click', PrintTermsEvent );
     
     ShowTermsAndConditions(Lightbox_Callback);
}

function PrintTermsEvent(event)
{
    box.Close();
    window.open('Print.aspx?type=terms');
}

function ShowBillingInfoEvent(event)
{	
	box = new Lightbox('BillingBox1')
    box.Left = 25;
    box.Height = 599;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Content = "Details";
    box.Show();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    Event.observe( $('print_link'), 'click', PrintBillingEvent );
    
	RenderBillingInfo(Lightbox_Callback);    
}

function PrintBillingEvent(event)
{
    box.Close();
	window.open('Print.aspx?type=billing');
}

function ShowCustomizations( customizationID )
{
    Expand(customizationID);
}

function HideCustomizations( customizationIDs )
{
    Collapse(customizationIDs)
}

Event.observe( window, 'load', OpenFirstCustomization );

function OpenFirstCustomization()
{
    if (customizationGroupToOpen != null) 
        ShowCustomizations('div' + customizationGroupToOpen);
}

///////////////////////////////////////////////OrderAttachmentsControl.ascx///////////////////////////////////////////////
function initAttachments()
{
	var orderComplete = isAttachmentOrderComplete();
	if(orderComplete)
	{
		var attachmentsDiv = $('OrderAttachments');
		if(attachmentsDiv)
			attachmentsDiv.hide();
	}
}

function declineAttachments()
{
	var attDiv = $('OrderAttachmentsDiv');
	attDiv.hide();
	
	setAttachmentsComplete();
}

function ViewOrderAttachments(selectedAttachments)
{
	selectedAttachments = selectedAttachments || "";
	RenderOrderAttachmentOffers(selectedAttachments, ViewOrderAttachmentsCallback);
}

function ViewOrderAttachmentsCallback(ajaxResponse)
{
	var div = $('OrderAttachmentContent');
	div.innerHTML = ajaxResponse.Output;
	
	var subhead = $('OrderAttachmentSubhead');
	subhead.innerHTML = ORDER_ATTACHMENTS_STEP1;
}

function ViewAttachmentOfferDetails(offerID)
{
	if( box != null )
		box.Close();
		
	chosenOfferID = offerID;
    box = new Lightbox('details1');
    box.Left = 25;
    box.Height = 597;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Content = "";
    box.Show();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    //Event.observe( $('print_link'), 'click', PrintDetailEvent );

	RenderAttachmentDetails(offerID, Lightbox_Callback);
}

function OrderAttachmentsConfirmSelection()
{
	var offersDiv = $('OrderAttachmentOffers');
	var chbx = offersDiv.getElementsByTagName("INPUT");
	var ids = [];
	for(var i=0; i<chbx.length; i++)
	{
		if(chbx[i].checked)
			ids.push(chbx[i].value);
	}
	
	if(ids.length == 0)
		alert(INVALID_SELECTION);
	else
	{
		var selectedIDs = ids.join(",");
		OrderAttachmentsSelect(selectedIDs, OrderAttachmentsConfirmSelection_callback);
	}
}

function OrderAttachmentsConfirmSelection_callback(ajaxResponse)
{
	var div = $('OrderAttachmentContent');
	div.innerHTML = ajaxResponse.Output;
	var ccctrlobj = $('ccctrlobj');
	if(ccctrlobj)
	{
		var ccparams = eval(ccctrlobj.value);
		window.cc = new ccControl(ccparams[0], ccparams[1], ccparams[2], ccparams[3], ccparams[4], ccparams[5], ccparams[6]);
		var ccdiv = document.getElementById("divcreditcard");
		if(ccdiv) ccdiv.style.display = "";
	}
	
	var subhead = $('OrderAttachmentSubhead');
	subhead.innerHTML = ORDER_ATTACHMENTS_STEP2;
	
	if(div.scrollIntoView)
		div.scrollIntoView(true);
}

function DoOrderAttachmentSubmit(selectedOfferIDs)
{
	var errDiv = $("orderAttachmentError");
	errDiv.style.display = "none";
	
	var termsDiv = $("OrderAttachmentBillingTerms");
	var termsAccepted = true;
	if(termsDiv)
	{
	
		var termsChbx = termsDiv.getElementsByTagName("INPUT");
		for(var i=0; i<termsChbx.length; i++)
		{
			if(termsChbx[i].type == "checkbox")
			{
				termsAccepted = termsAccepted && termsChbx[i].checked; 
			}
		}
	}
	
	if(!termsAccepted)
	{
		alert(TERMS_ACCEPT_ERR);
		return;
	}

	var ccparam = "";
	if(window["cc"])
	{
		if(cc.validate())
		{
			if(!cc.reuse)
				ccparam = cc.getJSON();
		}
		else
			return false;
	}	
	else
	{
		ccparam = "";
	}
	
	var btn = $("orderAttachmentSubmit");
	btn.disabled = true;
	
	OrderAttachmentSubmit(ccparam, selectedOfferIDs, DoOrderAttachmentSubmit_Callback);	

}

function DoOrderAttachmentSubmit_Callback(ajaxResponse)
{
	//TODO: Error checking
	var result;
	if(ajaxResponse.Output)
		result = eval("(" + ajaxResponse.Output + ")");
	else
		result = { Status: 3, Message: "Unfortunately your content subscription could not be processed." };
		
	if(result.Status == 3) //failure
	{
		var message = result.Message;
		var errDiv = $("orderAttachmentError");
		errDiv.innerHTML = message;
		errDiv.style.display = "";
		alert(message);
		
		var btn = $("orderAttachmentSubmit");
		btn.disabled = false;
	}
	else
	{
		var div = $('OrderAttachmentBillingDiv');
		div.innerHTML = "<b>" + result.Message + "</b>";
	
		setAttachmentsComplete();
		var subhead = $('OrderAttachmentSubhead');
		subhead.style.display = "none";
	}
}

/*
function GetCCControl()
{
	RenderCreditCardControl(GetCCControl_callback);
}


function GetCCControl_callback(ajaxResponse)
{
	var billingDiv = $("orderAttachmentBilling");
	billingDiv.innerHTML = ajaxResponse.Output;
	
		var ccctrlobj = $('ccctrlobj');
	if(ccctrlobj)
	{
		var ccparams = eval(ccctrlobj.value);
		window.cc = new ccControl(ccparams[0], ccparams[1], ccparams[2]);
	}
}
*/

function AttachmentTerms(offerID)
{
	if( box != null )
		box.Close();
		
	chosenOfferID = offerID;
    box = new Lightbox('details1');
    box.Left = 25;
    box.Height = 597;
    box.Width = 701;
    box.Modal = false;
    box.Shadow = false;
    box.Draggable = true;
    box.Show();
    Event.observe( $(box.CloseRef()), 'click', CloseLightbox );
    Event.observe( $('print_link'), 'click', PrintDetailEvent );

	RenderAttachmentTerms(offerID, Lightbox_Callback);
}

function C2CHack()
{
      var lnk = [];
      lnk.push($$("a[href='http://as00.estara.com/ep/?ulbid=441639']")); // Comcast
      lnk.push($$("a[href='http://as00.estara.com/ep/?ulbid=440973']")); // Cablevision
      lnk.push($$("a[href='http://as00.estara.com/ep/?ulbid=441669']")); // Insight
      lnk.push($$("a[href='http://as00.estara.com/ep/?ulbid=441589']")); // Charter
      lnk.push($$("a[href='http://as00.estara.com/ep/?ulbid=441679']")); // Time Warner
    

      lnk = lnk.flatten();
      for(var i=0; i<lnk.length; i++)

      {
            lnk[i].innerHTML = "CLICK HERE TO SCHEDULE YOUR INSTALLATION";
      }
}
 

if(location.href.toLowerCase().indexOf("orderconfirmation.aspx") != -1)
      Event.observe(window, "load", C2CHack);
