// Boxy plugin
// (LW - I'm putting it here rather than changing the 45-odd different page templates, or trying
// to shoe-horn it into a module's drupal_add_js function)


// Boxy - Facebook-style dialog, with frills
// (c) 2008 Jason Frame

// TODO: multi-select list
// TODO: allow resizing when not visible
// BUG: modal dialog blackout doesn't resize when window resizes
// BUG: 'single' option to main plugin method not yet supported.

//
// jQuery Plugin

// single - only show a single instance at a time (default: true)
// cache - if true, data retrieved from AJAX calls will be cached. Inline data
//         will always be cached as we need to stash it someplace outside the DOM
//         to avoid having multiple elements with the same ID.
// message - confirmation message for form submit hook (default: "Please confirm:")
// method - AJAX method to use for loading remote content (default: GET)
// (any leftover options - e.g. 'clone' - will be passed onto the boxy constructor)



$.fn.boxy = function(options) {
    options = $.extend({single: true}, options || {});
    this.each(function() {      
        var node = this.nodeName.toLowerCase(), self = this;
        if (node == 'a') {
            $(this).click(function() {
                var anchor = this,
                    href = this.getAttribute('href'),
                    realOpts = $.extend(options, {title: this.title});
                    
                var loadContent = function(after) {
                    if (Boxy.cache[href]) {
                        after(Boxy.cache[href].clone());   
                    } else if (href.indexOf('#') === 0) {
                        Boxy.cache[href] = $(href).remove();
                        after(Boxy.cache[href].clone());
                    } else { // fall back to AJAX; could do with a same-origin check
                        $.ajax({
                            url: anchor.href,
                            method: options.method || 'GET',
                            dataType: 'html',
                            success: function(data) {
                                data = $(data);
                                if (options.cache) {
                                    Boxy.cache[href] = data;
                                    data = data.clone();
                                }
                                after(data);
                            }
                        });
                    }
                };
                
                var active;
                if (options.single && (active = $.data(this, 'active.boxy'))) {
                    loadContent(function(content) {
                        active.setContent(content).center().show();     
                    });
                } else {
                    loadContent(function(content) {
                        $.data(anchor, 'active.boxy', new Boxy(content, realOpts));     
                    });
                }
                
                return false;
            });
        } else if (node == 'form') {
            $(this).bind('submit.boxy', function() {
                Boxy.ask(options.message || 'Please confirm:', ['OK', 'Cancel'], function(v) {
                    if (v == 'OK') {
                        $(self).unbind('submit.boxy').submit();
                    }
                }, {modal: true, closeable: false});
                return false;
            });
        }
    });
};

//
// Boxy Class

function Boxy(element, options) {
    
    this.boxy = $(this.WRAPPER);
    $.data(this.boxy[0], 'boxy', this);
    
    this.visible = false;
    this.options = $.extend({
        title: null, closeable: true, draggable: true, clone: false,
        center: true, show: true, modal: false
    }, options || {});
    
    if (this.options.modal) {
        this.options = $.extend(this.options, {center: true, draggable: false});
    }
    
    this.setContent(element || "<div></div>");
    this._setupTitleBar();
    this._setupBehaviours();
    
    this.boxy.css('display', 'none').appendTo(document.body);
    this.toTop();
    
    if (this.options.center
        && typeof this.options.x == 'undefined'
        && typeof this.options.y == 'undefined') {
        this.center();
    } else {
        this.moveTo(this.options.x || Boxy.DEFAULT_X,
                    this.options.y || Boxy.DEFAULT_Y);
    }
    
    if (this.options.show) this.show();

};

$.extend(Boxy, {
    DEFAULT_X:          50,
    DEFAULT_Y:          50,
    cache:              {},
    zIndex:             1337,
    dragConfigured:     false, // only set up one drag handler for all boxys
    dragging:           null,
    
    // allows you to get a handle to the containing boxy instance of any element
    // e.g. <a href='#' onclick='alert(Boxy.get(this));'>inspect!</a>.
    // this returns the actual instance of the boxy 'class', not just a DOM element.
    // Boxy.get(this).hide() would be valid, for instance.
    get: function(ele) {
        var p = $(ele).parents('.boxy-wrapper');
        return p.length ? $.data(p[0], 'boxy') : null;
    },
    
    // asks a question with multiple responses presented as buttons
    // selected item is returned to a callback method.
    // answers may be either an array or a hash. if it's an array, the
    // the callback will received the selected value. if it's a hash,
    // you'll get the corresponding key.
    ask: function(question, answers, callback, options) {
        
        options = $.extend({modal: true, closeable: false}, options, {show: true});
        
        var body = $('<div></div>').append($('<div class="question"></div>').html(question));
        
        // ick
        var map = {}, answerStrings = [];
        if (answers instanceof Array) {
            for (var i = 0; i < answers.length; i++) {
                map[answers[i]] = answers[i];
                answerStrings.push(answers[i]);
            }
        } else {
            for (var k in answers) {
                map[answers[k]] = k;
                answerStrings.push(answers[k]);
            }
        }
        
        var buttons = $('<form class="answers"></form>');
        buttons.html($.map(answerStrings, function(v) {
            return "<input class='magicButtonBlack' type='button' value='" + v + "' />";
        }).join(' '));
        
        $('input[type=button]', buttons).click(function() {
            var clicked = this;
            Boxy.get(this).hide(function() {
                if (callback) callback(map[clicked.value]);
            });
        });
        
        body.append(buttons);
        
        new Boxy(body, options);
        
    },
    
    _handleDrag: function(evt) {
        var d;
        if (d = Boxy.dragging) {
            d[0].boxy.css({left: evt.pageX - d[1], top: evt.pageY - d[2]});
        }
    },
    
    _nextZ: function() {
        return Boxy.zIndex++;
    }
});

Boxy.prototype = {
    
    WRAPPER:    "<table cellspacing='0' cellpadding='0' border='0' class='boxy-wrapper'>" +
                    "<tr><td class='top-left'></td><td class='top'></td><td class='top-right'></td></tr>" +
                    "<tr><td class='left'></td><td class='boxy-inner'></td><td class='right'></td></tr>" +
                    "<tr><td class='bottom-left'></td><td class='top'></td><td class='bottom-right'></td></tr>" +
                "</table>",
    
    // Returns the size of this boxy instance without displaying it.
    // Do not use this method if boxy is already visible, use getSize() instead.
    estimateSize: function() {
        this.boxy.css('display', 'none')
                 .css({top: 0, left: 0, visibility: 'hidden'})
                 .css('display', 'block');
        var dims = this.getSize();
        this.boxy.css('display', 'none').css('visibility', 'visible');
        return dims;
    },
                
    // Returns the dimensions of the entire boxy dialog as [width,height]
    getSize: function() {
        return [this.boxy.width(), this.boxy.height()];
    },
    
    // Returns the dimensions of the content region as [width,height]
    getContentSize: function() {
        var c = this.getContent();
        return [c.width(), c.height()];
    },
    
    // Returns the position of this dialog as [x,y]
    getPosition: function() {
        var b = this.boxy[0];
        return [b.offsetLeft, b.offsetTop];
    },
    
    // Returns the center point of this dialog as [x,y]
    getCenter: function() {
        var p = this.getPosition();
        var s = this.getSize();
        return [Math.floor(p[0] + s[0] / 2), Math.floor(p[1] + s[1] / 2)];
    },
                
    // Returns a jQuery object wrapping the inner boxy region.
    // Not much reason to use this, you're probably more interested in getContent()
    getInner: function() {
        return $('.boxy-inner', this.boxy);
    },
    
    // Returns a jQuery object wrapping the boxy content region.
    // This is the user-editable content area (i.e. excludes titlebar)
    getContent: function() {
        return $('.boxy-content', this.boxy);
    },
    
    // Replace dialog content
    setContent: function(newContent) {
        newContent = $(newContent).css({display: 'block'}).addClass('boxy-content');
        if (this.options.clone) newContent = newContent.clone();   
        var content = this.getContent();
        if (content.length) {
            content.replaceWith(newContent);   
        } else {
            this.getInner().append(newContent);
        }
        return this;
    },
    
    // Move this dialog to some position, funnily enough
    moveTo: function(x, y) {
        this.boxy.css({left: x, top: y});
        return this;
    },
    
    // Move this dialog so that it is centered at x,y
    centerAt: function(x, y) {
        if (this.visible) {
            var s = this.getSize();
        } else {
            var s = this.estimateSize();
        }
        this.moveTo(x - s[0] / 2, y - s[1] / 2);
        return this;
    },
    
    // Center this dialog in the viewport
    center: function() {
        var s = $.browser.msie ? [document.body.scrollLeft, document.body.scrollTop]
                               : [window.pageXOffset, window.pageYOffset];
        var v = [s[0], s[1], $(window).width(), $(window).height()];
        this.centerAt((v[0] + v[2] / 2), (v[1] + v[3] / 2));
        return this;
    },
    
    // Resize the content region to a specific size
    resize: function(width, height, after) {
        if (!this.visible) return;
        var bounds = this._getBoundsForResize(width, height);
        this.boxy.css({left: bounds[0], top: bounds[1]});
        this.getContent().css({width: bounds[2], height: bounds[3]});
        if (after) after(this);
        return this;
    },
    
    // Tween the content region to a specific size
    tween: function(width, height, after) {
        if (!this.visible) return;
        var bounds = this._getBoundsForResize(width, height);
        var self = this;
        this.boxy.stop().animate({left: bounds[0], top: bounds[1]});
        this.getContent().stop().animate({width: bounds[2], height: bounds[3]}, function() {
            if (after) after(self);
        });
        return this;
    },
    
    isVisible: function() {
        return this.visible;    
    },
    
    // Make this boxy instance visible
    show: function() {
        if (this.visible) return;
        if (this.options.modal) {
            $('<div class="boxy-modal-blackout"></div>')
                .css({zIndex: Boxy._nextZ(),
                      width: $(document).width(),
                      height: $(document).height()})
                .appendTo(document.body);
            this.toTop();
        }
        this.boxy.stop().css({opacity: 1, display: 'block'});
        this.visible = true;
        return this;
    },
    
    // Hide this boxy instance
    hide: function(after) {
        if (!this.visible) return;
        var self = this;
        if (this.options.modal) {
            $('.boxy-modal-blackout').animate({opacity: 0}, function() {
                $(this).remove();
            });
        }
        this.boxy.stop().animate({opacity: 0}, 300, function() {
            self.boxy.css({display: 'none'});
            self.visible = false;
            if (after) after(self);
        });
        return this;
    },
    
    // Move this dialog box above all other boxy instances
    toTop: function() {
        this.boxy.css({zIndex: Boxy._nextZ()});
        return this;
    },
    
    //
    // Don't touch these privates
    
    _getBoundsForResize: function(width, height) {
        var csize = this.getContentSize();
        var delta = [width - csize[0], height - csize[1]];
        var p = this.getPosition();
        return [Math.max(p[0] - delta[0] / 2, 0),
                Math.max(p[1] - delta[1] / 2, 0), width, height];
    },
    
    _setupTitleBar: function() {
        if (this.options.title) {
            var self = this;
            var tb = $("<div class='title-bar'></div>").html(this.options.title);
            if (this.options.closeable) {
                tb.append($("<a href='#' class='close'></a>").html("[close]"));
            }
            if (this.options.draggable) {
                if (!Boxy.dragConfigured) {
                    $(document).mousemove(Boxy._handleDrag);
                    Boxy.dragConfigured = true;
                }
                tb.mousedown(function(evt) {
                    self.toTop();
                    Boxy.dragging = [self, evt.pageX - self.boxy[0].offsetLeft, evt.pageY - self.boxy[0].offsetTop];
                    $(this).addClass('dragging');
                });
                tb.mouseup(function() {
                    $(this).removeClass('dragging');
                    Boxy.dragging = null;
                });
            }
            this.getInner().prepend(tb);
        }
    },
    
    _setupBehaviours: function() {
        var self = this;
        $('.close', this.boxy).click(function() {
            self.hide();
            return false;
        }).mousedown(function(evt) { evt.stopPropagation(); });
    }
    
};

function getURLParams()
{
	var vals = location.search.substring(1, location.search.length).split('&');
	var gets = {};
	for (var i=0; i<vals.length; i++)
	{
		var t = vals[i].split('=');
		if (t[1])
		{
			gets[t[0]] = t[1];
		}
		else
		{
			gets[t[0]] = true;
		}
	}
	return gets;
}


function initiateSearch()
{
	$("#search_results").hide();
	$("#pbar").show();

	var params = getURLParams();
	$.get("/ajax.php", {op:"ucarSearch", manufacturer:params['manufacturer'], model:params['model'], prange:params['prange']}, function(data) {
		$("#search_results").html( data );
		$("#pbar").fadeOut();
		$("#search_results").fadeIn();
	});
}

function populateManufacturerNew(where, what)
{
	$.getJSON("/ajax.php?op=getmannew", {}, function(j) {
		var options= '<option value="0">Please select one</option>';
		options += '<option value="0">&nbsp;</option>';
		for (var i = 0; i < j.length; i++) {
			// LW - exclude Toyota for the Book a Test Drive form [https://thisisbliss.basecamphq.com/projects/2692931/posts/32080780/comments]
			if ((where=='td_man')&&(j[i].optionId==10519)) break;
			options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';			
		}

		//$("#manufacturer_new").html(options);
		$("#" + where).html(options);
		if(typeof what != "undefined")
		{
			//autoselect manufacturer, trigger change()
		}
	});
}

function search_notification_getModels(what, where)
{
	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$.getJSON("/ajax.php", { op: "getNotificationModels", make: what.value }, function(j) {
		var options = '<option value="All">All</option>';
		for (var i = 0; i < j.length; i++) {
		options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
		}

		$("#" + where).html(options);
	});
}

function search_getModels(what, where)
{
	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$.getJSON("/ajax.php", { op: "getModels", make: what.value }, function(j) {
		var options = '<option value="All">All</option>';
		for (var i = 0; i < j.length; i++) {
		options += '<option value="' + j[i].optionValueString + '">' + j[i].optionValue + '</option>';
		}

		$("#" + where).html(options);
	});
}

/*
function search_getModels(what)
{
	if(what.value==0)
	{
		$("select#model").html('<option value="All">All</option>');
		return;
	}

	$.getJSON("/ajax.php", { op: "getModels", make: what.value }, function(j) {
		var options = '<option value="all">All</option>';
		for (var i = 0; i < j.length; i++) {
		options += '<option value="' + j[i].optionValue + '">' + j[i].optionValue + '</option>';
		}
		$("select#model").html(options);
	});
}
*/

function replaceAdminText()
{
	var toolbar = '<div id="msg-toolbar">test</div>';

	if( $("#edit-body") )
	{
		var val = toolbar + "<div id='msg-enclosure' class='msg-enclosure'>" + $("#edit-body").val() + '<div style="clear:both;margin:10px 0;">&nbsp;</div></div>';
	}

	$("#edit-body").after(val);
	$("#edit-body").hide();
	//$("#edit-body").remove();
}

function instantiate()
{
	var div = document.getElementById("testfck");
	var val = div.firstChild.nodeValue;
	var fck = new FCKeditor("testfck");
	fck.BasePath = "/sites/all/themes/myTheme/extra/fckeditor/"
	fck.ToolbarSet = 'Basic';

	div.innerHTML = fck.CreateHtml();
}

function selectTab(what)
{
	if(what.value != 0)
	{
		if(what.id == "page")
		{
			document.location.href = '/rrgadmin/staticpages/' + what.value + '/';
		}
		else
		{
			document.location.href = '/rrgadmin/frontpage/' + what.value + '/';
		}
	}
}

function preview(what)
{
	for ( i = 0; i < parent.frames.length; ++i )
	if ( parent.frames[i].FCK )
	parent.frames[i].FCK.UpdateLinkedField();
	//tinyMCE.triggerSave();
	
	if(what == "rrg")
	{
		var title = document.getElementById("txt1").value;
		//var subtitle = document.getElementById("txt2").value;
		//var link1 = document.getElementById("txt3").value;
		//var link2 = document.getElementById("txt4").value;
		//var link3 = document.getElementById("txt5").value;

		window.open('/preview/?mod=rrg&txt1=' + encodeURIComponent(title) + '&txt2=&txt3=&txt4=&txt5=','mywindow','width=1000,height=600');
	}
	else
	{
		var title = document.getElementById("txt1").value;
		var subtitle = document.getElementById("txt2").value;
		var link1 = document.getElementById("txt3").value;
		var link2 = document.getElementById("txt4").value;

		window.open('/preview/?mod=' + what + '&txt1=' + encodeURIComponent(title) + '&txt2=' + encodeURIComponent(subtitle) + '&txt3=' + encodeURIComponent(link1) + '&txt4=' + encodeURIComponent(link2) ,'mywindow','width=1000,height=1600');
		//alert("title: " + title + "\n" + "subtitle: " + subtitle + "\n" + "link1: " + link1 + "\n" + "link2: " + link2);
	}
}

function preview2()
{
	for ( i = 0; i < parent.frames.length; ++i )
	if ( parent.frames[i].FCK )
	parent.frames[i].FCK.UpdateLinkedField();
	
	var title = document.getElementById("txt1").value;
	var subtitle = document.getElementById("txt2").value;
	var link1 = document.getElementById("txt3").value;
	var link2 = document.getElementById("txt4").value;
	var link3 = document.getElementById("txt5").value;

	window.open('/?mode=preview&txt1=' + encodeURIComponent(title) + '&txt2=' + encodeURIComponent(subtitle) + '&txt3=' + encodeURIComponent(link1) + '&txt4=' + encodeURIComponent(link2) + '&txt5=' + encodeURIComponent(link3) ,'mywindow','width=1000,height=600');
}

function newCarByMan_td()
{
	if( $("#td_man").val() == 0)
	{
		return;
	}

	var man = $("#td_man").val();
	$("#td_mod").html('<option value="0">Please wait...</option>');

	$.getJSON('/ajax.php', {op:"getcarbymanid", man: man}, function(j) {
		var options= '<option value="0">Select model...</option>';
		options += '<option value="0">&nbsp;</option>';
		for (var i = 0; i < j.length; i++) {
		options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
		}

		$("#td_mod").html(options);
	});
}

function offer_listing_commit_changes(what)
{
	$("#enquiry_table_" + what).fadeTo("fast", 0.5);

	var str = '';
	$("#enquiry_table_" + what + " input.fleet_discount").each( function(i, j) {
		str += $(j).attr('rel') + ':' + $(j).val() +',';
	});

	$.getJSON('/ajax.php', { op:"updateOffers", data:str, type:"new" }, function(j) {
		if(j.error=="1")
		{
			alert(j.msg);
		}

		$("#enquiry_table_" + what).fadeTo("fast", 1);
	});
}

function offer_commit_changes_blcv(what)
{
	var str = '';
	$("#enquiry_table input.fleet_orp").each( function(i, j) {
		str += $(j).attr('rel') + ':' + $(j).val() + '-';//CHANGEME
	});

	$.getJSON('/ajax.php', { op:"updateBLCVOffers", data:str, user:$("#fleet_user").val() }, function(j) {
		if(j.error=="1")
		{
			var str = '<input type="button" onclick="javascript:offer_commit_changes(' + what + ');" value="Commit changes" id="submit_der_options" name="submit"/><br /><p><strong>' + j.rsp + '</strong></p>';
			$("#fleet_settings").html(str);
		}
		else
		{
			$("#fleet_" + what).trigger("change");
		}
	});
}

function offer_commit_changes_fleet(what)
{
	var str = '';
	$("#enquiry_table input.fleet_orp").each( function(i, j) {
		str += $(j).attr('rel') + ':' + $(j).val() + '-';//CHANGEME
	});

	$.getJSON('/ajax.php', { op:"updateFleetOffers", data:str, user:$("#fleet_user").val() }, function(j) {
		if(j.error=="1")
		{
			var str = '<input type="button" onclick="javascript:offer_commit_changes(' + what + ');" value="Commit changes" id="submit_der_options" name="submit"/><br /><p><strong>' + j.rsp + '</strong></p>';
			$("#fleet_settings").html(str);
		}
		else
		{
			$("#fleet_" + what).trigger("change");
		}
	});
}

function offer_commit_changes_lcv(what)
{
	var str = '';
	$("#enquiry_table input.fleet_discount").each( function(i, j) {
		//str += $(j).attr('rel') + ':' + $(j).val() + ':' + $('#' + $(j).attr('rel') + '_finalprice').val() + '-';//CHANGEME
		str += $(j).attr('rel') + ':' + $(j).val() + ':' + $('#' + $(j).attr('rel') + '_finalprice').val() + ':' + $('#disabled_' + $(j).attr('rel')).attr('checked') + '-';//CHANGEME
	});

	$.getJSON('/ajax.php', { op:"updateLCVOffers", data:str, type:"lcv" }, function(j) {
		if(j.error=="1")
		{
			var str = '<input type="button" onclick="javascript:offer_commit_changes(' + what + ');" value="Commit changes" id="submit_der_options" name="submit"/><br /><p><strong>' + j.rsp + '</strong></p>';
			$("#fleet_settings").html(str);
		}
		else
		{
			$("#fleet_" + what).trigger("change");
		}
	});
}

function offer_commit_changes(what)
{
	var str = '';
	$("#enquiry_table input.fleet_discount").each( function(i, j) {
		//str += $(j).attr('rel') + ':' + $(j).val() + ':' + $('#' + $(j).attr('rel') + '_finalprice').val() + '-';//CHANGEME
		str += $(j).attr('rel') + ':' + $(j).val() + ':' + $('#' + $(j).attr('rel') + '_finalprice').val() + ':' + $('#disabled_' + $(j).attr('rel')).attr('checked') + '-';//CHANGEME
	});

	$.getJSON('/ajax.php', { op:"updateOffers", data:str, type:"new" }, function(j) {
		if(j.error=="1")
		{
			var str = '<input type="button" onclick="javascript:offer_commit_changes(' + what + ');" value="Commit changes" id="submit_der_options" name="submit"/><br /><p><strong>' + j.rsp + '</strong></p>';
			$("#fleet_settings").html(str);
		}
		else
		{
			$("#fleet_" + what).trigger("change");
		}
	});
}

function newVarByMod_td()
{
	if( $("#td_mod").val() == 0)
	{
		return;
	}

	var man = $("#td_mod").val();
	$("#td_var").html('<option value="0">Please wait...</option>');

	$.getJSON('/ajax.php',{op:"getvarbymodid", mod:man}, function(j) {
		var options= '<option value="0">Select variant...</option>';
		options += '<option value="0">&nbsp;</option>';
		for (var i = 0; i < j.length; i++) {
		options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
		}

		$("#td_var").html(options);
	});
}


function rrgadmin_fleet_update_derDetails()
{
	var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
	txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
	txt += '<br /><label>Range:</label> ' + $("#fleet_range option:selected").text();
	txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/' + $("#fleet_range option:selected").val() +'/">edit</a>)';
	txt += '<br /><label>Derivative:</label> ' + $("#fleet_der option:selected").text();
	txt += '<div class="fleet_settings" id="fleet_settings">';
	txt += '<input type="button" name="submit" id="submit_der_options" value="Commit changes" onclick="javascript:offer_commit_changes();"/>';
	txt += '</div>';
	$("#rrgfleet_box_details").html(txt);

	$("a#refresh_manufacturer").click( function() {
		$("#fleet_manufacturer").trigger("change");
	});

	$("a#refresh_range").click( function() {
		$("#fleet_range").trigger("change");
	});

	
}

function newCarByMan_feed_lcv()
{
	if( $("#fleet_manufacturer_lcv").val() == 0)
	{
		return;
	}

	var man = $("#fleet_manufacturer_lcv").val();
	$("#fleet_range_fleet").html('<option value="0">Please wait...</option>');
	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_loading").show();
	$("#rrgfleet_box_details").hide();

		$.getJSON('/ajax.php', { op:"getcarbymanid", man:man, lcv:"1" }, function(j) {
			var options= '<option value="0">Please select one</option>';
			var table = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
			table += '<thead>';
			table += '<tr>';
			table += '<th>id</th>';
			table += '<th>Range name</th>';
			table += '</tr>';
			table += '<tbody>';

			options += '<option value="0">&nbsp;</option>';
			for (var i = 0; i < j.length; i++)
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
				table += '<tr id="' + j[i].optionId + '">';
				table += '<td class="col1">' + j[i].optionId + '</td>';
				table += '<td>' + j[i].optionValue + '</td>';
				table += '</tr>';
			}

			table += '</tbody></table>';
			$("#fleet_results").html(table);
			$("#fleet_range_lcv").html(options);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
			/*
			$("tr").click( function() {
				window.location.href = "/rrgadmin/recruitment/application/" + $(this).attr("id") + "/";
			});
			*/

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer_lcv option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt+= '<br /><br />Please note that any discounts to the range will apply to all derivatives that don\'t already have a discount.</div>';

			$("#rrgfleet_box_details").html(txt);

			$("#fleet_der").html('<option value="0">Please select a manufacturer first</option>');

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_lcv").trigger("change");
			});

		});
	});

}

function newCarByMan_feed_blcv()
{
	if( $("#fleet_manufacturer_fleet").val() == 0)
	{
		return;
	}

	var man = $("#fleet_manufacturer_fleet").val();
	$("#fleet_range_fleet").html('<option value="0">Please wait...</option>');
	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_loading").show();
	$("#rrgfleet_box_details").hide();

		$.getJSON('/ajax.php', { op:"getcarbymanid", man:man, lcv:"1" }, function(j) {
			var options= '<option value="0">Please select one</option>';
			var table = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
			table += '<thead>';
			table += '<tr>';
			table += '<th>id</th>';
			table += '<th>Range name</th>';
			table += '</tr>';
			table += '<tbody>';

			options += '<option value="0">&nbsp;</option>';
			for (var i = 0; i < j.length; i++)
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
				table += '<tr id="' + j[i].optionId + '">';
				table += '<td class="col1">' + j[i].optionId + '</td>';
				table += '<td>' + j[i].optionValue + '</td>';
				table += '</tr>';
			}

			table += '</tbody></table>';
			$("#fleet_results").html(table);
			$("#fleet_range_fleet").html(options);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
			/*
			$("tr").click( function() {
				window.location.href = "/rrgadmin/recruitment/application/" + $(this).attr("id") + "/";
			});
			*/

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer_fleet option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt+= '<br /><br />Please note that any discounts to the range will apply to all derivatives that don\'t already have a discount.</div>';

			$("#rrgfleet_box_details").html(txt);

			$("#fleet_der").html('<option value="0">Please select a manufacturer first</option>');

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_fleet").trigger("change");
			});

		});
	});

}

function newCarByMan_feed_fleet()
{
	if( $("#fleet_manufacturer_fleet").val() == 0)
	{
		return;
	}

	var man = $("#fleet_manufacturer_fleet").val();
	$("#fleet_range_fleet").html('<option value="0">Please wait...</option>');
	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_loading").show();
	$("#rrgfleet_box_details").hide();

		$.getJSON('/ajax.php', { op:"getcarbymanid", man:man, type:"fleet" }, function(j) {
			var options= '<option value="0">Please select one</option>';
			var table = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
			table += '<thead>';
			table += '<tr>';
			table += '<th>id</th>';
			table += '<th>disabled</th>';
			table += '<th>Range name</th>';
			table += '</tr>';
			table += '<tbody>';

			options += '<option value="0">&nbsp;</option>';
			for (var i = 0; i < j.length; i++)
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
				table += '<tr id="' + j[i].optionId + '">';
				table += '<td class="col1">' + j[i].optionId + '</td>';

				table += '<td class="delete"><input type="checkbox"';
				
				if(j[i]['disabled'] == "1")
				{
					table += ' checked="checked"';
				}

				table += ' id="disabled_' + j[i]['optionId'] + '" onchange="disable_range_fleet(this);" rel="' + j[i]['optionId'] + '"/></td>';




				table += '<td>' + j[i].optionValue + '</td>';
				table += '</tr>';
			}

			table += '</tbody></table>';
			$("#fleet_results").html(table);
			$("#fleet_range_fleet").html(options);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
			/*
			$("tr").click( function() {
				window.location.href = "/rrgadmin/recruitment/application/" + $(this).attr("id") + "/";
			});
			*/

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt+= '<br /><br />Please note that any discounts to the range will apply to all derivatives that don\'t already have a discount.</div>';

			$("#rrgfleet_box_details").html(txt);

			$("#fleet_der").html('<option value="0">Please select a manufacturer first</option>');

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_fleet").trigger("change");
			});

		});
	});

}

function disable_der_fleet(what)
{
	$.getJSON('/ajax.php', {op:'disablederfleet', derId: $(what).attr('rel'), state: $(what).attr('checked')}, function(j) {
		if(j.rsp=='error')
		{
			$("#results_div").empty().append("An error occured while trying to perform your request. Please try again later or contact a member of staff.");
		}
		else
		{	if(j.rsp=='false')
			{	
				$("#results_div").empty().append("Fleet derivative has been enabled.");
			}
			else
			{
				$("#results_div").empty().append("Fleet derivative has been disabled.");
			}
		}

		$("#results_div").show();
		$("#results_div").animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200).animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200);
	});
}

function disable_range_fleet(what)
{
	$.getJSON('/ajax.php', {op:'disablerangefleet', rangeId: $(what).attr('rel'), state: $(what).attr('checked')}, function(j) {
		if(j.rsp=='error')
		{
			$("#results_div").empty().append("An error occured while trying to perform your request. Please try again later or contact a member of staff.");
		}
		else
		{	if(j.rsp=='false')
			{	
				$("#results_div").empty().append("Fleet range has been enabled.");
			}
			else
			{
				$("#results_div").empty().append("Fleet range has been disabled.");
			}
		}

		$("#results_div").show();
		$("#results_div").animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200).animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200);
	});
}

function disable_range(what)
{
	$.getJSON('/ajax.php', {op:'disablerange', rangeId: $(what).attr('rel'), state: $(what).attr('checked')}, function(j) {
		if(j.rsp=='error')
		{
			$("#results_div").empty().append("An error occured while trying to perform your request. Please try again later or contact a member of staff.");
		}
		else
		{	if(j.rsp=='false')
			{	
				$("#results_div").empty().append("Range has been enabled.");
			}
			else
			{
				$("#results_div").empty().append("Range has been disabled.");
			}
		}

		$("#results_div").show();
		$("#results_div").animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200).animate({ opacity: "0.3" }, 200).animate({ opacity: "1" }, 200);
	});
}

function newCarByMan_offers()
{
	if( $("#fleet_manufacturer").val() == 0)
	{
		return;
	}

	var man = $("#fleet_manufacturer").val();
	$("#fleet_range").html('<option value="0">Please wait...</option>');
	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_loading").show();
	$("#rrgfleet_box_details").hide();

		$.getJSON('/ajax.php', { op:"getcarbymanid_offers", man:man }, function(j) {
			var options= '<option value="0">Please select one</option>';
			var table = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
			table += '<thead>';
			table += '<tr>';
			table += '<th>id</th>';
			table += '<th>Range name</th>';
			table += '<th>Available offer</th>';
			table += '<th>actions</th>';
			table += '</tr>';
			table += '<tbody>';

			options += '<option value="0">&nbsp;</option>';
			for (var i = 0; i < j.length; i++)
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
				table += '<tr id="' + j[i].optionId + '">';
				table += '<td class="col1">' + j[i].optionId + '</td>';

				table += '<td>' + j[i].optionValue + '</td>';
				table += '<td>';
				if(j[i].offer==1)
				{
					table += '<a href="/rrgadmin/offers/view/' + j[i].optionId + '/">' + j[i].headline + '</a>';
				}
				else
				{
					table += '<a href="/rrgadmin/offers/add/' + j[i].optionId + '/">Add offer</a>';
				}
				table += '</td>';
				if(j[i].offer==1)
				{
					table += '<td><a href="/rrgadmin/offers/delete/' + j[i].optionId + '">delete</a></td>';
				}
				else
				{
					table += '<td>&nbsp;</td>';
				}
				table += '</tr>';
			}

			table += '</tbody></table>';
			$("#fleet_results").html(table);
			$("#fleet_range").html(options);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
			/*
			$("tr").click( function() {
				window.location.href = "/rrgadmin/recruitment/application/" + $(this).attr("id") + "/";
			});
			*/

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt+= '<br /><br />Please note that any discounts to the range will be overridden by specific derivative offers.</div>';

			$("#rrgfleet_box_details").html(txt);

			$("#fleet_der").html('<option value="0">Please select a manufacturer first</option>');

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer").trigger("change");
			});
		});
	});

}

function delete_listing_discount(id, what)
{
	$("#discount_" + id).val("0");
	$("#submit_list_options_" + what).trigger("click");
	$("#row_" + id).remove();
}

function newCarByMan_feed()
{
	if( $("#fleet_manufacturer").val() == 0)
	{
		return;
	}

	var man = $("#fleet_manufacturer").val();
	$("#fleet_range").html('<option value="0">Please wait...</option>');
	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_loading").show();
	$("#rrgfleet_box_details").hide();

		$.getJSON('/ajax.php', { op:"getcarbymanid", man:man }, function(j) {
			var options= '<option value="0">Please select one</option>';
			var table = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
			table += '<thead>';
			table += '<tr>';
			table += '<th>id</th>';
			table += '<th>disabled</th>';
			table += '<th>Range name</th>';
			table += '<th>discount</th>';
			table += '<th>delete</th>';
			table += '</tr>';
			table += '<tbody>';

			options += '<option value="0">&nbsp;</option>';
			for (var i = 0; i < j.length; i++)
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
				table += '<tr id="' + j[i].optionId + '">';
				table += '<td class="col1">' + j[i].optionId + '</td>';

				table += '<td class="delete"><input type="checkbox"';
				
				if(j[i]['disabled'] == "1")
				{
					table += ' checked="checked"';
				}

				table += ' id="disabled_' + j[i]['optionId'] + '" onchange="disable_range(this);" rel="' + j[i]['optionId'] + '"/></td>';



				table += '<td>' + j[i].optionValue + '</td>';
				table += '<td><input type="text" class="fleet_discount" id="discount_' + j[i]['optionId'] + '" value="' + j[i]['discount'] + '" rel="' + j[i]['optionId'] + '"/> %</td>';
				table += '<td class="delete">';
				if( j[i]['discount'] != 0 )
				{
					table += '<a href="javascript:void(0);" title="Delete discount" onclick="delete_discount(\'' + j[i]['optionId'] + '\');" ><img alt="" src="/resource/images/layout/delete-button.png" /></a>';
				}
				else
				{
					table += '&ndash;';
				}
				table += '</td>';
				table += '</tr>';
			}

			table += '</tbody></table>';
			$("#fleet_results").html(table);
			$("#fleet_range").html(options);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
			/*
			$("tr").click( function() {
				window.location.href = "/rrgadmin/recruitment/application/" + $(this).attr("id") + "/";
			});
			*/

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options" value="Commit changes" onclick="javascript:offer_commit_changes(\'manufacturer\');"/>';
			txt+= '<br /><br />Please note that any discounts to the range will apply to all derivatives that don\'t already have a discount.</div>';

			$("#rrgfleet_box_details").html(txt);

			$("#fleet_der").html('<option value="0">Please select a manufacturer first</option>');

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer").trigger("change");
			});
		});
	});

}

function delete_listing_discount(id, what)
{
	$("#discount_" + id).val("0");
	$("#submit_list_options_" + what).trigger("click");
	$("#row_" + id).remove();
}

function delete_discount(id)
{
	$("#discount_" + id).val("0");
	$("#" + id + "_finalprice").val('');
	$("#submit_der_options").trigger("click");
}

function getNewCarDer_lcv(what, where)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>disabled</th>';
		table2 += '<th>title</th>';
		table2 += '<th>rd / discount</th>';
		table2 += '<th>price</th>';
		table2 += '<th>vat</th>';
		table2 += '<th>price+vat</th>';
		table2 += '<th>final price</th>';
		table2 += '<th>delete</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		$.getJSON("/ajax.php", { op: "getNewModelsLcv", modID: what.value, usr:where }, function(j) {
			var options = '<option value="All">All</option>';
			for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionValue + '</option>';
				

				table2 += '<tr id="' + j[i]['optionId'] + '">';
				table2 += '<td class="col1">' + j[i]['optionId'] + '</td>';
				table2 += '<td class="delete"><input type="checkbox"';
				
				if(j[i]['disabled'] == "1")
				{
					table2 += ' checked="checked"';
				}

				table2 += ' id="disabled_' + j[i]['optionId'] + '" /></td>';
				table2 += '<td>' + j[i]['optionValue'] + '<br />' + j[i]['model'] + '</td>';
				table2 += '<td>(';


				table2 += j[i]['rangeDiscount'];
				/*
				if( j[i]['discount'] != 0)
				{
					table2 += '0';
				}
				else
				{
					table2 += j[i]['rangeDiscount'];
				}
				*/
				
				table2 += '%) <input type="text" name="discount_' + j[i]['optionId'] + '" rel="' + j[i]['optionId'] + '" id="discount_' + j[i]['optionId'] + '" class="fleet_discount" value="' + j[i]['discount'] + '"/> %' +
				' <span><a href="javascript:void(0);" class="fleet_dok" rel="' + j[i]['optionId'] + '">OK</a></span></td>';
				table2 += '<td>&pound;' + j[i]['price'] + '</td>';
				table2 += '<td>&pound;' + j[i]['vat'] +'</td>';
				table2 += '<td>&pound;' + j[i]['pricevat'] +'</td>';
				if(j[i]['finalprice']=='')
				{
					table2 += '<td class="delete"><span id="' + j[i]['optionId'] + '_price"><a href="javascript:void(0);" rel="' + j[i]['optionId'] + '" class="fleet_sprice" id="' + j[i]['optionId'] + '_link">';
					table2 += 'override price';
				}
				else
				{
					table2 += '<td class="delete"><span id="' + j[i]['optionId'] + '_price">&pound;<a href="javascript:void(0);" rel="' + j[i]['optionId'] + '" class="fleet_sprice" id="' + j[i]['optionId'] +'_link">';
					table2 += j[i]['finalprice'];
				}
				
				table2 += '</a></span>' +
				'<span id="' + j[i]['optionId'] + '_span" style="display: none;">&pound; <input type="text" class="fleet_finalprice" id="' + j[i]['optionId'] + '_finalprice" rel="' + j[i]['optionId'] + '"/><br /><a href="javascript:void(0);" class="fleet_ok" rel="' + j[i]['optionId'] + '">OK</a> - <a href="javascript:void(0);" class="fleet_cancel" rel="' + j[i]['optionId'] + '">CANCEL</a></span><span style="color: red;font-weight: bold;display:none;" id="span_mod_' + j[i]['optionId'] + '">(M)</span>';
				table2 += '<td class="delete">';
				if( j[i]['discount'] != 0 )
				{
					table2 += '<a href="javascript:void(0);" title="Delete discount" onclick="delete_discount(\'' + j[i]['optionId'] + '\');" ><img alt="" src="/resource/images/layout/delete-button.png" /></a>';
				}
				else
				{
					table2 += '&ndash;';
				}
				table2 += '</td>';
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#" + where).html(options);
			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/'+ $("#fleet_range option:selected").val()  +'/">edit</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options" value="Commit changes" onclick="javascript:offer_commit_changes_lcv(\'range_lcv\');"/>';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});

			$("a.fleet_sprice").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").hide();
				$("#" + id + "_span").show();
				$("#" + id + "_finalprice").focus();
			});

			$("a.fleet_cancel").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("a.fleet_dok").click( function() {
				//reset 32242_finalprice to ''
				var id = $(this).attr('rel');
				$("#" + id + "_finalprice").val('');
				if( isNaN( $("#discount_" + id).val() ) )
				{
					return;
				}

				$("#span_mod_" + id).show();
			});

			$("a.fleet_ok").click( function() {
				var id = $(this).attr('rel');
				var val = $("#" + id + "_finalprice").val();

				if(val == "0" || val=='' || isNaN(val))
				{
					return;
				}

				if(val != $("#" + id + "_link").text())
				{
					$("#" + id + "_link").html( $("#" + id + "_finalprice").val() + ' <span style="color: #FF0000;font-weight: bold;">(M)</span>');
				}
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("input.fleet_finalprice").keydown(function(j) {
				if(j.which == 27)
				{
					$("a.fleet_cancel[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}

				if(j.which == 13)
				{
					$("a.fleet_ok[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}
			});

		});
	});
}

function getNewCarDer_blcv(what, usr)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>title</th>';
		table2 += '<th>on the road price</th>';
		table2 += '<th>override</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		if(typeof usr == 'undefined')
		{
			usr = 0;
		}

		$.getJSON("/ajax.php", { op: "getNewModelsblcv", modID: what.value, usr:usr }, function(j) {
			for (var i = 0; i < j.length; i++) {
				table2 += '<tr id="' + j[i]['optionId'] + '">';
				table2 += '<td class="col1">' + j[i]['optionId'] + '</td>';
				table2 += '<td>' + j[i]['optionValue'] + '</td>';
				table2 += '<td>&pound;' + j[i]['price'] + '</td>';
				table2 += '<td>&pound; <input type="text" name="fleet_orp" rel="' + j[i]['optionId'] + '" class="fleet_orp" id="fleet_orp' + j[i]['optionId'] + '" style="width: 50px;"/></td>';
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer_fleet option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range_fleet option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/'+ $("#fleet_range option:selected").val()  +'/">edit</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options_fleet" value="Commit changes" onclick="javascript:offer_commit_changes_blcv(\'range_fleet\');"/>';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_fleet").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range_fleet").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
		});
	});
}

function getNewCarDer_fleet_blcv(what, usr)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>title</th>';
		table2 += '<th>on the road price</th>';
		table2 += '<th>override</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		if(typeof usr == 'undefined')
		{
			usr = 0;
		}

		$.getJSON("/ajax.php", { op: "getNewModelsBLCV", modID: what.value, usr:usr }, function(j) {
			for (var i = 0; i < j.length; i++) {
				table2 += '<tr id="' + j[i]['optionId'] + '">';
				table2 += '<td class="col1">' + j[i]['optionId'] + '</td>';
				table2 += '<td>' + j[i]['optionValue'] + '</td>';
				table2 += '<td>&pound;' + j[i]['price'] + '</td>';
				table2 += '<td>&pound; <input type="text" name="fleet_orp" rel="' + j[i]['optionId'] + '" class="fleet_orp" id="fleet_orp' + j[i]['optionId'] + '" style="width: 50px;"/></td>';
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer_fleet option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range_fleet option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/'+ $("#fleet_range option:selected").val()  +'/">edit</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options_fleet" value="Commit changes" onclick="javascript:offer_commit_changes_blcv(\'range_fleet\');"/>';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_fleet").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range_fleet").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
		});
	});
}

function getNewCarDer_fleet(what, usr)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>disabled</th>';
		table2 += '<th>title</th>';
		table2 += '<th>on the road price</th>';

		table2 += '<th>override</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		if(typeof usr == 'undefined')
		{
			usr = 0;
		}

		$.getJSON("/ajax.php", { op: "getNewModelsFleet", modID: what.value, usr:usr }, function(j) {
			for (var i = 0; i < j.length; i++) {
				table2 += '<tr id="' + j[i]['optionId'] + '">';
				table2 += '<td class="col1">' + j[i]['optionId'] + '</td>';

				table2 += '<td class="delete"><input type="checkbox"';
				
				if(j[i]['disabled'] == "1")
				{
					table2 += ' checked="checked"';
				}

				table2 += ' id="disabled_' + j[i]['optionId'] + '" onchange="disable_der_fleet(this);" rel="' + j[i]['optionId'] + '"/></td>';

				table2 += '<td>' + j[i]['optionValue'] + '</td>';
				table2 += '<td>&pound;' + j[i]['price'] + '</td>';

				table2 += '<td>&pound; <input type="text" name="fleet_orp" rel="' + j[i]['optionId'] + '" class="fleet_orp" id="fleet_orp' + j[i]['optionId'] + '" style="width: 50px;"/></td>';
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/'+ $("#fleet_range option:selected").val()  +'/">edit</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options_fleet" value="Commit changes" onclick="javascript:offer_commit_changes_fleet(\'range_fleet\');"/>';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer_fleet").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range_fleet").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});
		});
	});
}

function getNewCarDer_offers(what)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>Derivative name</th>';
		table2 += '<th>Available offer</th>';
		table2 += '<th>delete</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		$.getJSON("/ajax.php", { op: "getNewModels_offer", modID: what.value }, function(j) {
			var options = '<option value="All">All</option>';
			for (var i = 0; i < j.length; i++) {
				table2 += '<tr id="' + j[i]['cap_id'] + '">';
				table2 += '<td class="col1">' + j[i]['cap_id'] + '</td>';
				table2 += '<td>' + j[i]['name'] + ' ' + j[i]['bodytype'] + '</td>';
				if( j[i]['headline'] == "")
				{
					table2 += '<td><a href="/rrgadmin/offers/add/' + j[i]['cap_id'] + '">Add offer</a></td>';
				}
				else
				{
					table2 += '<td><a href="/rrgadmin/offers/view/' + j[i]['cap_id'] + '">' + j[i]['headline'] + '</a></td>';
				}

				if( j[i]['headline'] == "")
				{
					table2 += '<td>&nbsp;</td>';
				}
				else
				{
					table2 += '<td><a href="/rrgadmin/offers/delete/' + j[i]['cap_id'] + '">delete</a></td>';
				}
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});

			$("a.fleet_sprice").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").hide();
				$("#" + id + "_span").show();
				$("#" + id + "_finalprice").focus();
			});

			$("a.fleet_cancel").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("a.fleet_dok").click( function() {
				//reset 32242_finalprice to ''
				var id = $(this).attr('rel');
				$("#" + id + "_finalprice").val('');
				if( isNaN( $("#discount_" + id).val() ) )
				{
					return;
				}

				$("#span_mod_" + id).show();
			});

			$("a.fleet_ok").click( function() {
				var id = $(this).attr('rel');
				var val = $("#" + id + "_finalprice").val();

				if(val == "0" || val=='' || isNaN(val))
				{
					return;
				}

				if(val != $("#" + id + "_link").text())
				{
					$("#" + id + "_link").html( $("#" + id + "_finalprice").val() + ' <span style="color: #FF0000;font-weight: bold;">(M)</span>');
				}
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("input.fleet_finalprice").keydown(function(j) {
				if(j.which == 27)
				{
					$("a.fleet_cancel[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}

				if(j.which == 13)
				{
					$("a.fleet_ok[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}
			});

		});
	});
}

function getNewCarDer(what, where)
{
	var what = document.getElementById(what);

	if(what.value==0)
	{
		$("#" + where).html('<option value="All">All</option>');
		return;
	}

	$("#fleet_results").fadeTo("fast", 0.5, function() {
	$("#rrgfleet_box_details").hide();
	$("#rrgfleet_box_loading").show();

		var table2 = '<table cellpadding="0" cellspacing="0" border="0" id="enquiry_table">';
		table2 += '<thead>';
		table2 += '<tr>';
		table2 += '<th>id</th>';
		table2 += '<th>disabled</th>';
		table2 += '<th>title</th>';
		table2 += '<th>rd / discount</th>';
		table2 += '<th>price</th>';
		table2 += '<th>vat</th>';
		table2 += '<th>price+vat</th>';
		table2 += '<th>final price</th>';
		table2 += '<th>delete</th>';
		table2 += '</tr>';
		table2 += '</thead>';
		table2 += '<tbody>';

		$.getJSON("/ajax.php", { op: "getNewModels", modID: what.value }, function(j) {
			var options = '<option value="All">All</option>';
			for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionValue + '</option>';
				

				table2 += '<tr id="' + j[i]['optionId'] + '">';
				table2 += '<td class="col1">' + j[i]['optionId'] + '</td>';
				table2 += '<td class="delete"><input type="checkbox"';
				
				if(j[i]['disabled'] == "1")
				{
					table2 += ' checked="checked"';
				}

				table2 += ' id="disabled_' + j[i]['optionId'] + '" /></td>';
				table2 += '<td>' + j[i]['optionValue'] + '<br />' + j[i]['model'] + '</td>';
				table2 += '<td>(';


				table2 += j[i]['rangeDiscount'];
				/*
				if( j[i]['discount'] != 0)
				{
					table2 += '0';
				}
				else
				{
					table2 += j[i]['rangeDiscount'];
				}
				*/
				
				table2 += '%) <input type="text" name="discount_' + j[i]['optionId'] + '" rel="' + j[i]['optionId'] + '" id="discount_' + j[i]['optionId'] + '" class="fleet_discount" value="' + j[i]['discount'] + '"/> %' +
				' <span><a href="javascript:void(0);" class="fleet_dok" rel="' + j[i]['optionId'] + '">OK</a></span></td>';
				table2 += '<td>&pound;' + j[i]['price'] + '</td>';
				table2 += '<td>&pound;' + j[i]['vat'] +'</td>';
				table2 += '<td>&pound;' + j[i]['pricevat'] +'</td>';
				if(j[i]['finalprice']=='')
				{
					table2 += '<td class="delete"><span id="' + j[i]['optionId'] + '_price"><a href="javascript:void(0);" rel="' + j[i]['optionId'] + '" class="fleet_sprice" id="' + j[i]['optionId'] + '_link">';
					table2 += 'override price';
				}
				else
				{
					table2 += '<td class="delete"><span id="' + j[i]['optionId'] + '_price">&pound;<a href="javascript:void(0);" rel="' + j[i]['optionId'] + '" class="fleet_sprice" id="' + j[i]['optionId'] +'_link">';
					table2 += j[i]['finalprice'];
				}
				
				table2 += '</a></span>' +
				'<span id="' + j[i]['optionId'] + '_span" style="display: none;">&pound; <input type="text" class="fleet_finalprice" id="' + j[i]['optionId'] + '_finalprice" rel="' + j[i]['optionId'] + '" value="' + j[i]['finalprice'] + '"/><br /><a href="javascript:void(0);" class="fleet_ok" rel="' + j[i]['optionId'] + '">OK</a> - <a href="javascript:void(0);" class="fleet_cancel" rel="' + j[i]['optionId'] + '">CANCEL</a></span><span style="color: red;font-weight: bold;display:none;" id="span_mod_' + j[i]['optionId'] + '">(M)</span>';
				table2 += '<td class="delete">';
				if( j[i]['discount'] != 0 )
				{
					table2 += '<a href="javascript:void(0);" title="Delete discount" onclick="delete_discount(\'' + j[i]['optionId'] + '\');" ><img alt="" src="/resource/images/layout/delete-button.png" /></a>';
				}
				else
				{
					table2 += '&ndash;';
				}
				table2 += '</td>';
				table2 += '</tr>';
			}

			table2 += '</tbody></table>';

			$("#" + where).html(options);
			$("#fleet_results").html(table2);

			$("#fleet_results").fadeTo("slow", 1);
			$("#rrgfleet_box_loading").hide();
			$("#rrgfleet_box_details").show();

			$("tr").mouseover( function() {
				$(this).addClass("highlight");
			});
			$("tr").mouseout( function() {
				$(this).removeClass("highlight");
			});

			var txt = '<label>Manufacturer:</label> ' + $("#fleet_manufacturer option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_manufacturer">refresh</a>)';
			txt += '<br /><label>Range:</label> ' + $("#fleet_range option:selected").text();
			txt += ' (<a href="javascript:void(0);" id="refresh_range">refresh</a> - <a href="/rrgadmin/feed/new/range/'+ $("#fleet_range option:selected").val()  +'/">edit</a>)';
			txt += '<div class="fleet_settings" id="fleet_settings">';
			txt += '<input type="button" name="submit" id="submit_der_options" value="Commit changes" onclick="javascript:offer_commit_changes(\'range\');"/>';
			txt += '</div>';
			$("#rrgfleet_box_details").html(txt);

			$("a#refresh_manufacturer").click( function() {
				$("#fleet_manufacturer").trigger("change");
			});

			$("a#refresh_range").click( function() {
				$("#fleet_range").trigger("change");
			});

			$("#select_all").change( function() {
				$("#fleet_results INPUT[type='checkbox']").each( function(i, j) {
					$(j).attr('checked',$("#select_all").attr('checked'));
				});
			});

			$("a.fleet_sprice").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").hide();
				$("#" + id + "_span").show();
				$("#" + id + "_finalprice").focus();
			});

			$("a.fleet_cancel").click( function() {
				var id = $(this).attr('rel');
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("a.fleet_dok").click( function() {
				//reset 32242_finalprice to ''
				var id = $(this).attr('rel');
				$("#" + id + "_finalprice").val('');
				if( isNaN( $("#discount_" + id).val() ) )
				{
					return;
				}

				$("#span_mod_" + id).show();
			});

			$("a.fleet_ok").click( function() {
				var id = $(this).attr('rel');
				var val = $("#" + id + "_finalprice").val();

				if(val == "0" || val=='' || isNaN(val))
				{
					return;
				}

				if(val != $("#" + id + "_link").text())
				{
					$("#" + id + "_link").html( $("#" + id + "_finalprice").val() + ' <span style="color: #FF0000;font-weight: bold;">(M)</span>');
				}
				$("#" + id + "_price").show();
				$("#" + id + "_span").hide();
			});

			$("input.fleet_finalprice").keydown(function(j) {
				if(j.which == 27)
				{
					$("a.fleet_cancel[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}

				if(j.which == 13)
				{
					$("a.fleet_ok[@rel=" + $(this).attr('rel') + "]").trigger("click");
				}
			});

		});
	});
}

function leaveSite()
{
	
}

function newCarByMan()
{
	if( $("#manufacturer_new").val() == 0)
	{
		return;
	}
	
	var man = $("#manufacturer_new").val();
	
	// LW - check whether the user has selected Toyota. If so, this data is now off-site, so we need to
	// alert them that they are going to have to leave the site to get this information.
	if (man == 10519) {		
		
		Boxy.ask('Toyota new car information can be found on the RRG Toyota website.  Click OK to go there now, or cancel to return to the site', ['OK', 'Cancel'], function(v) {
            if (v == 'OK') {
				window.location.href = 'http://rrg.toyota.co.uk/cgi-bin/toyota/bv/generic_editorial.jsp?navRoot=toyotaDealers&dealerId=G00923&fullwidth=TRUE&sr=0&edname=SeeTheRangeFlash&catname=null&menuid=59779&zone=Zone+See+the+Range&id=D_new_cars';
			}
		}, {modal: true, closeable: false});
		
		// set the manuafacturer to null
		$("#manufacturer_new").val(0);
		return;
	}
	
	
	$("#manufacturer_new_cars").html('<option value="0">Please wait...</option>');

	$.getJSON('/ajax.php', { op:"getcarbymanid", man:man }, function(j) {
		var options= '<option value="All">All</option>';
		options += '<option value="0">&nbsp;</option>';
		for (var i = 0; i < j.length; i++) {
			if(j[i].disabled == "0")
			{
				options += '<option value="' + j[i].optionId + '">' + j[i].optionValue + '</option>';
			}
		}

		$("#manufacturer_new_cars").html(options);
	});
}

function newSearchForm()
{
	var manufacturer = document.getElementById("manufacturer_new");
	var model = document.getElementById("manufacturer_new_cars");

	if(manufacturer.value == 0 || model.value == 0)
	{
		alert("Please select a manufacturer and a model first.");
		return;
	}

	var man = $("#manufacturer_new option:selected").text();
	var mod = $("#manufacturer_new_cars option:selected").text();
	var prange = $("#manufacturer_new_prange option:selected").val();

	window.location.href = '/search/new-' + man + '-cars/' + mod + '/' + prange + '/';
}

function usedSearchForm()
{
	var manufacturer = document.getElementById("manufacturerselect");
	var model = document.getElementById("model");
	var prange = document.getElementById("prange");

	if(manufacturer.value == 0)
	{
		alert("Please select a manufacturer first.");
		return;
	}

	var nmodel = model.value.replace(/\s+/g,'+');
	window.location.href = '/search/used-' + manufacturer.value + '-cars/' + model.value + '/' + prange.value + '/';
}

function submitform()
{
	if( confirm("Are you sure you want to submit this form?") )
	{
		tinyMCE.triggerSave();
		return true;
	}
	else
	{
		return false;
	}
}

function addToShowroom(carID)
{
	$.getJSON('/ajax.php', { op:"showroom", ac:"add", car:carID }, function(res) {
		if(res.error != 0)
		{
			alert(res.msg);
		} else {
			window.location.reload();
		}
	});
}

function removeFromShowroom(carID)
{
	$.getJSON('/ajax.php', { op:"showroom", ac:"delete", car:carID }, function(res) {
		if(res.error != 0)
		{
			alert(res.msg);
		}
	});
}

function emptyShowroom()
{
	$.getJSON('/ajax.php', { op:"showroom", ac:"empty" }, function(res) {
		if(res.error == 0)
		{
			alert("Your showroom has been emptied.");
			//empty showroomn:
			$("#resultenc").fadeOut("slow");
		}
		else
		{
			alert(res.msg);
		}
	});
}

function compareAgain(num)
{
	var params = '';
	for(i=1;i<=4;i++)
	{
		if(i == num)
		{
			//get value from select
			params += document.getElementById("select_" + i).value;
			$("div#" + document.getElementById("select_" + i).value).trigger("click");
		}
		else
		{
			//get value from div
			params += document.getElementById("slot_" + i).firstChild.nodeValue;
		}

		if(i<4)
		{
			params += ':';
		}
	}

	compareCars(params);
}

//determine info
function beginCompare()
{
	var elems = $("#my-cars-view").children(".car-selected");
	var params = '';

	$.each(elems, function(i, n) {
		params += n.id + ':';
	});

	if(params.length==0)
	{
		//return;
	}

	for(var i=elems.length;i<4;i++)
	{
		params += 'empty:';
	}

	//compareCars(params, allcars);
	compareCars(params);
}

function compareCars(params)
{

	$.get('/ajax.php', { op:"compare", params: params }, function(data) {
		$("#my-cars-compared-view").html(data);
	});
}

	//replace all images of rel=newcar_result with http://.....id
/*
	if( document.getElementById("edit-body") )
	{
		replaceAdminText();
		$(".editable_textarea").editable( function(value, settings) {
				document.getElementById("edit-body").value = value;
				return value;
			}, {
			type      : 'textarea',
			cancel    : 'Cancel',
			submit    : 'OK',
			indicator : "<img src='img/indicator.gif'>",
			tooltip   : '',
			callback : function (value, settings) {
				$("#edit-body").val( $("#msg-enclosure").html() );
			}
		});
	}
*/

//Toyota External Links CODE
$().ready(function() {
	
	$("a.external").bind("click", function(event, i) {
		
		Boxy.ask('Toyota new car information can be found on the RRG Toyota website.  Click OK to go there now, or cancel to return to the site...', ['OK', 'Cancel'], function(v) {
            if (v == 'OK') {
				
				tagname = event.target.nodeName.toLowerCase();				
				if (tagname == 'a') {
					window.location.href = event.target.href;	
				} else {
					// it must be the image that initiated the event. currentTarget ought to
					// be what we're after, but this misbehaves in IE - so let's use the parent					
					//window.location.href = event.target.parent().href;
					if(navigator.appName == "Microsoft Internet Explorer") {
						window.location.href = $(event.target).parent().attr('href');
					} else {
						window.location.href = event.currentTarget.href;
					}
				}
			} else {
			 	function disablelink(e){
				 var evt=window.event || e
				 if (evt.preventDefault) //supports preventDefault?
				  evt.preventDefault()
				 else //IE browser
				  return false
				}
			}
		}, {modal: false, closeable: false});
		
		
		return false;
	});

});
