/*
UI Nano rotation using jQuery, jQuery Cycle Plugin, and jQuery Brokenimage Plugin

HISTORY
	090331
		Started and completed initial lid work on functionality for HES dealers.
		Reworked functionality for rigged MySource and Expert lids.
	090331
		Added improvements for HES navigation
*/

// Get banners
function uinano(name, loc, obj)
{
	// Default variables
	var defaults = {
		delay : 7500, 
		speed : 500, 
		timeout : 180000, 
		categories : "", 
		brands : "", 
		dealer : "", 
		package : "", 
		strict : false, 
		hes : false, 
		replaceOld : "/rss/", 
		replaceNew : "/tsv/", 
		dataDivCategories : "uinano_categories", 
		dataDivBrands : "uinano_brands", 
		dataDivDealer : "uinano_dealer", 
		dataDivPackage : "uinano_package", 
		dataDivStrict : "uinano_strict", 
		dataDivHes : "uinano_hes", 
		pause : true, 
		brokenimage : "http://images.brandsource.com/_layouts/images/UINano/broken_image.png", 
		xmlfault : "http://images.brandsource.com/_layouts/images/UINano/broken_image.png", 
		domain : "brandsource.com",  
		local : ["file://", "brandsource.com"], 
		proxy : "/proxy.aspx?url=", 
		method : "GET", 
		contenttype : "text/plain", 
		dataformat : "text", 
		cache : false, 
		datesplit : "-", 
		catOrig : "", 
		rigFind : "_View", 
		rigInsert : "_Rig", 
		rigHes : "_HES", 
		rigMySourceFind: "/Lid_MySource", 
		rigExpertFind: "/Lid_Expert", 
		limit: 2, 
		test: false
	}
	// Pull in text from divs
	defaults.categories = jQuery.trim($("#" + defaults.dataDivCategories).text().toLowerCase());
	defaults.brands = jQuery.trim($("#" + defaults.dataDivBrands).text().toLowerCase());
	defaults.dealer = jQuery.trim($("#" + defaults.dataDivDealer).text().toLowerCase());
	defaults.package = jQuery.trim($("#" + defaults.dataDivPackage).text().toLowerCase());
	defaults.strict = jQuery.trim($("#" + defaults.dataDivStrict).text().toLowerCase());
	defaults.hes = jQuery.trim($("#" + defaults.dataDivHes).text().toLowerCase());
	// Fix booleans
	defaults.strict = (defaults.strict == "1" || defaults.strict == "true") ? true : false;
	defaults.hes = (defaults.hes == "1" || defaults.hes == "true") ? true : false;
	// Set cross-domain
	uinano_domain(defaults.domain);
	// Origional Categories
	defaults.catOrig = defaults.categories;
	// Default object in case nothing is passed
	obj = obj || {};
	// Apply new values
	jQuery.each(obj, function(i, val)
	{
		defaults[i] = val;
	});
	$(document).ready(function ()
	{
		// Fix the navigation for the dealers
		package(defaults.package, defaults.categories, defaults.catOrig, defaults.dealer, defaults.hes);
	});
	// Local proxy
	if(jQuery.url.setUrl(document.location).attr("protocol") == "file")
	{
		defaults.proxy = "";
	}
	// Load the TSV instead of the RSS
	if(loc.indexOf(defaults.replaceOld) != -1)
	{
		var begin = loc.slice(0, loc.indexOf(defaults.replaceOld));
		var end = loc.slice(loc.indexOf(defaults.replaceOld) + defaults.replaceOld.length);
		loc = begin + defaults.replaceNew + end;
	}
	// Secure pages
	loc = securePage(loc);
	// Add div and location to defaults
	defaults.div = name;
	defaults.location = uinano_proxy(loc, defaults.proxy, defaults.local);
	// Rig the MySource and Experts lids for Basic and Bronze
	var pkg = defaults.package.split(",");
	var basicbronze = (jQuery.inArray("basic", pkg) != -1 || jQuery.inArray("bronze", pkg) != -1) ? true : false;
	// Rigged
	var beginR = loc.slice(0, loc.indexOf(defaults.rigFind));
	var endR = loc.slice(loc.indexOf(defaults.rigFind));
	var locR = beginR + defaults.rigInsert + endR;
	if(locR.indexOf(defaults.rigInsert + defaults.rigInsert) != -1)
	{
		locR = loc;
	}
	var riggedView = (loc.toLowerCase() != locR.toLowerCase()) ? false : true;
	var rigged = (loc.toLowerCase().indexOf(defaults.rigMySourceFind.toLowerCase()) != -1 || loc.toLowerCase().indexOf(defaults.rigExpertFind.toLowerCase()) != -1) && basicbronze && !riggedView;
	// HES
	var beginH = loc.slice(0, loc.indexOf(defaults.rigFind));
	var endH = loc.slice(loc.indexOf(defaults.rigFind));
	var locH = beginH + defaults.rigHes + endH;
	if(locH.indexOf(defaults.rigHes + defaults.rigHes) != -1 || locH.indexOf(defaults.rigHes + defaults.rigInsert) != -1)
	{
		locH = loc;
	}
	// Continue
	if(defaults.hes && loc != locH)
	{
		uinano(name, locH, obj);
	}
	else if(rigged && !defaults.hes)
	{
		uinano(name, locR, obj);
	}
	else
	{
		uinano_call(defaults);
	}
}


// Retrieve XML
function uinano_call(obj)
{
	// Get XML
	jQuery.ajax({
		cache: obj.cache, 
		type: obj.method, 
		dataType: obj.dataformat, 
		contentType: obj.contenttype, 
		url: obj.location, 
		timeout: obj.timeout, 
		error: function(xhrObj, textStatus, errorThrown)
		{
			uinano_fault(obj.div, obj.xmlfault, xhrObj, textStatus, errorThrown);
		}, 
    	success: function(data)
		{
			uinano_result(obj, data);
		}
	});
}


// Fault
function uinano_fault(div, img, xhrObj, textStatus, errorThrown)
{
	// Clear the div
	$("#" + div).empty();
	// Background image
	uinano_background(div, img);
}


// Result
function uinano_result(obj, data)
{
	// Split data
	data = data.split("\n");
	// Titles from first row
	var titles = data[0].split("\t");
	// Remove first and last items
	data.remove(0);	// titles
	data.remove(data.length - 1);	// Blank line
	// Parse data to array collection
	var banners = [];
	jQuery.each(data, function(i, val)
	{
		var b = {};
		jQuery.each(val.split("\t"), function(i2, val2)
		{
			b[titles[i2]] = jQuery.trim(val2);
		});
		banners.push(b);
	});
	// Valid dates
	banners = uinano_date(banners, obj.datesplit);
	// Valid categories
	banners = uinano_categories(banners, obj.categories);
	// Valid brands
	banners = uinano_brands(banners, obj.brands);
	// Valid dealer
	banners = uinano_dealer(banners, obj.strict, obj.dealer);
	// Shuffle array
	banners = uinano_shuffle(banners);
	// Limit results
	if(banners.length > obj.limit)
	{
		banners = $(banners).slice(0, obj.limit);
	}
	// Empty div
	$("#" + obj.div).empty();
	// Only run the code if there is one or more banners
	if(banners.length != 0)
	{
		// If delay is 0, only add first banner in order to save bandwidth
		if(obj.delay == 0)
		{
			uinano_add(obj.div, banners[0], obj.dealer);
		}
		// If delay is not 0, add all banners
		else
		{
			jQuery.each(banners, function(i)
			{
				uinano_add(obj.div, banners[i], obj.dealer);
			});
			// Create rotation
			$("#" + obj.div).cycle(
			{
				next: "#" + obj.div + "_next", 
				prev: "#" + obj.div + "_prev", 
				timeout: obj.delay, 
				speed: obj.speed, 
				pause: obj.pause 
			});
		}
	}
	// Replace broken images
	uinano_replace(obj.div, obj.brokenimage, obj.timeout);
}


// Apply banners
function uinano_add(div, content, dlr, w, h)
{
	// No location
	if(content.location == undefined)
	{
		content.location = "";
	}
	// Rig the link for the testing pages
	content.location = testing(content.location, dlr);
	// Replace space in url with %20
	content.location = content.location.replace(" ", "%20");
	// Make (or don't make) clicks
	var linkClick = (content.location.toLowerCase().indexOf("/promotional%20pages/") == -1) ? "" : "onClick=\"javascript:openModal('" + content.location + "'); return false;\" target=\"_blank\"";
	// Rig promotions for dealers
	if(linkClick.length != 0 && content.location.indexOf(".brandsource.") == -1)
	{
		content.location = "http://www.brandsource.com" + content.location;
	}
	// Target
	var linkTarget = (content.location.toLowerCase().indexOf("gemoneyredirect.htm") != -1) ? "target='_blank'" : "";
	// Make (or don't make) links
	var linkStart = (content.location.length == 0) ? "" : "<a href=\"" + content.location + "\" " + linkClick + " " + linkTarget + ">";
	var linkEnd = (content.location.length == 0) ? "" : "</a>";
	// Create the div
	var data = "<div>" + linkStart + "<img src='" + securePage(content.image) + "' alt='" + content.alt + "' title='" + content.alt + "' border='0'>" + linkEnd + "</div>";
	$("#" + div).append(data)
}


// Validate dates
function uinano_date(b, sp)
{
	var remove = [];
	// Current date/time
	var now = new Date();
	// Loop to find items to remove
	jQuery.each(b, function(i, val)
	{
		var s = (val.startdate == undefined) ? "" : val.startdate;
		var startSplit = s.split(sp);
			var start = (s.length == 0) ? now : new Date(startSplit[2], uinano_month(startSplit[1]), startSplit[0]);
		var e = (val.enddate == undefined) ? "" : val.enddate;
		var endSplit = e.split(sp);
			var end = (e.length == 0) ? now : new Date(endSplit[2], uinano_month(endSplit[1]), endSplit[0], 23, 59, 59);
		if(now.getTime() < start.getTime() || now.getTime() > end.getTime())
		{
			remove.push(i);
		}
	});
	
	// Remove banners
	jQuery.each(remove.reverse(), function(i, val)
	{
		b.remove(val);
	});
	return b;
}


// Validate categories
function uinano_categories(b, vals)
{
	// Remove white space from items
	vals = vals.split(",");
	jQuery.each(vals, function(i, val)
	{
		vals[i] = jQuery.trim(val);
	});
	// Array
	var remove = [];
	// Loop to find items to remove
	jQuery.each(b, function(i, val)
	{
		var c = (val.category == undefined) ? "" : val.category;
		if(vals.toString().length != 0 && c.length != 0 && jQuery.inArray(c.toLowerCase(), vals) == -1)
		{
			remove.push(i);
		}
	});
	// Remove banners
	jQuery.each(remove.reverse(), function(i, val)
	{
		b.remove(val);
	});
	return b;
}

// Validate brands
function uinano_brands(b, vals)
{
	// Remove white space from items
	vals = vals.split(",");
	jQuery.each(vals, function(i, val)
	{
		vals[i] = jQuery.trim(val);
	});
	// Array
	var remove = [];
	// Loop to find items to remove
	jQuery.each(b, function(i, val)
	{
		var c = (val.brand == undefined) ? "" : val.brand;
		if(vals.toString().length != 0 && c.length != 0 && jQuery.inArray(c.toLowerCase(), vals) == -1)
		{
			remove.push(i);
		}
	});
	// Remove banners
	jQuery.each(remove.reverse(), function(i, val)
	{
		b.remove(val);
	});
	return b;
}

// Validate dealer
function uinano_dealer(b, strict, vals)
{
	var remove = [];
	// Loop to find items to remove
	jQuery.each(b, function(i, val)
	{
		var d = (val.dealer == undefined) ? "" : val.dealer;
		// Strict mode
		if(strict && jQuery.inArray(d.toLowerCase(), vals.split(",")) == -1)
		{
			remove.push(i);
		}
		// Not strict mode
		else
		{
			var common = ((vals == "" && d == "national") || (vals != "" && d == "dealers")) ? false : true;
			if(d.length != 0 && jQuery.inArray(d.toLowerCase(), vals.split(",")) == -1 && common)
			{
				remove.push(i);
			}
		}
	});
	// Remove banners
	jQuery.each(remove.reverse(), function(i, val)
	{
		b.remove(val);
	});
	return b;
}


// Get Month number
function uinano_month(m)
{
	var monthArray = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	return jQuery.inArray(m, monthArray);
}


// Apply proxy
function uinano_proxy(loc, prox, local)
{
	var p = prox;
	// Check if data is coming from local source
	jQuery.each(local, function(i, val)
	{
		if(loc.toLowerCase().indexOf(val.toLowerCase()) != -1)
		{
			p = "";
		}
	});
	prox = p + loc;
	// Add proxy
	return prox;
}


// Shuffle array
function uinano_shuffle(arr)
{
	for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
	return arr;
}


// CSS background image
function uinano_background(div, img)
{
	$("#" + div).css("background-image", "url(" + img + ")"); 
}


// Replace broken images
function uinano_replace(div, img, to)
{
	$("#" + div + " img").brokenImage({replacement:img, timeout: to});
}


// Set domain for cross-domain functionality
function uinano_domain(value)
{
	if(value.length != 0)
	{
		$(document).domain = value;
	}
}


// Remove item from array
Array.prototype.remove = function(from, to)
{
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
}


// Unique values
Array.prototype.uinano_unique = function()
{
	var o = new Object();
	var i, e;
	for(i = 0; e = this[i]; i++)
	{
		o[e] = 1
	};
	var a = new Array();
	for(e in o)
	{
		a.push (e)
	};
	return a;
}

// Rig for testing pages
function testing(loc, dealer)
{
	if(loc.slice(0, 1) == "/" && loc.toLowerCase().indexOf("/dealers/") == -1 && dealer.length != 0 && document.location.toString().toLowerCase().indexOf("www.") != -1)
	{
		return "/Dealers/" + dealer + loc;
	}
	return loc;
}

// Rig for IE secure pages
function securePage(loc)
{
	if(jQuery.url.setUrl(loc).attr("protocol") != null && jQuery.url.setUrl(document.location).attr("protocol") == "https")
	{
		loc = jQuery.url.setUrl(document.location).attr("protocol") + "://" + jQuery.url.setUrl(loc).attr("host") + ((!jQuery.url.setUrl(loc).attr("port")) ? "" : ":" + jQuery.url.setUrl(loc).attr("port")) + jQuery.url.setUrl(loc).attr("relative");
	}
	return loc;
}

$.log = function(){
	if(window.console && window.console.log)
	{
		window.console.log(Array.prototype.join.call(arguments, ''));
	}
};







/*
* Filter navigation based on package
*/

// Package
function navigation(pkg, cat, dlr, h)
{
	// Parse divs
	var pack = jQuery.trim(pkg.toLowerCase());
	var categories = jQuery.trim(cat.toLowerCase());
	var dealer = jQuery.trim(dlr.toLowerCase());
	var hes = jQuery.trim(h.toLowerCase());
		hes = (hes == "1" || hes == "true") ? true : false;
	// Call function
	package(pack, categories, categories, dealer, hes);
}






/*
* Filter navigation based on package
*/

// Package
function package(pkg, cat, catOrig, dlr, hes)
{
	// Hide appliances or electronics if nessisary
	var e = {div:"147003", category:"electronics", divider:"0147002", shoppingcartlink:"link_shopping_electronics", wishlistlink:"wishlist_electronics", shoppingcartlink2:".shopping_cart_body .link_shopping:eq(1)"};
	var a = {div:"147002", category:"appliances", divider:"0147001", shoppingcartlink:"link_shopping_appliances", wishlistlink:"wishlist_appliances", shoppingcartlink2:".shopping_cart_body .link_shopping:eq(0)"};	
	package_category(catOrig, a, e);
	// Force hide for subsites
	if(pkg.length != 0)
	{
		// Hide sitemap
		$("#footer_sitemap").hide();
			$("#footer_divider_1").hide();
		// Hide sitemap
		$("#footer_community").hide();
			$("#footer_divider_2").hide();
		// Hide store locator
		$("#head_locatestore").hide();
		// Hide 'Content Your Nearest Store' in MySource
		$(".rightnav_link_01:last").hide();
	}
	// HES
	if(hes)
	{
		// Header nav
		$("#147005").hide();
			$("#0147004").hide();
		$("#147007").hide();
			$("#0147006").hide();
		// Footer nav
		$("#footer_community").hide();
			$("#footer_divider_2").hide();
		$("#footer_joinbrandsource").hide();
			$("#footer_divider_7").hide();
		$("#footer_membersonly").hide();
			$("#footer_divider_8").hide();
		return;
	}
	// Hide navigation based on package
	switch(pkg)
	{
		case "basic": 
			// Header nav
			$("#147004").hide();
				$("#0147003").hide();
			$("#147005").hide();
				$("#0147004").hide();
			$("#147006").hide();
				$("#0147005").hide();
			$("#147007").hide();
				$("#0147006").hide();
			// Footer nav
			$("#footer_community").hide();
				$("#footer_divider_2").hide();
			$("#footer_customerservice").hide();
				$("#footer_divider_4").hide();
			$("#footer_contactus").hide();
				$("#footer_divider_6").hide();
			$("#footer_joinbrandsource").hide();
				$("#footer_divider_7").hide();
			$("#footer_membersonly").hide();
				$("#footer_divider_8").hide();
			break;
		case "bronze": 
			// Header nav
			$("#147004").hide();
				$("#0147003").hide();
			$("#147005").hide();
				$("#0147004").hide();
			$("#147007").hide();
				$("#0147006").hide();
			// Footer nav
			$("#footer_community").hide();
				$("#footer_divider_2").hide();
			$("#footer_joinbrandsource").hide();
				$("#footer_divider_7").hide();
			$("#footer_membersonly").hide();
				$("#footer_divider_8").hide();
			break;
		case "silver":
			// Header nav
			$("#147004").hide();
				$("#0147003").hide();
			// Footer nav
			$("#footer_joinbrandsource").hide();
				$("#footer_divider_7").hide();
			$("#footer_membersonly").hide();
				$("#footer_divider_8").hide();
			break;
		case "gold": 
			// Header nav
			// all visible
			// Footer nav
			$("#footer_joinbrandsource").hide();
				$("#footer_divider_7").hide();
			$("#footer_membersonly").hide();
				$("#footer_divider_8").hide();
			break;
		case "goldnoms": 
			// Header nav
			$("#147005").hide();
				$("#0147004").hide();
			$("#147007").hide();
				$("#0147006").hide();
			// Footer nav
			$("#footer_joinbrandsource").hide();
				$("#footer_divider_7").hide();
			$("#footer_membersonly").hide();
				$("#footer_divider_8").hide();
			break;
		default:  
			// National site. Display everything
	}
}


// Package categories
function package_category(catOrig, a, e)
{
	// Remove white space from items
	catOrig = catOrig.split(",");
	jQuery.each(catOrig, function(i, val)
	{
		catOrig[i] = jQuery.trim(val);
	});
	// Remove navigation
	jQuery.each(new Array(a, e), function(i, val)
	{
		if(catOrig.toString().length != 0 && jQuery.inArray(val.category, catOrig) == -1)
		{
			$("#" + val.div).hide();
			if(val.divider)
			{
				$("#" + val.divider).hide();
				$("#" + val.shoppingcartlink).hide();
				$("#" + val.wishlistlink).hide();
				$(val.shoppingcartlink2).hide();
			}
		}
	});
}






/*
* Modals
*/

function openModal_OLD(value)
{
	$.floatbox({
        content: "<iframe id='bs_" + new Date().getTime() + "' src='" + value + "' width='740' height='550' scrolling='auto' frameborder='0'></iframe>", 
		boxConfig : {
			width: "740px",
			marginLeft: "-370px"
		}
    });
}

function videoWindow(value, options)
{
	var now = new Date().getTime();
	$.floatbox({
		content: "<div id='bs_" + now + "' class='player'></div>", 
		boxConfig : {
			width: "400px",
			marginLeft: "-200px"
		}
	});
	// Add video
	var opt = $.extend({}, { video: value }, options);
	$("#bs_" + now).videoplayer(opt);
}






/*
* jQuery URL Parser 1.0
* http://projects.allmarkedup.com/jquery_url_parser/
*/

jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();






/*
* jQuery Floatbox Plugin 1.0.7
* Copyright (c) 2008 Leonardo Rossetti (motw.leo@gmail.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function ($) {
	$.floatbox = function (options) {
		//support for jquery 1.0 request by christoph@breidert.net
		var getWidth = function () {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var width;
			if (version > 1) {
				width = $(window).width();
			} else {
				width = document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth;
			}
			return width / 2;
		};
		
		var settings = $.extend(true, {
			bg : "floatbox-background",
			box : "floatbox-box",
			content : "",
			button: "<div style='padding:3px; text-align:right;'><a role='button' href='javascript:void(0);' class='close-floatbox' title='Close window'>Close</a></div>",
			desc: "This is a popup box, press esc key to close.",
			fade : false,
			ajax: null,
			bgConfig : {
				position: ($.browser.msie) ? "absolute" : "fixed",
				zIndex: 8000,
				width: "100%",
				height: "100%",
				top:  "0px",
				left: "0px",
				backgroundColor: "#000",
				opacity: "0.75",
				display: "none"
			},
			boxConfig : {
				position : ($.browser.msie) ? "absolute" : "fixed",
				zIndex: 8001,
				width: getWidth() + "px",
				marginLeft: "-" + (getWidth() / 2) + "px",
				height: "auto",
				top: "50%",
				left: "50%",
				backgroundColor: "#fff",
				display: "none"
			}
		}, options);

		//inserts floatbox and sets its content
		var showBox = function () {
			var content = typeof settings.content === "string" ? settings.content : settings.content.clone();
			//inserts the background element in the document
			$("<div></div>")
				.bind("click", function () {
					closeBox();
				})
				.attr("id", settings.bg)
				.css(settings.bgConfig)
				.width(($.browser.msie) ? document.body.clientWidth : "100%")
				.height(($.browser.msie) ? document.body.clientHeight : "100%")
				.appendTo("body");
			//inserts the floating box in the document
			$("<div></div>")
				.attr({id: settings.box, role: "alertdialog"}) 
				.html(content)
				.append(settings.button)
				.css(settings.boxConfig)
				.appendTo("body")
				.css("margin-top", "-" + $("#" + settings.box).height() / 2 + "px")
				.find(".close-floatbox").bind("click", function () {
					closeBox();
				})
				.end();
			//checks if it needs to fade or not
			if (settings.fade) {
				$("#" + settings.bg)
				.fadeIn(200, function () {
					$("div#" + settings.box).fadeIn(200);
				});
			} else {
				$("#" + settings.bg)
				.show()
				.parent().find("#" + settings.box).show();
			}
			//sets if ajax is needed(already detectets if it is POST or GET)
			if (settings.ajax) {
				$.ajax({
					type: settings.ajax.params === "" ? "GET" : "POST",
					url: settings.ajax.url,
					data: settings.ajax.params,
					
					beforeSend: function () {
						$("#" + settings.box).html(settings.ajax.before);
					},
					
					success: function (data) {
						$("#" + settings.box)
							.html(data)
							.append(settings.button)
							.find(".close-floatbox").bind("click", function () {
								closeBox()
							})
						.end();
						
					},
					complete: function (XMLHttpRequest, textStatus) {
						if (settings.ajax.finish) {
							settings.ajax.finish(XMLHttpRequest, textStatus);
						}
					},
					contentType: "html"
				});
			}
		};
		//hides floatingbox and background
		var closeBox = function () {
			if (settings.fade) {
				$("#" + settings.box).fadeOut(200, function () {
					 $("#" + settings.bg).fadeOut(200, function () {
						$("#" + settings.box).remove();
						$("#" + settings.bg).remove();
					});
				});
			} else {
				//for opera issues hide first and a timeout is needed to remove the elements
				$("#" + settings.box + ",#" + settings.bg).hide();
				setTimeout(function () {
					$("#" + settings.box).remove();
					$("#" + settings.bg).remove();
				}, 500);
			}
		};
		//inits the floatbox
		var init = function () {
			//shows box
			showBox();
			//adds cross browser event to esc key to hide floating box
			$(document).one("keypress", function (e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			})
			.one("keydown", function (e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			});
			//if msie6, adds event to browser scroll to keep floatbox ina fixed position and uses css hack for full background size
			if ($.browser.msie) {
				$("body, html").css({height: "100%", width: "100%"});
				$(window).bind("scroll", function () {
					$("#" + settings.box).css("top", document.documentElement.scrollTop +  ($(window).height() / 2) + "px");
				});
			}
		};
		//starts the plugin
		init();
	};
})(jQuery);