var myquote;
var caltd;
var calfdt;

function initialize_quote()
{    
    ajax_loading();
    
    new Ajax.Autocompleter("new_distributor", "autocomplete_choices", "typeahead.php", 
        {paramName: "value", minChars: 1, parameters: "type=users", afterUpdateElement: function(txt,li) {
        $('new_distributor_hidden').value=li.id;
     }});
     
    new Ajax.Autocompleter("new_contractor", "autocomplete_choices", "typeahead.php", 
        {paramName: "value", minChars: 1, parameters: "type=users", afterUpdateElement: function(txt,li) {
        $('new_contractor_hidden').value=li.id;
    }});
     
    new Ajax.Autocompleter("new_user_cc", "autocomplete_choices", "typeahead.php", 
        {paramName: "value", minChars: 1, parameters: "type=users", afterUpdateElement: function(txt,li) {
        $('new_user_cc_hidden').value=li.id;
    }});    

    new Tooltip("pdf_ctrl", {mouseFollow: false});
    new Tooltip("show_email", {mouseFollow: false});
    //new Tooltip("email_drawings_ctrl", {mouseFollow: false});
    new Tooltip("customer_notes_tt", {mouseFollow: false});
    
    cdi_typeahead("old_model","model",1);
    cdi_typeahead("new_model","model",1);
    cdi_typeahead("old_part","part",1);
    cdi_typeahead("new_part","part",1);
    
    caltd = new calendar2($('scheduled_ship'));
    caltd.year_scroll = true;
    caltd.time_comp = false;
    
    calfdt = new calendar2($('freight_datetime'));
    calfdt.year_scroll = true;
    calfdt.time_comp = true;
            
    myquote = new quote();
   
    if($F('load_quote_id') != "0")
    {
        myquote.unsaved = false;        
        myquote.load_quote($F('load_quote_id'));
    }
    else if($F('admin') == 1)
        myquote.show_customer_wnd();
    else
        $('customer_step1_wnd').show();
    
}

function php_post_ar(/*name,a,keys_only*/)
{    
    if(arguments.length < 2)
        return "need at least 2 arguments";
    var name = arguments[0];    
    var old_a = $H(arguments[1]);
    var new_a = $H();
    var keys = (arguments.length == 3) ? arguments[2] : old_a.keys();    
    keys.each(function(k) {       
        var val = old_a.get(k);
        if(val != undefined)          
            new_a.set(name + "[" + k + "]",old_a.get(k));
    });
    return new_a.toObject();
}

on_load_init.push(initialize_quote);

var order_url = "";
function order_redirect()
{
    window.location = order_url;
}

// headers
var curb_TH = "<tr><th>Line</th><th>Qty</th><th>Description</th></tr>";
var price_TH = "<tr><th>Manufacturing Time</th><th>5 Day</th><th>4 Day</th><th>3 Day</th><th>Tomorrow</th><th>Today</th></tr>";
var shipdate_TH = new Template("<tr><td><b>When will it ship?</b></td><td>#{five_day}</td><td>#{four_day}</td><td>#{three_day}</td><td>#{two_day}</td><td>#{one_day}</td></tr>");
var price_TH_iso = "<tr><th>Manufacturing Time</th><th colspan='5' colspan='5' style='text-align: center' >2 Weeks</th></tr>";
// rows
var d_template = new Template("<br><a target='_new' href='cdi_download.php?cdi_file_id=#{cdi_file_id}'>#{title}</a>");
var c_template = new Template("<tr align='center'><th>#{line}</th><th>#{qty}</th><th><a target='_new' href='curb_admin.php?curb_id=#{curb_id}'>#{nomenclature}</a> #{tag}</th></tr><tr align='center'><td colspan=2 width=64 valign='top' id='curb_row#{i}' >#{buttons}</td><td>#{desc}</td></tr>");
var p_template = new Template("<tr class='#{cname}' ><td>#{nomenclature}</td><td>#{five_day}</td><td>#{four_day}</td><td>#{three_day}</td><td>#{two_day}</td><td>#{one_day}</td></tr>");
var pcat_template = new Template("<tr><td>#{nomenclature}</td><td colspan='5' style='text-align: center'  >#{catalog_num}</td></tr>");
var piso_template = new Template("<tr class='#{cname}' ><td>#{nomenclature}</td><td colspan='5' style='text-align: center'  >#{ten_day}</td></tr>");

var cbut_template = new Template("<img name='#{action}' title='#{title}' src='images\/curb_#{action}.png' class='curb_button' >"); 

//<img name='edit' src='images\/item.gif' id='edit_curb#{i}' title='Edit Curb' style='cursor: pointer'></td><td><img src='images\/delete.gif' id='dele_curb#{i}' name='del' title='Delete Curb' style='cursor: pointer'>

var shipday=new Array(7);
shipday[0]="Monday";
shipday[1]="Monday";
shipday[2]="Tuesday";
shipday[3]="Wednesday";
shipday[4]="Thursday";
shipday[5]="Friday";
shipday[6]="Monday";
shipday[7]="Tuesday";
shipday[8]="Wednesday";
shipday[9]="Thursday";
shipday[10]="Friday";


var quote = Class.create({ 
    
    initialize: function() {        
        this.ax_url = "quote_ajax.php";
        this.ax_upload = false;
        this.i_ax_upload = false;
        this.my_data = { quote_id : 0, distributor_id: 0, admin: false, quote_curbs: [] };   
        
        // filter keys for php array. see post_data 
        this.c_keys = ['curb_id','curb_type_id','qty','old_model_id','new_model_id','side_type_id','pitch_id','base_height', 
            'price_override','width_ft', 'width_inch_id', 'length_ft', 'length_inch_id', 
            'spacing','diameter','frame','quote_curb_id','tag','curb_estimate_id','cdi_part_id_old','cdi_part_id_new','old_model','new_model']; 
        this.edit_curb_id = -1;          
        this.badd_more = false;
        this.unsaved = false;
        this.frm_observer = false;
        var panes = $('curb_wnd','quote_buttons','place_order','cancel_order','estimator_buttons','extra_row','email_wnd','customer_step1','customer_step2','model_finder_wnd');
        
        for (var i=0, il=panes.length; i<il; i++)        
            panes[i].observe('click', this.on_click.bindAsEventListener(this)); 
        $('curb_table').observe('click', this.on_click_curb.bindAsEventListener(this));
        $('model_list').observe('click', this.on_model_click.bindAsEventListener(this));
        
        $('ship_day').observe('change', this.on_ship_day.bindAsEventListener(this));
        $('user_address_id').observe('change', this.on_address.bindAsEventListener(this));
        $('mbrand_id').observe('change', this.on_mbrand.bindAsEventListener(this));
        
        if($F('admin') == 1) {
            this.my_data.admin = true;
            var panes = $('dist_pane','cont_pane','cc_pane','set_customers_pane','internal_files','ifile_wnd','customd_wnd','edit_ordered_quote');
            for (var i=0, il=panes.length; i<il; i++)        
                panes[i].observe('click', this.on_click.bindAsEventListener(this));            
        } else {
            this.my_data.distributor_id = $F('distributor_id');
            this.my_data.contractor_id = $F('contractor_id');
        }
        this.validate_ctrl();
        this.estimator = false;        
        this.valid_total = false;        
    },
    
    load_quote: function(quote_id) {
        this.unsaved = false;
        this.post_ajax({'quote_id': quote_id, m: 'to_json' });
    },
    
    post_ajax: function(params) {        
        new Ajax.Request(this.ax_url, {         
            method:'post',            
            onComplete: this.on_ajax_complete.bind(this),
            parameters: params
        });  
    },
       
    get_details_ar: function() {
        var params = $('quote_form').serialize(true);
        params.distributor_id = this.my_data.distributor_id;
        params.contractor_id = this.my_data.contractor_id;
        params.user_cc_id = this.my_data.user_cc_id;
        params.quote_id = this.my_data.quote_id;
        if(this.my_data.admin)
            params.customer_notes = this.my_data.customer_notes;
        else 
            params.notes = this.my_data.notes;
        return params; 
    },    
        
    post_details: function(rt) {
        var params = this.get_details_ar();
        params = php_post_ar("params",params);
        params.quote_id = this.my_data.quote_id;
        params.m = "save_details";
        this.post_ajax(params);        
    },
    
    post_curb: function(c) {
        var params = php_post_ar('params',c,this.c_keys);
        if(this.unsaved)
            Object.extend(params,php_post_ar('params[details]',this.get_details_ar()));
        if(!$('curb_lining').disabled)
        {            
            var o = $('curb_options').serialize(true);
            params['params[options][]'] = $H(o).values().flatten();         
        }        
        
        params.quote_id = this.my_data.quote_id;
        params.m = "save_curb";
        //alert($H(params).inspect());
        this.post_ajax(params);
    },
    
    post_del_curb: function(quote_curb_id) {
        var params = { 'params[quote_curb_id]' : quote_curb_id };
        if(this.unsaved)
            Object.extend(params,php_post_ar('params[details]',this.get_details_ar()));
        params.quote_id = this.my_data.quote_id;
        params.m = "del_curb";
        this.post_ajax(params);
    },
    
    post_with_details: function(params) {        
        if(this.unsaved)
            Object.extend(params,php_post_ar('params[details]',this.get_details_ar()));
        this.post_ajax(params);
    },
    
    on_ajax_complete: function(transport) {
        var opt = transport.responseJSON.opt;
        switch(opt)
        {
            case "error":
                alert(transport.responseJSON.msg); return;
                break;
            case "order":
                return this.handle_order_result(transport.responseJSON);
                break;
            case "estimator":
                return this.handle_estimator_result(transport.responseJSON);
                break;       
            case "email":     
                alert_box(transport.responseJSON.msg); return;
                break;            
        }
                
        this.my_data = transport.responseJSON;
        switch(opt)
        {
            case "get":
                //this.newmodelctrl.get_brand_options(this.my_data.distributor_id);
                $('distributor_notes_wnd').show();
                break;
            case "save":
                alert_box("Quote Saved!");//alert("Quote Saved!");
                this.unsaved = false;                                
                break;            
        }
        this.update_form();
        this.validate_ctrl();
        this.update_header();
        this.observe_form();
                
        if(this.badd_more) {
            this.set_curb_form_view(parseInt($F('step2_lb')));            
            this.toggle_wnds('curb_wnd','quote_pane');
            this.badd_more = false;            
        }     
    },

    observe_form: function() {
        if(!this.frm_observer)
            this.frm_observer = new Form.Observer('quote_form', 1, this.form_change.bind(this));        
    },    
    
    form_change: function(form,value) {
        this.unsaved = true;
        this.validate_ctrl();
        this.update_header();
    },
    
    on_click: function(evt) {
        var e = Event.element(evt);
        if(e.tagName == "INPUT" && e.disabled)
            return;       
        
        if(Object.isFunction(this[e.id]))
            this[e.id](evt);
        else
        {
        	switch(e.id)
            {
                case "dist_pane":
                case "cont_pane":
                case "cc_pane":
                    this.show_customer_wnd(); break;                
                case "save_ctrl":
                    this.post_details(); break;                    
                case "pdf_ctrl":
                    window.open("quote_pdf_ajax.php?quote_id=" + this.my_data.quote_id + "&genid=" + Math.floor(Math.random()*101) + "&m=stream");
                    break;
                case "customer_step1":
                	if($('step1_job_tag').present()) {
                		$('job_tag').value = $F('step1_job_tag');                                
                        this.toggle_wnds('customer_step2_wnd','customer_step1_wnd');
                        this.unsaved = true;
                	} else
                		alert("Job Tag Required!");                
                    break;                 
                case "customer_step2":
                    //$('curb_type_id').value = $F('step2_lb');                	
                    $('customer_step2_wnd').hide();
                    this.set_curb_form_view(parseInt($F('step2_lb'))); // curb_type_id
                    this.toggle_wnds('curb_wnd','quote_pane');
                    break;                
                case "exfreight":
                case "weatherproof":
                    var params = {quote_id : this.my_data.quote_id}
                    params.m = (e.checked) ? "add_" + e.id : "del_" + e.id;
                    this.post_with_details(params);                 
                    break;
                /* curb options events */
                case "options_add_curb":
                    $('options_no_curb','options_add_curb','curb_options_OL').invoke('toggle');
                    var co_frm = $('curb_options');
                    co_frm.reset();
                    co_frm.enable();                                
                    co_frm.select('.curb_lining').invoke('disable');
                    $('solid_floor_sr').disable()
                    //this.reset_curb_options_frm();
                    break;
                case "options_no_curb":
                    $('options_no_curb','options_add_curb','curb_options_OL').invoke('toggle');
                    $('curb_options').disable();
                    break;            
                case "curb_lining":            
                    var f = e.checked ? "enable" : "disable"; 
                    $('curb_options').select('.' + e.id).invoke(f);
                    break;
                case "solid_floor":
                    e.checked ? $('solid_floor_sr').enable() : $('solid_floor_sr').disable();
                    break;
                case "cb_old_part":
                case "cb_new_part":
                    var pre = (e.id=="cb_old_part") ? "old" : "new";
                    if(e.checked) {
                        $(pre + '_part_row').show();
                        $(pre + '_model_row').hide();
                        $(pre + '_part_id').enable();
                        $(pre + '_model_id').disable();                    
                    } else {
                        $(pre + '_model_row').show();
                        $(pre + '_part_row').hide();
                        $(pre + '_model_id').enable();
                        $(pre + '_part_id').disable();
                    } 
                    break;
                case "old_model_find":
                case "new_model_find":
                    $('model_finder_form').reset();
                    $('model_find_type').value = (e.id=="old_model_find") ? "old" : "new";
                    this.toggle_wnds('model_finder_wnd','curb_wnd'); 
                    break;
                case "unknown_model":
                    var mt = $F('model_find_type');
                    $(mt + '_part_id').enable().value = 314;
                    $(mt + '_model_id').value = 0;
                    $(mt + '_model').setStyle({'backgroundColor' : '#e17171'}).value = $F('unknown_model_txt');                
                    this.toggle_wnds('curb_wnd','model_finder_wnd');
                    $('model_list').update('');
                    break;                
            }
        }       
                
    },
    
    on_mbrand: function(evt) {
        var brand_id = parseInt($F('mbrand_id'));
        if(brand_id > 0)
            new Ajax.Updater('model_list', this.ax_url, { parameters: { m: 'brand_list_html', params: $F('mbrand_id') }});
    },
    
    on_model_click: function(evt) {
        var e = Event.element(evt);
        if(e.nodeName == "A") {
            var mt = $F('model_find_type');
            $(mt + '_model_id').value = e.id.substring(5);
            $(mt + '_model').setStyle({'backgroundColor' : ''}).value = e.innerHTML;
            this.toggle_wnds('curb_wnd','model_finder_wnd');
            $('model_list').update('');
        }
    },
        
    on_ship_day: function(evt) {
        ($F('ship_day') == "pick_date") ? $('scheduled_ship').enable(): $('scheduled_ship').disable();
        $('scheduled_ship').clear();        
    },
    
    on_address: function(evt) {
        var user_address_id = $F('user_address_id');
        if(user_address_id == "0") {
            $('bsave_address').enable();
            return; // clear address
        }
        var params = {quote_id: this.my_data.quote_id, m: 'get_address', 'params' : user_address_id};
        new Ajax.Request(this.ax_url, {         
            method:'post',            
            onComplete: function(transport) {
                var a = transport.responseJSON;
                $('shipto_name').value = a.user_address_name;
                $('shipto_address').value = a.address;
                $('shipto_city').value = a.city;
                $('shipto_state').value = a.state;
                $('shipto_zip').value = a.zip;
                $('bsave_address').disable();
                //alert($H(transport.responseJSON).inspect());                
            },
            parameters: params
        });
    },
    
    update_header: function() {
        var txt = "Quote Builder #" + this.my_data.quote_id;
        if(this.unsaved)
            txt += " (unsaved)"; 
        else if(this.my_data.locked)
            txt += " (locked)";   
        $('quote_header').update(txt);
    },    
    
    update_user_lnks: function() {
        if(this.my_data.admin) {        
            $('distributor_name').update("<a href='user_admin.php?opt=edit_form&user_id="+this.my_data.distributor_id+"' target='_new'>"+this.my_data.distributor_name+"</a>");
            $('contractor_name').update("<a href='user_admin.php?opt=edit_form&user_id="+this.my_data.contractor_id+"' target='_new'>"+this.my_data.contractor_name+"</a>");
            $('user_cc_name').update("<a href='user_admin.php?opt=edit_form&user_id="+this.my_data.user_cc_id+"' target='_new'>"+this.my_data.user_cc_name+"</a>");
            $('company_name').update("<a href='company_admin2.php?company_id="+this.my_data.company_id+"' target='_new'>"+this.my_data.company_name+"</a>");
        } else {
            $('distributor_name').update(this.my_data.distributor_name);
            $('company_name').update(this.my_data.company_name);
            $('contractor_name').update(this.my_data.contractor_name);
            $('user_cc_name').update(this.my_data.user_cc_name);        
        }        
    },    
    
    update_form: function() {
        //this.update_header();
        this.update_user_lnks();   
        if(this.my_data.admin)
        {   
        	if(!this.my_data.locked && (parseInt(this.my_data.quote_status_id)==3) && $('edit_ordered_quote').checked) {        		 
        		$('edit_ordered_quote_wnd').show();
        		this.my_data.locked = true;
        	}        		
        	
            $('customer_notes').update(this.my_data.customer_notes.gsub('\n','<br>'));
            $('notes').update("<textarea name='notes' >" + this.my_data.notes + "</textarea>");
            $('internal_notes').value = this.my_data.internal_notes;
            var d_html = "";
            for (var i=0, il=this.my_data.internal_files.length; i<il; i++)       
                d_html += d_template.evaluate(this.my_data.internal_files[i]);        
            $('internal_files_ul').update(d_html);
            
            var h_html = "";
            for (var i=0, il=this.my_data.history.length; i<il; i++)       
                h_html += "<LI>" + this.my_data.history[i];        
            $('history').update(h_html);   
            $('quote_status_id').value = this.my_data.quote_status_id;         
        }
        else
        {
            $('customer_notes').update("<textarea name='customer_notes' >" + this.my_data.customer_notes + "</textarea>");    
            $('notes').update(this.my_data.notes.gsub('\n','<br>'));
        }
        
        $('job_tag').value = this.my_data.job_tag;
        $('weatherproof').checked = this.my_data.weatherproof;
        $('exfreight').checked = this.my_data.exfreight;        
        $('freight_zipcode').value = this.my_data.freight_zipcode;
        $('freight_datetime').value = this.my_data.freight_datetime;
        (this.my_data.exfreight) ? $('exfreight_info').show() : $('exfreight_info').hide();
                                
        if(this.my_data.distributor_notes != "")
            $('distributor_notes').update(this.my_data.distributor_notes.gsub('\n','<br>'));                    
        else
            $('distributor_notes_wnd').hide();  
        (this.my_data.locked) ? $('locked').show() : $('locked').hide();    
                      
        // curb panes
        this.update_curbs();        
    },    
    
    update_curbs: function() {    
        var shipdates = $H(); 
        var d = new Date();
        var day = d.getDay();
        shipdates.set('one_day',shipday[day++]);
        shipdates.set('two_day',shipday[day++]);
        shipdates.set('three_day',shipday[day++]);
        shipdates.set('four_day',shipday[day++]);
        shipdates.set('five_day',shipday[day++]);
                
        var c_html = "";
        var p_html = "";
        var footnotes = "";
        var valid_total = true;
        c_html += curb_TH;        
        p_html += (this.my_data.has_iso) ? price_TH_iso : price_TH;  
        if(!this.my_data.has_iso)
            p_html += shipdate_TH.evaluate(shipdates);
        
        var i = 0;
        var il=this.my_data.quote_curbs.length                
        for (i=0;i<il; i++) 
        {
            var c = this.my_data.quote_curbs[i];
            var p = this.my_data.prices[i];
            p.nomenclature = c.nomenclature;
            p.cname = (this.my_data.admin && c.price_override > 0) ? "pover_row" : "";
            c.i = i;
            c.buttons = "";
            
            if(this.my_data.locked) {            	
            	c.buttons += cbut_template.evaluate({action:'locked', title: 'This Quote is Locked'});
            	if(this.my_data.admin && parseInt(c.curb_estimate_id) > 1) {
                	c.buttons += cbut_template.evaluate({action:'est',title: 'Estiamtor'});
                }
            }
            else {
            	if(!c.cdi_only || this.my_data.admin) {
                	c.buttons += cbut_template.evaluate({action:'edit', title: 'Edit Item'});
                	c.buttons += cbut_template.evaluate({action:'delete', title: 'Delete Item'});
                } else 
                	c.buttons += cbut_template.evaluate({action:'locked', title: 'Only CDI can Edit this item. Contact your CDI sales rep for help.'});
                
                if(this.my_data.admin) {
                	c.buttons += cbut_template.evaluate({action:'upload',title: 'Upload Drawing'});
                	c.buttons += cbut_template.evaluate({action:'est',title: 'Estiamtor'});
                }
            }
            
            if(c.drawing_old)
            	c.desc += d_template.evaluate(c.drawing_old);
            if(c.drawing_new)
            	c.desc += d_template.evaluate(c.drawing_new);
            if(c.drawing_3d)
            	c.desc += d_template.evaluate(c.drawing_3d);
            c_html += c_template.evaluate(c);
            if(p.catalog_num != "")
                p_html += pcat_template.evaluate(p);
            else if(this.my_data.has_iso)
                p_html += piso_template.evaluate(p);
            else            
                p_html += p_template.evaluate(p);
        }
        var p = this.my_data.prices[i];   
        p.nomenclature = "<B>TOTAL:</B>";         
        if(p.catalog_num != "")
            p_html += pcat_template.evaluate(p);
        else if(this.my_data.has_iso)
            p_html += piso_template.evaluate(p);
        else
            p_html += p_template.evaluate(p);
        $('curb_table').update(c_html);
        $('price_table').update(p_html);  
        $('price_footnotes').update(footnotes);      
    },    
    
    validate_ctrl: function() {
        var disable_save = false;
        var disable_pdf = false;
        var disable_order = false;
        var disable_email = false;
        var disable_emaild = false;
        var disable_curb = false;
        //var q_msg = false;
        
        if(this.my_data.locked)
            disable_save = disable_order = disable_curb  = true;    
                
        if(parseInt(this.my_data.distributor_id) == 0)        
            disable_save = disable_pdf = disable_order = disable_curb  = true;              
        
        if($('exfreight').checked && (!$('freight_zipcode').present() || !$('freight_datetime').present()) )
        {
            disable_save = disable_curb = disable_pdf = disable_email = disable_order = true;
            q_msg = "Zipcode and Date/Time Required with Guaranteed Delivery";
        }        
        
        if(this.unsaved)
            disable_pdf = disable_email = disable_emaild = disable_order  = true;     
        
        if(this.my_data.quote_curbs.length == 0)        
            disable_save = disable_pdf = disable_order = true;
               
        (disable_save) ? $('save_ctrl').disable() : $('save_ctrl').enable();   
        (disable_pdf) ? $('pdf_ctrl').disable() : $('pdf_ctrl').enable();                 
        (disable_email) ? $('show_email').disable() : $('show_email').enable();
        (disable_order) ? $('show_place_order').disable() : $('show_place_order').enable();
        (disable_curb) ? $('add_curb','weatherproof','exfreight').invoke('disable') : $('add_curb','weatherproof','exfreight').invoke('enable'); 
        //(disable_emaild) ? $('email_drawings_ctrl').disable() : $('email_drawings_ctrl').enable();
        
        //(q_msg) ? $('q_msg').show().update(q_msg) : $('q_msg').hide();
    },
    
    edit_ordered_quote: function(evt) {
    	$('edit_ordered_quote_wnd').hide();
    	this.load_quote(this.my_data.quote_id);
    },
           
    show_customer_wnd: function() {
        if(this.my_data.distributor_id > 0) {                    
            $('new_distributor_hidden').value =  this.my_data.distributor_id;
            $('new_contractor_hidden').value =  this.my_data.contractor_id;
            $('new_user_cc_hidden').value =  this.my_data.user_cc_id;
            $('new_distributor').value =  this.my_data.distributor_name;
            $('new_contractor').value =  this.my_data.contractor_name;
            $('new_user_cc').value =  this.my_data.user_cc_name;
        }        
        $('customer_wnd').show();            
    },
    
    set_customers: function() {
        if(!$("new_distributor_hidden").present()) {
            alert("Must Select Distributer!");
            return false;
        }            
        this.my_data.distributor_id = $F('new_distributor_hidden');
        this.my_data.distributor_name = $F('new_distributor');
        this.my_data.contractor_id = $('new_contractor').present() ? $F('new_contractor_hidden') : 0;
        this.my_data.contractor_name = $('new_contractor').present() ? $F('new_contractor') : '';
        this.my_data.user_cc_id = $('new_user_cc').present() ? $F('new_user_cc_hidden'): 0;
        this.my_data.user_cc_name = $('new_user_cc').present() ? $F('new_user_cc'): '';        
        this.update_user_lnks();
        this.unsaved = true;
        this.update_header();  
        //this.newmodelctrl.get_brand_options(this.my_data.distributor_id);
        //$('customer_wnd').hide();
        this.toggle_wnds('quote_pane','customer_wnd');    
        this.validate_ctrl();     
        
        new Ajax.Updater('distributor_notes', this.ax_url, { parameters: { m: 'distributor_notes_HTML', params: this.my_data.distributor_id },
            onComplete: function(t) { $('distributor_notes_wnd').show(); }} );     
    },
    
    cancel_set_customers: function(evt) {
    	this.toggle_wnds('quote_pane','customer_wnd');
    },
    
    /* email functions */
    
    show_email: function(evt) {
    	this.toggle_wnds('email_wnd','quote_pane');
    },
    
    email_me_cb: function(evt) {
    	var m = (Event.element(evt).checked) ? "enable" : "disable";
    	$('email_me_ol').select("input").invoke(m);
    },
    
    email_drawings_cb: function(evt) {
    	var m = (Event.element(evt).checked) ? $('email_txt').enable() : $('email_txt').disable();    	
    },
    
    email_quote: function(evt) {
    	var params = $('email_form').serialize(true);
        params.quote_id = this.my_data.quote_id;
        params.m = "email";
        new Ajax.Request('quote_pdf_ajax.php', {         
            method:'post',            
            onComplete: this.on_ajax_complete.bind(this),
            parameters: params
        });
        this.toggle_wnds('quote_pane','email_wnd');
    },
    
    email_cancel: function(evt) {
    	this.toggle_wnds('quote_pane','email_wnd');
    },
    
    email_cancel_b: function(evt) {
    	this.email_cancel(evt);
    },
        
    /* curb functions */
    
    add_curb: function(evt) {
    	this.toggle_wnds('customer_step2_wnd','quote_pane');
    },
    
    cancel_curb: function(evt) {
    	this.toggle_wnds('quote_pane','curb_wnd');
    },
       
    set_curb_form_view: function(curb_type_id) {
        // reset fields if not editing curb
        var curb_form = $('curb_form');
        curb_form.disable();     
        curb_form.getElements().invoke('hide');
        $('new_model_span','burglar_curb_span','old_model_span', 'misc_curb_span','width_length_span','iso_span','dwall_span','part_span','old_part_row','new_part_row').invoke('hide');
        curb_form.select('.show').invoke('show').invoke('enable');
        
        //var curb_type_id  = parseInt($F('curb_type_id'));
        
        //$('curb_type_id').value = curb_type_id;
        
        var ct_lb = $('step2_lb');
        $('curb_form_title').update("Step 3: " + ct_lb.options[ct_lb.selectedIndex].text + ":");
                
        var cname = "";
        switch(curb_type_id)
        {
            case 1:
                cname = ".adapter"; break;
            case 2:
                cname = ".pitched"; break;                
            case 3:
                cname = ".metal"; break;
            case 4:
                cname = ".straight"; break;
            case 5:
                cname = ".exhaust"; break;
            case 6:
                cname = ".burglar"; break;
            case 7:
                cname = ".adjustable"; break;
            case 8:
                cname = ".custom"; break;
            case 9:
                cname = ".iso"; break;
            case 10:
                cname = ".misc"; break;
            case 11:
                cname = ".dwall"; break;
        }
        curb_form.select(cname).invoke('show');
        curb_form.select('SELECT' + cname).invoke('enable');        
        curb_form.select('INPUT' + cname).invoke('enable');
        
        if(this.my_data.admin)
        	$('price_override').enable().show();        	
                       
        if(this.edit_curb_id == -1)
        {
            $('curb_form').reset();
            $('curb_type_id').value = curb_type_id;
            $('curb_estimate_id').value = 0;        
            $('new_model_id').value = 0;
            $('old_model_id').value = 0;  
            $('options_no_curb','curb_options_OL').invoke('hide');
            $('options_add_curb').show();            
            $('new_part_id').value = 0;
            $('old_part_id').value = 0;
            $('curb_options').disable();
            $('old_part_id','new_part_id').invoke('disable');
            $('new_model').setStyle({'backgroundColor' : ''});
            $('old_model').setStyle({'backgroundColor' : ''});
        }
        else
        {
        	$('curb_type_id').value = curb_type_id;
            if($('cb_old_part').checked)
            {
                $('old_model_row').hide();
                $('old_model_id').disable();
                $('old_part_row').show();
            }
            if($('cb_new_part').checked)
            {
                $('new_model_row').hide();
                $('new_model_id').disable();
                $('new_part_row').show();
            }
            
            if(this.my_data.locked)
                $('save_curb','save_curb_more').invoke('disable');
        }
        
        ([2,3,4,7].indexOf(curb_type_id) != -1) ? $('curb_options_div').show() : $('curb_options_div').hide();
        
        //this.toggle_wnds('curb_wnd','quote_pane');                   
    },
       
    validate_curb: function() {
        var c = $('curb_form').serialize(true);     
        c.curb_type_id = parseInt(c.curb_type_id); //parseInt($F('curb_type_id'));        
        c.bvalid = true;         
        var qty = c.qty;        
        if( parseInt(qty) == 0 || isNaN(parseInt(qty)) ) {            
            c.bvalid = false;
            c.error_msg = "Invalid Qty";
        }
        
        if(c.curb_type_id == 1 || c.curb_type_id == 11) {
            if(!parseInt(c.old_model_id) && !parseInt(c.cdi_part_id_old))
                c.bvalid = false
            if(!parseInt(c.new_model_id) && !parseInt(c.cdi_part_id_new))                                
                c.bvalid = false;
            if(!c.bvalid)
                c.error_msg = "Need to select New and Old Model";            
        } else if([2,3,4,6,7,9].indexOf(c.curb_type_id) != -1 && (!parseInt(c.new_model_id) && !parseInt(c.cdi_part_id_new))) {                      
            c.bvalid = false;
            c.error_msg = "Need to select a New Model";
        }        
        return c;
    },    
    
    save_curb: function(evt)  {           
        var c = this.validate_curb();
        if(!c.bvalid)
        {
            alert(c.error_msg);
            return false;
        }
        $('curb_form').reset();          
                  
        if(this.edit_curb_id >= 0)
            c.quote_curb_id = this.my_data.quote_curbs[this.edit_curb_id].quote_curb_id;                
         
        this.edit_curb_id = -1;        
        this.post_curb(c);
        this.toggle_wnds('quote_pane','curb_wnd');
    },    
    
    save_curb_more: function(evt) {
    	this.badd_more = true;
    	this.save_curb();    	
    },
    
    on_click_curb: function(evt) {
    	var e = Event.element(evt);
    	if(!e.hasClassName("curb_button"))
    		return;
    	
    	i = parseInt(e.up().id.substring(8));        
        var c = this.my_data.quote_curbs[i];    	
        
        if(!this.my_data.admin && c.cdi_only) {
            alert("Only CDI can Edit/Delete this item.\n\nContact your CDI sales rep for help.");
            return;
        }
    	
        switch(e.name) {
        	case "edit":
        		this.edit_curb_id = i;
        		this.set_curb_form(c);
        		this.toggle_wnds('curb_wnd','quote_pane');
        		break;
        	case "delete":
        		if(confirm("Delete line item?"))
                    this.post_del_curb(c.quote_curb_id);
        		break;
        	case "est":
        		this.edit_curb_id = i;
        		this.set_curb_form(c);
        		this.curb_estimator();
        		$('quote_pane').hide();
        		break;
        	case "upload":
        		this.custom_darwings_form(c.quote_curb_id);
        		//this.edit_curb_id = i;
        		//this.toggle_wnds('customd_wnd','quote_pane');
        		break;
        }
    },
    
    set_curb_form: function(c) {       
        $('curb_form').reset();
        
        if(c.price_override > 0)
            $('price_override').value = c.price_override;            
                        
        $('qty').value = c.qty;
        $('tag').value = c.tag;
        $('base_height').value = c.base_height;
        $('curb_estimate_id').value = c.curb_estimate_id;
                
        if(c.new_part_id)
        {
            $('new_part_id').value = c.new_part_id;
            $('new_part').value = c.new_part_num;
            $('new_model_id').value = c.new_model_id;
            $('new_model').value = c.new_model;
            if(c.new_part_id==314)
                $('new_model').setStyle({'backgroundColor' : '#e17171'});
            else if(!c.new_model_id)            
                $('cb_new_part').checked = true;
            else
                $('new_model').setStyle({'backgroundColor' : ''});
        }
          //  this.newmodelctrl.set_model_brand(c.new_model_id,c.new_brand_id);
        
        // curb options
        if(c.options)
        {            
            var co_frm = $('curb_options');
            co_frm.reset();
            co_frm.enable();
            var x = $('curb_linig');
            $('curb_options').getInputs().each( function(i) 
            {
                if(i.id=='curb_lining')
                    return;
                if(c.options.indexOf(parseInt(i.value)) > -1)
                {
                    i.enable().checked = true;
                    if(i.type=='radio')
                        $("curb_lining").checked = true;
                }
            });            
            $('options_no_curb','curb_options_OL').invoke('show');
            $('options_add_curb').hide();
        }
        else
        {
            $('options_no_curb','curb_options_OL').invoke('hide');
            $('options_add_curb').show();
            $('curb_options').disable();
        }
        //alert(c.curb_type_id);
        switch(parseInt(c.curb_type_id))
        {
            case 1:                
                $('old_part_id').value = c.old_part_id;
                $('old_part').value = c.old_part_num;
                $('old_model_id').value = c.old_model_id;
                $('old_model').value = c.old_model;
                if(c.old_part_id==314)
                    $('old_model').setStyle({'backgroundColor' : '#e17171'});
                else if(!c.old_model_id)            
                    $('cb_old_part').checked = true;
                else
                    $('old_model').setStyle({'backgroundColor' : ''});
                break;
            case 2:
                $('pitched_side_type_id').value = c.side_type_id;
                $('pitched_pitch_id').value = c.pitch_id;                
                break;
            case 3:
                $('metal_side_type_id').value = c.side_type_id;
                $('pitched_pitch_id').value = c.pitch_id;
                break;
            case 4:
                $('straight_side_type_id').value = c.side_type_id;
                $('straight_pitch_id').value = c.pitch_id;
                break;
            case 5:
                $('exhaust_side_type_id').value = c.side_type_id;
                $('pitched_pitch_id').value = c.pitch_id;
                $('width_ft').value = c.width_ft;
                $('width_inch_id').value = c.width_inch_id;
                $('length_ft').value = c.length_ft;
                $('length_inch_id').value = c.length_inch_id;       
                break;
            case 6:
                //$('burglar_side_type_id').value = c.side_type_id;
                $('spacing').value = c.spacing;
                $('diameter').value = c.diameter;
                $('frame').value = c.frame;                
                break;     
            case 7:
                $('adjustable_side_type_id').value = c.side_type_id;
                $('adjustable_pitch_id').value = c.pitch_id;
                break;   
            case 8:
                $('cdi_part_id_custom').value = c.old_part_id;
                break;
            case 9:
                $('iso_model_id').value = c.old_model_id;
                break;
            case 10:
                $('cdi_part_id_misc').value = c.old_part_id;
                break;
        }
        // set curb type in the lb so the right curb form is shown
        //$('curb_type_id').value = c.curb_type_id;
        this.set_curb_form_view(parseInt(c.curb_type_id));        
    },

    curb_estimator: function() {
        if(this.my_data.quote_id == 0) {
            alert("Must save quote before using the estimator!");
            return;    
        }
    
        var c = this.validate_curb();
        if(!c.bvalid) {
            alert("Must input all curb details to open estimator!");
            return;    
        }
        
        //var params = {curb_type_id: $F('curb_type_id'), curb_estimate_id: c.curb_estimate_id};
        var params = {curb_type_id: c.curb_type_id, curb_estimate_id: c.curb_estimate_id};
        
        if([1,2,3,4,5,7,11].indexOf(c.curb_type_id) > -1)
            new Ajax.Updater('curb_estimator_frm', 'curb_estimator.php', { parameters: params, onComplete: this.on_estimator_loaded.bind(this)});
        else
            alert("No Estimator for this Curb Type!");                  
    },
    
    on_estimator_loaded: function() {
        this.estimator = new curb_estimator(parseInt($F('curb_type_id')));
        //$('curb_estimator_wnd').show();
        this.toggle_wnds('curb_estimator_wnd','curb_wnd');
    },    
    
    save_estimator: function() {        
        $('price_override').enable().value = this.estimator.sell_price;
        var params = this.estimator.serialize();
        params.m = "save_curb_estimate";
        params.quote_id = this.my_data.quote_id;
        this.post_ajax(params);
        this.estimator.frm.disable();        
    },
    
    handle_estimator_result: function(t) {
        $('curb_estimate_id').value = t.curb_estimate_id;
        this.toggle_wnds('curb_wnd','curb_estimator_wnd');
    },
    
    cancel_estimator: function(evt) {
    	this.toggle_wnds('curb_wnd','curb_estimator_wnd'); 
    },
    
    /* custom drawings */
    
    custom_darwings_form: function(quote_curb_id) {  
    	$('customd_frm').reset();
    	$('customd_upload').disable();
    	$('customd_disable').enable();
    	$('quote_file').value = "select file...";
    	$('customd_quote_curb_id').value = quote_curb_id;
    	if(this.ax_upload === false) {
    		this.ax_upload = new Ajax_upload('quote_file', {        	
            	action: this.ax_url, 
            	name: 'quote_file',
            	autoSubmit: false,
                data: { m : 'add_custom_drawing', quote_id : this.my_data.quote_id, params: '' },
                onChange: function(file, response) { 
                	$('quote_file').value = file.truncate(20); 
                	$('customd_upload').enable();
                	$('customd_disable').disable();
                },            
                onComplete: this.on_custom_darwings_complete.bind(this)
            });
    	}
        this.toggle_wnds('customd_wnd','quote_pane');
    },
    
    on_custom_darwings_complete: function(file, response) {
    	if(response == "error")
            alert("File Upload Failed");
        else
            alert_box("File Uploaded!");
        $('quote_file').update("Select File");
        ajax_complete();
        this.load_quote(this.my_data.quote_id);
        this.toggle_wnds('quote_pane','customd_wnd');
    },    
    
    customd_upload: function(evt) {
    	$('customd_upload').disable();
    	var params = $('customd_frm').serialize(true);
        params.quote_id = this.my_data.quote_id;
        params.m = "add_custom_drawing";
    	this.ax_upload.setData(params);
        ajax_working();
        this.ax_upload.submit();
    },
    
    customd_disable: function(evt) {
    	if(confirm("Delete Custom Drawing?")) {
    		var params = $('customd_frm').serialize(true);
            params.quote_id = this.my_data.quote_id;
            params.m = "disable_custom_drawing";
            this.post_ajax(params);
            this.toggle_wnds('quote_pane','customd_wnd');
    	}    	
    },
    
    customd_cancel: function(evt) {
    	this.toggle_wnds('quote_pane','customd_wnd');
    },
        
    /* internal files */
        
    internal_files: function() {        
        var params = {quote_id:this.my_data.quote_id,m:"ifiles_list_HTML"};
        new Ajax.Updater('quote_ifile_list',this.ax_url,{ parameters: params, onComplete: function(t) {
            $('quote_pane','ifile_wnd').invoke('toggle');
        }} );
        
        this.i_ax_upload = new Ajax_upload('quote_ifile', {        	
        	action: this.ax_url, 
        	name: 'quote_ifile',
        	autoSubmit: false,
            data: { m : 'add_ifile', quote_id : this.my_data.quote_id, params: '' },
            onChange: function(file, response) {
                $('quote_ifile').update(file.truncate(20));
                if(!$('quote_ifile_title').present())
                    $('quote_ifile_title').value = file;
            },            
            onComplete: function(file, response) {
                if(response == "error")
                    alert("File Upload Failed");
                else
                    alert_box("File Uploaded!");
                $('quote_ifile').update("Select File");
                $('quote_ifile_title').clear();
                $('quote_ifile_list').update(response);
                ajax_complete();
        	}	
        });
    },
    
    upload_ifile: function(evt) {
    	this.i_ax_upload.setData({m: 'add_ifile', 'params': $F('quote_ifile_title'), quote_id : this.my_data.quote_id});
        ajax_working();
        this.i_ax_upload.submit();
    },
    
    close_ifile: function(evt) {
    	$('quote_pane','ifile_wnd').invoke('toggle');
        this.post_ajax({quote_id: this.my_data.quote_id, m: 'to_json' });
    },
    
    save_ifile: function() {
        var params = $('ifile_frm').serialize(true);
        params.quote_id = this.my_data.quote_id;
        params.m = "disable_ifiles";
        new Ajax.Updater('quote_ifile_list',this.ax_url,{ parameters: params, onComplete: function(t) {
            alert_box("Settings Saved!");    
        }} );
    }, 
    
    /* misc ui functions */    
    
    toggle_wnds: function(show_id,hide_id) {
        $(hide_id).hide();
        new Effect.Appear(show_id, {quote: 'end', duration : .5 });        
    },
    
    /* ORDER FUNCTIONS */  
    
    show_place_order: function(evt) {     
    	if(this.my_data.has_dup_curbs && this.my_data.admin) {
    		alert("You need to Consolidate Duplicate Curbs!");
    		return;
    	}    	
        this.set_ship_day_lb();
        new Ajax.Updater('user_address_id',this.ax_url,{ parameters: { quote_id: this.my_data.quote_id, m: "get_addresses_LB"} } );
        $('bsave_address').enable().checked = true;                    
        this.toggle_wnds('order_wnd','quote_pane');
        if(this.my_data.distributor_notes != "")
            $('distributor_notes_wnd').show();
    },
    
    cancel_order: function(evt) {
    	this.toggle_wnds('quote_pane','order_wnd'); 
    },
    
    place_order: function(evt) {         
        if(!$('order_form').select('.order_req').all( function(n) {return n.present();} )) {
            alert("Missing *required field!");
            return;
        }
            
        if(confirm("Are you sure you want to place this order?")) {   
            if(this.post_order()) {
                this.toggle_wnds('order_processing_wnd','order_wnd');//$('order_wnd').hide();
                ajax_working_update();
            }
        }   
    },
    
    post_order: function() {   
        var odata = $('order_form').serialize(true);
        if(odata.ship_day == 'pick_date' ) {         
            odata.ship_day = "five_day_mod";             
            var today =  new Date();    
            today.setDate(today.getDate()+5);            
            var s_date = new Date(odata.scheduled_ship); 
            if(s_date.getTime() < today.getTime()) {
                alert("Invalid Date!");
                return false;
            }
        }        
        params = php_post_ar("params",odata);
        params.m = 'add_order';
        params.quote_id = this.my_data.quote_id;
        this.post_ajax(params);            
        return true;
    },
    
    handle_order_result: function(rst) {
        if(rst.tracker_id > 0) {
            if(rst.admin) {            
                if(rst.warehouse)
                    order_url="stock_allocator.php?tracker_id=" + rst.tracker_id;
                else
                    order_url="tracker_admin.php?tracker_id=" + rst.tracker_id;
            }
            else
                order_url="myorder.php?tracker_id=" + rst.tracker_id;
            var txt = "<P>" + rst.result + " Your order number is #" + rst.tracker_id;
            txt += "<P>You will be redirectly in 5 seconds or click below to continue.";
            txt += "<p class='H16'><a href='"+order_url+"'>Continue to Order Page</a>";            
            $("order_processing_txt").update(txt);
            if(!rst.dup_po)
            	setTimeout(order_redirect,5000);
        } else {
            alert("Order " + rst.result);
            this.toggle_wnds('quote_pane','order_processing_wnd')
        }
    },    
    
    set_ship_day_lb: function() {           
        var sd_lb = $('ship_day');
        sd_lb.options.length = i = 0;
        if(this.my_data.has_iso) {
            sd_lb.options[i++] = new Option("10+ Days (Pick Date)","pick_date");
            sd_lb.options[i++] = new Option("10 Days","ten_day");
        } else {
            var p = this.my_data.prices.last();
            sd_lb.options[i++] = new Option("5+ Day (Pick Date)","pick_date");
            if(p.five_day != "NA")
            {
                var txt = (p.catalog_num == "") ? "5 Day " + p.five_day: "5 Day";       
                sd_lb.options[i++] = new Option(txt,"five_day_mod");
            }
            txt = (p.catalog_num == "") ? "4 Day " + p.four_day: "4 Day";            
            sd_lb.options[i++] = new Option(txt,"four_day_mod");     
            txt = (p.catalog_num == "") ? "3 Day " + p.three_day: "3 Day";                 
            sd_lb.options[i++] = new Option(txt,"three_day_mod");
            if(p.two_day != "NA") {
            	txt = (p.catalog_num == "") ? "Tomorrow " + p.two_day: "Tomorrow";
            	sd_lb.options[i++] = new Option(txt,"two_day_mod");
            }
            if(p.one_day != "NA") {
                txt = (p.catalog_num == "") ? "Today " + p.one_day: "Today";
                sd_lb.options[i++] = new Option(txt,"one_day_mod");
            }
        }  
        sd_lb.options[1].selected = true;
        $('scheduled_ship').disable();        
    }
});    