

/*
 *  Manage display of area option preview & selector
 *
 */
 
    var quotes_panel;
    var optionLinks, optionDescriptions;
    var tips_n_quotes_responder ='/ajax/tips_n_quotes_responder.html';
    var editor_rows = 10;    
    
    
    OptionLinksInit = function() {
        optionLinks = Dom.getElementsByClassName('pa-OptionLinks')[0].getElementsByTagName('li');
        optionDescriptions = Dom.getElementsByClassName('pa-OptionDescription');
        
        Event.addListener(optionLinks, 'click', function() { OptionSelected(this); });
        Event.addListener(Dom.getElementsByClassName('pa-OptionClose'), 'click', function() { ResetOptions(); });
        for (i=0; i < optionLinks.length; i++) {
            if (optionLinks[i].className == 'selected') {
                OptionSelected(optionLinks[i]);
            }
        }
    }
    
    OptionSelected = function(el) {
        for (i=0; i < optionLinks.length; i++) {
            Dom.removeClass(optionLinks[i], 'selected');
            
            if (i < optionDescriptions.length) {
                Dom.setStyle(optionDescriptions[i], 'display', 'none');
                if (el == optionLinks[i])
                    Dom.setStyle(optionDescriptions[i], 'display', 'block');
            }
            
        }
        Dom.addClass(el, 'selected');
    }
    
    ResetOptions = function() {
        Dom.removeClass(optionLinks, 'selected');
        Dom.setStyle(optionDescriptions, 'display', 'none');
    }


    executeBeforeOnLoad = function() {
        InitPanel();
        InitDataTable();
        Dom.setStyle('quotes_panel', 'display', 'none');  //fixes YUI collapse border bug
    }
    
    
    InitPanel = function() {
        quotes_panel = new YAHOO.widget.SimpleDialog("quotes_panel", 
		{ 
			close:false,  
			visible:false,  
			draggable:false,
			underlay: null,
			modal:true
		});
		
		quotes_panel.render();
		quotes_panel.center();
		
		Dom.setStyle(quotes_panel.element, "visibility", "hidden");  /* fixes IE border lines showing through */
    }
    
    
    InitDataTable = function() {
        this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get('tblQuotes'));
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;   
        this.myDataSource.responseSchema = schema;

        // Pass in an empty config object for progressively enhanced table, due to known issue   
        this.quotesTable = new YAHOO.widget.DataTable('quotesContainer', myColumnDefs, this.myDataSource, { paginated:true, paginator: {rowsPerPage: editor_rows} });
        
        
   	    // Set up editing flow 
        this.highlightEditableCell = function(oArgs) { 
            var elCell = oArgs.target;  
            if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) { 
                this.highlightCell(elCell);
            } 
        }; 
        
        
        this.quotesTable.subscribe("cellClickEvent", this.quotesTable.onEventShowCellEditor);
        this.quotesTable.subscribe("cellMouseoverEvent", this.highlightEditableCell);
        this.quotesTable.subscribe("cellMouseoutEvent", this.quotesTable.onEventUnhighlightCell);


        // Hook into custom event to customize save-flow of "radio" editor 
        this.quotesTable.subscribe("editorUpdateEvent", function(oArgs) { 
            if(oArgs.editor.column.key === "active") { 
                this.saveCellEditor(); 
            } 
        }); 
        this.quotesTable.subscribe("editorBlurEvent", function(oArgs) { 
            this.cancelCellEditor(); 
        });
    }
    
    ViewEditQuotes = function() {
        Dom.setStyle('quotes_panel', 'display', 'block');
        quotes_panel.show();
    }

    var RequestThis;            // Place to save 'this' value for use upon returning from Ajax call
    YAHOO.widget.DataTable.prototype.doBeforeShowCellEditor = function(oCellEditor) {
        tq_hide_heading_controls();         // hide heading editor when editing tips/quotes

        document.getElementById('yui-dt0-celleditor').style.background="white";
        
        var spinner = Dom.getElementsByClassName('yui-dt-button')[0].appendChild(document.createElement("span"));
        spinner.id = 'validation_spinner';
    };
    
    YAHOO.widget.DataTable.prototype.saveCellEditor = function() {
        if(!this._oCellEditor.isActive) {
            return;     // not active?? we should not be here
        }
        var key     = this._oCellEditor.column.key;
        var newData = this._oCellEditor.value;
        var oldData = this._oCellEditor.record.getData(key);
        var id      = this._oCellEditor.record._oData.id;
        if (newData == oldData) {       // data has not changed
            this.resetCellEditor();     // do not need to do anything
            return;
        }
        
        //
        //  Goto the server to validate the user input
        //
        RequestThis = this;
        document.getElementById('validation_spinner').style.visibility = 'visible';
        new Ajax.Request(tips_n_quotes_responder,
        {
            method:'post',
            parameters: {
                id  : id,
                data: newData,
                type: key
            },
            onSuccess: function(transport) {
                var response = transport.responseText;
                
                if (response.substr(0,2) == 'ok') {
                    if (response.substr(3)) {
                        newData = response.substr(3);
                    }

                    // Update the Record
                    RequestThis._oRecordSet.updateKey(RequestThis._oCellEditor.record, RequestThis._oCellEditor.column.key, newData);
                    // Update the UI
                    RequestThis.formatCell(RequestThis._oCellEditor.cell);
                    // Clear out the Cell Editor
                    RequestThis.resetCellEditor();
                    RequestThis.fireEvent("editorSaveEvent", {editor:RequestThis._oCellEditor, oldData:oldData, newData:newData});
                }
                else {
                    // an error of some kind, inform the user
                    var msgbox = document.getElementById('yui-dt0-celleditor').appendChild(document.createElement("div"));

                    msgbox.id = 'validation_msgbox';
                    msgbox.innerHTML = response;

                    document.getElementById('validation_spinner').style.visibility = 'hidden';
                    document.getElementById('yui-dt0-celleditor').style.background = 'salmon';
                }
            },
            onFailure: ajax_failure
        });

    };


    function open_logo_library(area, option) {
        var html   = '<div id="LogoSelector"></div>';
        var width  = 680;
        var height = 420;

        openLightBox(html,width,height, 0, 1);
        ahah('/your_order/SectionHandlers/LogoLibrary?area='+area+'&option='+option,'LogoSelector');
    }

    function new_page(loc, area) {
        var page_ref=loc.selectedIndex;
        if (loc.options[page_ref].value != "none") {
            ahah('/your_order/logo_library/index.html?mode=show_cat&category='+loc.options[page_ref].value+"&area="+area, 'image_list');
            ahah('/your_order/logo_library/index.html?mode=start_img&area='+area, 'image_preview');
        }
    }
    
    function insert_logo (area, logo) {
        new Ajax.Request('/ajax/logo_library_responder.html',
        {
            method:'post',
            parameters: {
                insert_logo : logo,
                area        : area
            },
            onSuccess: function(transport){
                var response = transport.responseText;

                if (response == 'ok') {
                    current_panel.hide();
                    var url = document.location.href;
                        url = url.replace('#','');
                    
                    document.location.href = url;
                }
                else {
                    alert(response);
                }
            },
            onFailure: ajax_failure
        });
    }
    
    function delete_logo (area, delete_logo, logo) {
        var params;
        
        if (delete_logo == 'delete_logo') {      // logo from logo library
            params = {
                delete_logo    : logo ,
                with_id_format : 1 ,            
                area           : area
            };
        }
        else {              // deleting an image
            params = {
                'delete'       : logo ,
                with_id_format : 1 ,            
                area           : area
            };
        }
        
        new Ajax.Request('/ajax/logo_library_responder.html',
        {
            method:'post',
            parameters: params,
            onSuccess: function(transport){
                var response = transport.responseText;

                if (response == 'ok') {
                    var url = document.location.href;
                        url = url.replace(/\?.*/,'');
                    
                    document.location.href = url;
                }
                else {
                    alert(response);
                }
            },
            onFailure: ajax_failure
        });
    }
    
    
/*
 * ahah with some prototype sugar
 */
    function ahah(url, target, callback) {
        new Ajax.Request(url ,
        {
            method:'get',
            parameters: {},
            onSuccess: function(transport){
                if (document.getElementById(target)) {
                    document.getElementById(target).innerHTML = transport.responseText;
                }
                execJS2(transport.responseText);
                buttonStyles2();
                if (callback && (callback != 'undefined')) {
                    try {
                        callback();
                    }
                    catch (e) {
                        alert(e);
                    }
                }
            },
            onFailure: ajax_failure
        });
    } 

    function ajax_failure() {
    	alert("There was a transmission error with your request.\nPlease try again.");
    }
    
    /*
     * from: http://microformats.org/wiki/rest/ahah
     */
    var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
    var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
    var bMoz = (navigator.appName == 'Netscape');
    function execJS(node) { //DOESN'T WORK IN IE!!
      var st = node.getElementsByTagName('script');
      var strExec;
      for(var i=0;i<st.length; i++) {     
        if (bSaf) {
          strExec = st[i].innerHTML;
        }
        else if (bOpera) {
          strExec = st[i].text;
        }
        else if (bMoz) {
          strExec = st[i].textContent;
        }
        else {
          strExec = st[i].text;
        }
        try {
          eval(strExec.split("<!--").join("").split("-->").join(""));
        } catch(e) {
          alert(e);
        }
      }
    }
    function execJS2(val) { // run the first <script> block we encounter
        try {
        	var val2 = val.split(/<[\/]{0,1}script[^>]{0,}>/);
        	if (val2 && val2.length > 1 && val2[1]) {
            eval(val2[1].split("<!--").join("").split("-->").join(""));
          }
        } catch(e) {
          alert(e);
        }    	
    }
    
    
/*
 *
 *
 */
    function Handbook_Instructions (action, content) {
        
        if (action == 'save') {
            document.getElementById('hb_message').innerHTML = '';
            var postData = 'mode=instructions&action=save&instructions='+escape(content);

            var CallBackHandler = {
                success: function(response) {
                    document.getElementById('hb_message').innerHTML = response.responseText;
                },
                failure: function(response) {
                    document.getElementById('hb_message').innerHTML = 'An error occurred saving the instructions.';
                }
            };

            YAHOO.util.Connect.asyncRequest('POST', '/ajax/handbook_submission_responder.html', CallBackHandler, postData);
            
        }
        else {
            var html   = '<div id="HandbookInstructions"></div>';
            var width  = 500;
            var height = 350;

            openLightBox(html,width,height, 1, 1);
            ahah('/ajax/handbook_submission_responder.html?mode=instructions', 'HandbookInstructions');
        }
    }
    
/*
 *  there are four ways for Premier to recive Handbook materials
 *      provide the interface for each of them
 */
    function HandbookSubmission( method ) {
    
        var html   = '<div id="HandbookSubmission_interface"></div>';
        var width  = 800;
        var height = 525;

        openLightBox(html,width,height, 1, 1);
        ahah('/ajax/handbook_submission_responder.html?mode=init&method='+method, 'HandbookSubmission_interface');
}
    
/*
 *  Set the Handbook Submission method
 */    
    function Handbook_set_method (method) {
        ahah('/ajax/handbook_submission_responder.html?mode=set&method='+method, 'HandbookSubmission_response');
    }
    
/*
 *  Set the Handbook Submission method
 */    
    function Handbook_set_confirm (method) {
        document.confirm_form.confirm_button.disabled = true;
        ahah('/ajax/handbook_submission_responder.html?mode=set_confirm&method='+method, 'HandbookSubmission_response');
    }

/*
 *  Set that the user has mailed a QAS copy 
 */    
    function Handbook_set_qas (method) {
        document.confirm_form.confirm_button.disabled = true;
        ahah('/ajax/handbook_submission_responder.html?mode=set_qas&method='+method, 'HandbookSubmission_response');
    }

/*
 *  Confirm a Handbook file has been received
 */    
    function Handbook_confirm_method (method) {
        ahah('/ajax/handbook_submission_responder.html?mode=confirm&method='+method, 'HandbookSubmission_response');
    }

/*
 *  Delete an uploaded Handbook file
 */    
    function Handbook_filedelete (method) {
        var fileIndex = document.getElementById("file_selector").selectedIndex;
        var fileid    = document.getElementById("file_selector").options[fileIndex].value;
        
        ahah('/ajax/handbook_submission_responder.html?mode=delete&method='+method+'&delete_file='+escape(fileid), 'HB_delete_response');
        Handbook_confirm_method(method);
        document.getElementById('HB_upload_response').innerHTML = '';
        Handbook_filelist(method);
    }

/*
 *  Obtain list of uploaded files  
 */    
    function Handbook_filelist (method) {
        ahah('/ajax/handbook_submission_responder.html?mode=filelist&method='+method, 'HB_filelist');
    }

/*
 *  set the specified Handbook file format
 */    
    function HB_set_fileformat (method, format) {
        var button = document.ulform.HB_file_format;

        for(var j = 0; j < button.length; j++) {
            if (button[j].value == format) {
                button[j].checked = true;
            }
    	}
        ahah('/ajax/handbook_submission_responder.html?mode=set&method='+method+'&format='+format, '');
    }

    
    function setAndEnableConfirm(){
    	var pageCount = document.getElementById("handbook_pages_supplied").value;
    	document.getElementById("confirm_button").disabled = false;
    	Handbook_set_supplied_pages(pageCount);
    }


/*
 *
 */
    function Handbook_set_supplied_pages (pages) {
        ahah('/ajax/handbook_submission_responder.html?mode=set_supplied_pages&pages='+pages, 'HB_supplied_pages_msg');
    }

/*
 *  upload a file
 */
    function Handbook_fileupload (method) {
        
        Handbook_set_method(method);
        document.getElementById('HB_delete_response').innerHTML = '';
        
        YAHOO.util.Connect.setForm('ulform', true);
        var uploadHandler = {
            upload: function(response) {
                document.getElementById('HB_upload_response').innerHTML = response.responseText;
                
                Handbook_confirm_method(method);
                Handbook_filelist(method);
            }
        };
        
        YAHOO.util.Connect.asyncRequest('POST', '/cgi-bin/C2/upload_hb.cgi', uploadHandler);
    }

/*
 *  Display an interface for downloading handbook templates
 *
 *  using an iframe so the <script> tags are handled properly
 */    
    function HandbookTemplates( url ) {

        var html   = '<div id="HandbookTemplate_interface"><iframe id="HB_Templates" src="'+url+'"></iframe></div>';
        var width  = 400;
        var height = 325;

        openLightBox(html,width,height, 0, 1);
    }

/*
 *  Display the Handbook margin sizing guide
 *
 */    
    function HB_SizeGuide ( guide ) {
        var html   = '<div id="HandbookTemplate_SizeGuide">'+guide+'</div>';
        var width  = 750;
        var height = 570;

        openLightBox(html,width,height, 0, 1);
    }

/*
 *  based on buttonStyles from global.js
 *      needed for ajax loaded content so don't restyle already styled elements
 */    
    function buttonize(node) {
        var els = node.getElementsByClassName('pa-Button');

        for (i=0; i < els.length; i++) {
        	if (!els[i].innerHTML.match(/<span/i)) {
            	if (!els[i].innerHTML.match(/<span/i)) {
                    els[i].innerHTML = "<span class='res-span'>" + els[i].innerHTML + "</span>";
                }
            }
        }
    }
    
		function buttonStyles2() {
		    var els = Dom.getElementsByClassName('pa-Button');
		    for (i=0; i < els.length; i++) {
            	if (!els[i].innerHTML.match(/<span/i)) {
                	if (!els[i].innerHTML.match(/<span/i)) {
                        els[i].innerHTML = "<span class='res-span'>" + els[i].innerHTML + "</span>";
                    }
                }
		    }
		}
		
/*
 *  Step forward/backward & directly through a click-trail
 */
    var CurrentStep = 0;
    var MaxStep     = 0;
    
    function Step(number) {
        if (number.match(/^[-+]/)) {
            CurrentStep = CurrentStep + parseInt(number);
        }
        else {
            CurrentStep = parseInt(number);
        }
        
        document.getElementById('previous').style.display = 'block';            
        document.getElementById('previous').style.visibility = 'visible';  
        document.getElementById('next').style.display = 'block';
        document.getElementById('next').style.visibility = 'visible';
        if (CurrentStep <= 1) {
            CurrentStep = 1;
            document.getElementById('previous').style.display = 'none';
            document.getElementById('previous').style.visibility = 'hidden';
        }
        if (CurrentStep >= MaxStep) {
            CurrentStep = MaxStep;
            document.getElementById('next').style.display = 'none';
            document.getElementById('next').style.visibility = 'hidden';
        }
        
        for (j = 1; j<= MaxStep; j++) {
            document.getElementById('Step'+j).style.display = 'none';
            document.getElementById('Step'+j).style.visibility = 'hidden';
            document.getElementById('Trail'+j).className = '';
        }
        document.getElementById('Step'+CurrentStep).style.display = 'block';
        document.getElementById('Step'+CurrentStep).style.visibility = 'visible';
        document.getElementById('Trail'+CurrentStep).className = 'selected';
    }

/*
 *  Display PartTwo for option editing
 */
    var list = false;
    var optionsHeight = 0;
    var dialogHeight  = 0;
    function TogglePartTwo () {
        list = !list;
        var options = document.getElementById('PartTwo_list');
        var dialog  = document.getElementById('PartTwo_interface');
        var toggle  = document.getElementById('Selection_Toggle');
        var status  = document.getElementById('PartThree');
        
        if (list) {
            options.style.display   = 'none';
            options.style.visibility = 'hidden';
            dialog.style.visibility = 'visible';
            dialog.style.display    = 'block';
            status.style.display    = 'block';
            status.style.visibility = 'visible';
            toggle.innerHTML        = 'Change Option';
        }
        else {
            options.style.display   = 'block';
            options.style.visibility = 'visible';
            dialog.style.visibility = 'hidden';
            dialog.style.display    = 'none';
            status.style.display    = 'none';
            status.style.visibility = 'hidden';
            toggle.innerHTML        = 'Reselect Option';
        }

        return;        
        
        /* failed animation attempt */
        var $D      = YAHOO.util.Dom;
        var options = $D.get('PartTwo_list');
        var dialog  = $D.get('PartTwo_interface');
        var anim1;
        var anim2;
        
        if (options.scrollHeight > optionsHeight) {
            optionsHeight = options.scrollHeight;
        }
        if (dialog.scrollHeight > dialogHeight) {
            dialogHeight = dialog.scrollHeight;
        }
    
        if (list) {
            anim1 = new YAHOO.util.Anim(options,{ height: { to: optionsHeight } }, 0.3, YAHOO.util.Easing.easeInStrong);
            anim2 = new YAHOO.util.Anim(dialog, { height: { to: 0 } }, 0.3, YAHOO.util.Easing.easeInStrong);
        }
        else {
            anim1 = new YAHOO.util.Anim(dialog, { height: { to: dialogHeight } }, 0.3, YAHOO.util.Easing.easeInStrong);
            anim2 = new YAHOO.util.Anim(options,{ height: { to: 0 } }, 0.3, YAHOO.util.Easing.easeInStrong);
        }
        anim1.animate();
        anim2.animate();
    }
 

/*
 *
 */
    function openWindow(url, name, width, height) {
        var Width = width;
        var Height = height;
        var Left = parseInt((screen.availWidth/2) - (Width/2));
        var Top = parseInt((screen.availHeight/2) - (Height/2));
        var windowFeatures = " resizable=yes, scrollbars=yes, width=" + width + ",height=" + height +
           ", status=no, left=" + Left + ",top=" + Top +
           "screenX=" + Left + ",screenY=" + Top;

        var child_window = window.open(url, name, windowFeatures);
        child_window.resizeTo(width + 20, height + 20);
        child_window.focus();
    }


/*
 *  display the handbook template selector
 */
    function HB_Template() {
        var html   = '<div id="HandbookTemplate_selection"></div>';
        var width  = 300;
        var height = 300;

        openLightBox(html,width,height, 0, 1);
        ahah('/ajax/handbook_submission_responder.html?mode=template', 'HandbookTemplate_selection');
    }

/*
 *  display the input controls for the Tips and Quotes heading editor
 */
    var save_instance;
    function tq_show_heading_controls (instance) {
        if (! document.getElementById('tq_heading_controls'+instance)) {
            return;
        }
        
        if (save_instance) {
            tq_hide_heading_controls(save_instance);
        }
        
        save_instance = instance;
        document.getElementById('tq_heading_controls'+instance).style.display='inline';
        Dom.addClass(document.getElementById('tq_heading'+instance), 'focus');
    }

/*
 *  hide the Tips and Quotes editor controls
 */
    function tq_hide_heading_controls(instance) {
        if (! document.getElementById('tq_heading_controls'+instance)) {
            return;
        }
        save_instance = '';
        
        document.getElementById('tq_heading_controls'+instance).style.display='none';
        Dom.removeClass(document.getElementById('tq_heading'+instance), 'focus');
        
        document.getElementById('heading_msgbox'+instance).innerHTML = '';
        document.getElementById('heading_msgbox'+instance).style.visibility = 'hidden';
        
        document.getElementById('tq_heading_container'+instance).style.background = 'white';
        document.getElementById('tq_heading'+instance).value = document.getElementById('tq_old_heading'+instance).value;
    }

/*
 *  save the new Tips and Quotes heading value
 */
    function tq_save_heading(instance) {
        var newData = document.getElementById('tq_heading'+instance).value;
        var oldData = document.getElementById('tq_old_heading'+instance).value;
        var id      = document.getElementById('tq_heading_id'+instance).value;
        var type    = document.getElementById('tq_heading_type'+instance).value;
        if (newData == oldData) {           // data has not changed
            tq_hide_heading_controls(instance);     // do not need to do anything
            return;
        }
        
        //
        //  Goto the server to validate the user input
        //
        document.getElementById('heading_spinner'+instance).style.visibility = 'visible';
        new Ajax.Request(tips_n_quotes_responder,
        {
            method:'post',
            parameters: {
                id  : id,
                data: newData,
                type: type
            },
            onSuccess: function(transport) {
                var response = transport.responseText;

                document.getElementById('heading_spinner'+save_instance).style.visibility = 'hidden';
                
                if (response.substr(0,2) == 'ok') {             // Update the old copy & hide controls
                    document.getElementById('heading_msgbox'+save_instance).innerHTML = '';
                    document.getElementById('heading_msgbox'+save_instance).style.visibility = 'hidden';
                    document.getElementById('tq_heading_container'+save_instance).style.background = 'white';
                    
                    if (response.substr(3)) {
                        document.getElementById('tq_heading'+save_instance).value = response.substr(3);
                    }
                    
                    document.getElementById('tq_old_heading'+save_instance).value = document.getElementById('tq_heading'+save_instance).value;
                    tq_hide_heading_controls(save_instance);
                }
                else {                              // an error of some kind, inform the user
                    document.getElementById('heading_msgbox'+save_instance).innerHTML = response;
                    document.getElementById('heading_msgbox'+save_instance).style.visibility = 'visible';

                    document.getElementById('tq_heading_container'+save_instance).style.background = 'salmon';
                }
            },
            onFailure: ajax_failure
        });
    }

    function toggleBox(szDivID, iState) // 1 visible, 0 hidden
    {
        if(document.layers)	   //NN4+
        {
           document.layers[szDivID].visibility = iState ? "show" : "hide";
        }
        else if(document.getElementById)	  //gecko(NN6) + IE 5+
        {
            var obj = document.getElementById(szDivID);
            obj.style.visibility = iState ? "visible" : "hidden";
        }
        else if(document.all)	// IE 4
        {
            document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
        }
    }





