// Array Remove - By John Resig (MIT Licensed)
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);
};



var SnapDraft = {
	
	in_frame : false,
	is_facebook : false,
	ie : false,
	currentContest : null,
	currentGame : 'ALL',
	currentBalance : 0.00, //balance at start, will be set at page level.
	runningBalance : 0.00, //balance we are running on the given page, will dynamically change based on selections
	currentContestPane : false,
	initialCallBackTime : 30,
	retrievalMethod : 'all',
	callBackMethod : true,
	jsonHandler : '/includes/js/json_handler.php',
	selectedAlternateContests : new Array(),
	errorMessages : {
		insufficientFunds : {message : 'Sorry, but it appears you do not have enough money on your account to participate in that contest. \n\nClick OK if you would like to add some additional funds to your account now.', type : 'confirm', handler : { ok : 'add_funds.php', cancel : ''}},
		contestFull : {message : 'Sorry, but that contest is now filled.', type : 'message'},
		general : {message : 'Sorry, but there was an unknown error. Please try again. ', type : 'message'}
	},
	URLs : {
		loadStandings : "get_standings.php",
		updateCC : 'https://secure4.fanball.com/snapdraft/update_cc.php',
		addFunds : '/add_money.php?height=340',
		myAccount : '/my_account.php',
		myContests : '/my_contests.php',
		rules : '/rules.php',
		contactUs : '/contact_us.php',
		memberStandings : '/member_standings.php',
		affiliate : '/affiliates.php',
		viewContest : '/view_contest.php?cid=',
		goToContest : '/{league}/pick_winner.php?contest={id}',
		goToLiveScoring : '/{league}/livescoring.php?contest={id}',
		goToResults : '/results_contest.php?contest_id={id}',
		goToLiveDraft : '/livedraft/makedraftlist.php?contest={id}',
		Contest : {
			editLineup : '/{league}/pick_winner.php?contest={id}'
		}
	},
	games : {
		NFL : 605,
		NBA : 606,
		NHL : 607,
		MLB : 608,
		NFL_NBA_NHL : 631,
		NASCAR_NBA : 633
	},
	Facebook : {
		query_string : null,
		init : function(){
			SnapDraft.is_facebook = true;
			if(this.query_string != null){
				SnapDraft.jsonHandler = SnapDraft.jsonHandler + "?"+this.query_string;
				SnapDraft.URLs.addFunds = SnapDraft.URLs.addFunds + "?"+this.query_string;
				SnapDraft.URLs.loadStandings = SnapDraft.URLs.loadStandings +"?"+this.query_string;
				SnapDraft.URLs.goToContest = SnapDraft.URLs.goToContest + "&"+this.query_string;
				SnapDraft.URLs.goToLiveScoring = SnapDraft.URLs.goToLiveScoring + "&"+this.query_string;
				SnapDraft.URLs.goToResults = SnapDraft.URLs.goToResults + "&"+this.query_string;
				SnapDraft.URLs.goToLiveDraft = SnapDraft.URLs.goToLiveDraft + "&"+this.query_string;
				SnapDraft.URLs.Contest.editLineup = SnapDraft.URLs.Contest.editLineup +"&"+this.query_string;
			}
		}
	},
	refreshCookies : function(){
		jQuery.getJSON(SnapDraft.jsonHandler, {op: 'refresh-cookies'}, function(request){
			if(request.status){
				//success.
				jQuery(".balance").html(request.balance);
				jQuery("#myteams_holder").html(request.teams_dropdown); 
				jQuery("#myteams").bind("change",function(){
					var val = jQuery(this).val();
					if(val != ""){
						var vals = val.split("|");
						//temp fix DRS++
						if(vals[0].toLowerCase() == "mlb-draft"){
							url = SnapDraft.URLs.goToLiveDraft.replace("{league}", vals[0]);
							url = url.replace("{id}", vals[1]);
							document.location.href = url;
						}else{
							
							if(vals[2] == 1){
								//edit lineup
								url = SnapDraft.URLs.goToContest.replace("{league}", vals[0]);
								url = url.replace("{id}", vals[1]);
								document.location.href = url;
							}else if(vals[2] == 2){
								//live scoring
								url = SnapDraft.URLs.goToLiveScoring.replace("{league}", vals[0]);
								url = url.replace("{id}", vals[1]);
								document.location.href = url;
							}else{
								//results
								//DRS + mod, fix for playoff football... needs to be re-worked FIXME
								url = SnapDraft.URLs.goToResults.replace("{league}", vals[0]);
								url = url.replace("{id}", vals[1]);
								document.location.href = url;
							}
						}
					}
				});
			}else{
				//failed.
				//do nothing
			}
		});
	},
	initialize : function(){
		jQuery("#lb_wins_toggler").bind('click', function(){
			document.location.href="/member_standings.php";
		});
		jQuery("#lb_money_toggler").bind('click', function(){
			document.location.href="/member_standings.php";
		});
		jQuery("#myteams").bind("change",function(){
			var val = jQuery(this).val();
			if(val != ""){
				var vals = val.split("|");
				if(vals[0].toLowerCase() == "mlb-draft"){
					url = SnapDraft.URLs.goToLiveDraft.replace("{league}", vals[0]);
					url = url.replace("{id}", vals[1]);
					document.location.href = url;
				}else{
					
					if(vals[2] == 1){
						//edit lineup
						url = SnapDraft.URLs.goToContest.replace("{league}", vals[0]);
						url = url.replace("{id}", vals[1]);
						document.location.href = url;
					}else if(vals[2] == 2){
						//live scoring
						url = SnapDraft.URLs.goToLiveScoring.replace("{league}", vals[0]);
						url = url.replace("{id}", vals[1]);
						document.location.href = url;
					}else{
						//results
						//DRS + mod, fix for playoff football... needs to be re-worked FIXME
						url = SnapDraft.URLs.goToResults.replace("{league}", vals[0]);
						url = url.replace("{id}", vals[1]);
						document.location.href = url;
					}
				}
			}
		});
		var fromLeft = jQuery(document).width()/2 - 370;
		var fromTop = 400;
		var zIndex = 2000;
		
		jQuery(".contestPopup").click
		(
			function(e) 
			{ 
				var c = jQuery(this).attr('id').split("_");
				var cid = c[1];
				var pop = window.open(SnapDraft.URLs.viewContest+cid+"&as_popup=1", "_view"+cid, "width=720,height=470");
				pop.focus();
			}
		);
	},
	showPrizesByType : function(which){
		if(!which){
			jQuery("table.contest_table tr.contest_hidden").hide();
			jQuery("table.contest_table tr:not(#no_contests, .contest_hidden)").show();
			jQuery("table.contest_table tr#no_contests").hide();
			jQuery("table.contest_table tr.prize-totals:not(#all_prize_totals)").hide();
			jQuery("#contest_tabs a").removeClass("on");
		}else{
			var contests = jQuery("table.contest_table tr."+which+"_contest");
			contests.show();
			jQuery("table.contest_table tr:not(."+which+"_contest)").hide();
			if(contests.length == 0){
				jQuery("table.contest_table tr#no_contests").removeClass("hidden");
				jQuery("table.contest_table tr#no_contests").show();
			}else{
				jQuery("table.contest_table tr.prize-totals:not(#"+which+"_prize_totals").hide();
				jQuery("table.contest_table tr#"+which+"_prize_totals").show();
				jQuery("table.contest_table tr#no_contests").hide();
			}
			jQuery("#contest_tabs a").removeClass("on");
		}
		jQuery("table.contest_table").stripe();
		if(!which) {which = "ALL"};
		SnapDraft.currentGame = which;
		jQuery("#"+which+"-tab").addClass("on");
	},
	showMyContestsByType : function(which){
		if(!which){
			jQuery("table#contests_container tr.contest_hidden").hide();
			jQuery("table#contests_container tr:not(#no_contests,#hybrid_contests, .contest_hidden)").show();
			jQuery("table#contests_container tr#no_contests").hide();
			jQuery("table#contests_container tr#hybrid_contests").hide();
			if(!SnapDraft.in_frame){
				jQuery("#contest_tabs a").removeClass("on");
			}else{
				jQuery("#contest_tabs_widget a").removeClass("on");
			}
			jQuery("div.paging").show();
		}else{
			var contests = jQuery("table#contests_container tr."+which+"_contest");
			contests.show();
			jQuery("table#contests_container tr:not(."+which+"_contest)").hide();
			if(contests.length == 0){
					jQuery("table#contests_container tr#no_contests").removeClass("hidden");
					jQuery("table#contests_container tr#no_contests").show();
			}else{
				jQuery("table#contests_container tr#no_contests").hide();
			}
			if(!SnapDraft.in_frame){
				jQuery("#contest_tabs a").removeClass("on");
			}else{
				jQuery("#contest_tabs_widget a").removeClass("on");
			}
			jQuery("div.paging").hide();
		}

		jQuery("#contests_container").stripe();
		if(!which) {which = "ALL"};
		SnapDraft.currentGame = which;
		jQuery("#"+which+"-tab").addClass("on");
	},
	showContestsByType : function(which){
		if(!which){
			jQuery("table#contests_container tr.contest_hidden").hide();
			jQuery("table#contests_container tr:not(#no_contests,#hybrid_contests, .contest_hidden)").show();
			jQuery("table#contests_container tr#no_contests").hide();
			jQuery("table#contests_container tr#hybrid_contests").hide();
			if(!SnapDraft.in_frame){
				jQuery("#contest_tabs a").removeClass("on");
			}else{
				jQuery("#contest_tabs_widget a").removeClass("on");
			}
		}else{
			var contests = jQuery("table#contests_container tr."+which+"_contest");
			contests.show();
			jQuery("table#contests_container tr:not(."+which+"_contest)").hide();
			if(contests.length == 0){
				if(which == "NFL"){
					jQuery("table#contests_container tr#hybrid_contests").removeClass("hidden");
					jQuery("table#contests_container tr#hybrid_contests").show();
				}else{
					jQuery("table#contests_container tr#no_contests").removeClass("hidden");
					jQuery("table#contests_container tr#no_contests").show();
				}
			}else{
				jQuery("table#contests_container tr#no_contests").hide();
			}
			if(!SnapDraft.in_frame){
				jQuery("#contest_tabs a").removeClass("on");
			}else{
				jQuery("#contest_tabs_widget a").removeClass("on");
			}
		}
		jQuery("#contests_container").stripe();
		if(!which) {which = "ALL"};
		SnapDraft.currentGame = which;
		jQuery("#"+which+"-tab").addClass("on");
	},
	Toggle : function(layer){
		jQuery(layer).slideToggle(700);
	},
	DisplayError : function(error){
		//TODO
		if(error.type == "confirm"){
			//display the confirm message
			var confirmed = confirm(error.message);
			if(confirmed){
				error.handler.ok;
			}else{
				error.handler.cancel;
			}
			
			
		}else if(error.type == "message"){
			alert(error.message);
		}
	},
	QuickContestAvailableCheck : function(_id){
		jQuery.getJSON(this.jsonHandler, {id : _id, op: 'contest-check'}, function(data){
			return data.contestAvailable;
		});
	},
	UI : {
		Filters : {
			Apply : function(){
				jQuery("#filters > input:checked:not(.filter-button)").each(function(i,item){
					rows_sel = item.id.substring(2);
					sel = "."+rows_sel+":not(.contest_hidden)";
					jQuery(sel).show();
				});
				
				if(SnapDraft.currentGame != "ALL"){
					jQuery("#contests_container tr:not(."+SnapDraft.currentGame+"_contest)").hide();
				}
				
				jQuery("#filters > input:not(:checked)").each(function(i,item){
					rows_sel = item.id.substring(2);
					if(rows_sel != ""){
						jQuery("."+rows_sel+":not(.contest_hidden)").hide();
					}
				});
				jQuery("#contests_container").stripe();
			}
		},
		InPopup : false,
		Dialog : {
			lastTop: 400,
			zIndex : 1000,
			defaultWidth: 300,
			defaultOptions : {
				draggable : true,
				minmax : false,
				width : 300,
				height : 50,
				top : '200',
				left : '400',
				clickToFront : true,
				overlay : false,
				centered : false
			},	
			Create : function(caption, text, identifier, options){
		
				if(jQuery("#"+identifier).length > 0){
					jQuery("#"+identifier).show();
					return false;
				}
		
				_width = this.defaultOptions.width;
				_height = this.defaultOptions.height;
				_top = this.defaultOptions.top;
				_left = this.defaultOptions.left;
				_draggable = this.defaultOptions.draggable;
				_minmax = this.defaultOptions.minmax;
				_clickToFront = this.defaultOptions.clickToFront;
				_overlay = this.defaultOptions.overlay;
				_centered = this.defaultOptions.centered;
				
				var cloned = jQuery("#contestPopup").clone();
				cloned.find('.caption').html(caption);
				cloned.find('.contestContent').html(text);
				cloned.attr('id', identifier);
				
				//if the options object is there, set which options they passed
				if(options != null){
					if(options.minmax){ _minmax = options.minmax; }
					if(options.draggable){ _draggable = true; }
					if(options.width){	_width = options.width; }
					if(options.height){	_height = options.height; }
					if(options.top){ _top = options.top; }
					if(options.left){ _left = options.left; }
					if(options.clickToFront){ _clickToFront = options.clickToFront; }
					if(options.overlay){ _overlay = options.overlay; }
					if(options.centered){ _centered = options.centered;	}
				}
				
				if(_draggable){
					cloned.draggable
					({
						handle:'.dragHandle', 
						zIndex: 10000,
						stop: function()
						{
							jQuery(this).css("z-index", SnapDraft.UI.Dialog.zIndex);
							SnapDraft.UI.Dialog.zIndex++;
						}
					});
				}
				
				cloned.find('.toggleButton').hide();
				if(_minmax){
					cloned.find('.caption').bind("dblclick", function(){
						jQuery("#"+identifier+" .middle").toggle();
						jQuery("#"+identifier).find('.bottom').toggle();
						jQuery(this).toggleClass("maxButton");
					});	
				}
				
				if(_clickToFront){
					cloned.find('.middle:not(img)').click(function(){
						jQuery("#"+identifier).css("z-index", SnapDraft.UI.Dialog.zIndex);
						SnapDraft.UI.Dialog.zIndex++;
                    });
				}
				
				if(_overlay){
					//TODO
				}
				
				cloned.find('.closeButton').click(function(){
                	jQuery("#"+identifier).hide();
                });
				
				jQuery("body").append(cloned);
				
				if(_centered){

					//IE6
					if(jQuery.browser.msie){
						if(jQuery.browser.version == 6){
							var d = jQuery(document);					
							_mtop = 0 - parseInt(d.height() / 2) + d.scrollTop()+'px';//. 'expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + \'px\')';
							_pos = 'absolute';
						}else{
							_mtop = 'auto';//'expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + \'px\')';
							_pos = 'absolute';
						}
						_mleft = 'auto';
					}else{
						_mleft = '-'+(_width/2);
						_mtop = '-'+(_height/2);
						_top = '50%';
						_left = '50%';
						_pos = 'fixed';
					}
					
					cloned.css({
						display :	'block', 
						width : _width,
						height : _height,
						top : _top, 
						left : _left, 
						marginLeft : _mleft,
						marginTop : _mtop,
						position : _pos, 
						zIndex :	this.zIndex
					});
				}else{
					//hack for facebook
					if(document.domain.indexOf("pickspal") != -1){
						_top = this.lastTop+20;
						this.lastTop = _top;
						_left = 150;
					}
					
					
					cloned.css({
						'display' :	'block', 
						'width' : _width,
						'height' : _height,
						'top' :	_top, 
						'left' : _left,
						'position' : 'absolute', 
						'z-index' :	this.zIndex
					});
				}
				
				jQuery(cloned).show();
			}
		},
		Accounting : {
			CustomerID : null,
			HasCreditCard : false,
			IsPayPalUser : false,
			PayPal : {
				CreatePendingTransaction : function(cid, amt){
					var vars = {customer_id: cid, amount: amt, op: 'paypal-generate-form', currentContest: SnapDraft.currentContest, currentGame : SnapDraft.currentGame};
					jQuery.getJSON(SnapDraft.jsonHandler, vars, function(request){
						if(request.status){
							jQuery("#add_btn_submit").unbind("click").attr("disabled","disabled");
							jQuery("#paypal").attr("action", request.target);
							jQuery("#pp_email").val(request.email);
							jQuery("#pp_return").val(request.returnURL);
							jQuery("#pp_cancel").val(request.cancelURL);
							jQuery("#pp_uuid").val(request.uuids);
							jQuery("#item_name").val("SnapDraft Deposit $"+amt);
							jQuery("#item_number").val("SNAP-"+amt);
							jQuery("#item_amount").val(amt);
							jQuery("#paypal").submit();
						}else{
							alert(request.error);
						}
					});
					
				}
			},
			AddMoney : function(customer_id, selector){
				//TODO FIXME
				if(SnapDraft.UI.Accounting.CustomerID == null){
					SnapDraft.UI.Accounting.CustomerID = customer_id;
				}
				//hide the ad if its shown.
				jQuery("#live_scoring_ad").hide();
				jQuery("#openGames_swf").hide();
				
				//console.log(SnapDraft);
				
				//if(SnapDraft.UI.Accounting.HasCreditCard){
				tb_show('Add Money', SnapDraft.URLs.addFunds, null, '<b>Loading Account...</b><br />Please wait' );
				//}else{
				//	if(!SnapDraft.UI.Accounting.IsPayPalUser){
				//		//if they are not a paypal user, then display the dialog.
				//		this.UpdateCreditCard();
				//	}else{
				//		tb_show('Add Money', SnapDraft.URLs.addFunds+"&=", null, '<b>Loading Account...</b><br />Please wait' );
				//	}
				//}
			},
			AddMoneyFacebook : function(){
				this.AddMoney(null, null);
			},
			CloseAddMoney : function(){
				jQuery("#live_scoring_ad").show();
				jQuery("#openGames_swf").show();
				tb_remove();
				return false;
			},
			UpdateCreditCard : function(launch_add_money){
				var domain = document.domain;
				if(domain != "snapdraft.fanball.com"){
					uri = "login_redirect.php?to=secure_update_cc";
				}else{
					uri = SnapDraft.URLs.updateCC+"?e=1";
				}
				if(launch_add_money != null){
					uri += "&am=1";
				}
				Popup({url: uri, name: '_cc', width: 500, height: 260, focus: true, scrollbars: 'no', menubar: false});
			},
			AddCreditCardComplete : function(request){
				tb_remove();
				tb_show('Add Money', SnapDraft.URLs.addFunds, null, '<b>Loading Account...</b><br />Please wait' );
			},
			AddMoneyComplete : function(result, updated_balance, selector){
				jQuery("."+selector).html(updated_balance);
			},
			ApplyFundsToAccount : function(){
				var mpayment_type = jQuery("#payment_type").val();
				jQuery(this).attr('src','/images/button-submit_off.png');
				if(mpayment_type == "PP"){
					var deposit = jQuery("#deposit").val();
					if(deposit == "-" || deposit == 0){
						alert("Please select a deposit amount");
					}else{
						this.PayPal.CreatePendingTransaction(SnapDraft.UI.Accounting.CustomerID, deposit);
					}
				}else{
					var mcc_name = jQuery("#cc_name").val();
					var mcc_number = jQuery("#cc_number").val();
					var mcc_exp_month = jQuery("#cc_exp_month").val();
					var mcc_exp_year = jQuery("#cc_exp_year").val();
					var deposit = jQuery("#deposit").val();
					
					if(deposit == "-" || deposit == 0){
						alert("Please select a deposit amount");
					}else{
						
						var vars = {
							op : 'add-money-to-account',
							customer_id : SnapDraft.UI.Accounting.CustomerID,
							payment_type: mpayment_type,
							cc_name : mcc_name,
							cc_number : mcc_number,
							cc_exp_month : mcc_exp_month,
							cc_exp_year : mcc_exp_year,
							amount: deposit 
						};
						$("#add_btn_submit").attr("disabled","disabled");
						jQuery.getJSON(SnapDraft.jsonHandler, vars, function(request){
							if(request.status){
								tb_remove();
								SnapDraft.UI.Accounting.AddMoneyComplete(true, request.new_balance, "balance");
								alert("The deposit to your account was successful, your updated balance is $"+request.new_balance);
							}else{
								//failed to add funds, display error.
								if(request.error.type == "alert"){
									alert(request.error.message);
								}else{
									var confirmed = confirm(request.error.message);
									if(confirmed){
										//fire off the callback ;-)
										eval(request.error.callback);
									}
								}
							}
							$("#add_btn_submit").remoteAttr("disabled");
						});
					}
				}
			},
			BindAddMoneyControls : function(){
				jQuery("#add_btn_back").bind("click", function(){
					SnapDraft.UI.Accounting.CloseAddMoney();
					jQuery("#add_btn_back").unbind();
				});	
				jQuery("#add_btn_submit").bind("click",function(){
					var pt = jQuery("#payment_type").val();
					//jQuery(this).attr('src','/images/button-submit_off.png');
					var deposit = jQuery("#deposit").val();
					if(deposit == "-" || deposit == 0){
						alert("Please select a deposit amount");
						return false;
					}
					if(pt == 0 || pt == "PP"){
						
						/**
						 * If the user wants to use the existing card 
						 * on file, or chooses paypal as an option, 
						 * we continue to process the sale. If they want
						 * to use a new card or modify the existing, we 
						 * fire that off first then return to this step
						 * and auto submit.
						 */
						$(this).attr("disabled","disabled");
						SnapDraft.UI.Accounting.ApplyFundsToAccount();
					}else{
						//launch the popup to handle card updates
						var amt = deposit;
						var domain = document.domain;
						if(domain != "snapdraft.fanball.com"){
							uri = "login_redirect.php?to=secure_update_cc&amount="+amt;
						}else{
							uri = SnapDraft.URLs.updateCC+"?amount="+amt;
						}
						var options = {
							url : uri,
							name : '__cc',
							width : 500,
							height: 270,
							scrollbars: 'no'
						};
						Popup(options);
					}
				});
			},
			CheckPaymentType : function(val){
				if(val == "PP"){
					//its paypal, hide the cc info.
					jQuery("#cc_information").hide();
					jQuery("#deposit_information > span").hide();
				}else if(val == 0){
					//its existing cc, show it.
					jQuery("#cc_information").show();
					jQuery("#deposit_information > span").show();
				}else{
					//they want to add a new card, hide.
					jQuery("#cc_information").hide();
					jQuery("#deposit_information > span").show();
				}
			}
		},	
		//form handling
		Forms : {
			BindDefaultValue : function(elm, default_value, check_value){
				jQuery(elm).bind("blur", function(){
					if(this.value == check_value){
						this.value = default_value;
					}
				});
				jQuery(elm).bind("focus", function(){
					if(this.value == default_value){
						this.value = check_value;
					}
				});
			},
			BindValidator : function(form, callback){
				jQuery(form).bind("submit", function(){
					return eval(callback);
				});
			}
		},
		
		//Registration handling
		Registration : {
			
			lastValidationErrors : [],
			
			getVariables : function(){
				var returnObject = {
					op : 'validate-registration',
					customer_id : jQuery("#customer_id").val(),
					password : jQuery("#password").val(),
					password_verify : jQuery("#password").val(),
					first_name : jQuery("#first_name").val(),
					last_name : jQuery("#last_name").val(),
					street : jQuery("#street").val(),
					extra_line : jQuery("#extra_line").val(),
					city : jQuery("#city").val(),
					usState : jQuery("#usState").val(),
					caState : jQuery("#caState").val(),
					userState : jQuery("#userState").val(),
					countryrad : jQuery("#countryrad").val(),
					postal : jQuery("#postal").val(),
					phone : jQuery("#phone").val(),
					phone2 : jQuery("#phone2").val(),
					fax : jQuery("#fax").val(),
					email : jQuery("#email").val(),
					cc_number : jQuery("#cc_number").val(),
					cc_name : jQuery("#cc_name").val(),
					cc_exp_month : jQuery("#cc_exp_month").val(),
					cc_exp_year : jQuery("#cc_exp_year").val(),
					payment_type: jQuery("#payment_type").val(),
					deposit : jQuery("#deposit").val()
				};				
				return returnObject;
			},
			Validate : function(){
				jQuery.getJSON(SnapDraft.jsonHandler, this.getVariables(), function(request){
					//if validation was good, just send the form through.
					if(request.valid){
						//submit form
						jQuery("#step2").submit();
					}else{
						SnapDraft.UI.Registration.BindValidationErrors(request);
						return false;
					}
				});
			},
			BindValidationErrors : function(request){
				jQuery.each(request.errors, function(i, item){
					if(item.type != "select" && item.type != "select.small"){
						jQuery("#"+item.name).bind("mouseover",function(){
							//mouseover bind
							return overlib(item.error, WIDTH, 300, ABOVE, TEXTFONTCLASS, 'over-text', CAPTION, 'Error Message' ,FGCLASS, 'over-fg', BGCLASS, 'over-bg', CGCLASS, 'over-cap');
						});
						jQuery("#"+item.name).bind("mouseout", function(){
							//mouseout bind
							return nd();
						});
					}
					if(item.type != "select.small"){
						jQuery("#"+item.name).attr("class", "error");
					}else{
						jQuery("#"+item.name).attr("class","error-small");
					}
				});
				jQuery.each(request.validFields, function(i,item){
					if(item == "cc_exp_month" || item == "cc_exp_year"){
						jQuery("#"+item).attr("class","formstyle1 small-select");
						jQuery("#"+item).unbind();
					}else{
						jQuery("#"+item).attr("class","formstyle1");
						jQuery("#"+item).unbind();
					}
				});
				alert("Please correct the highlighted fields to continue. You can mouseover the field to see the problem.")
			}
		},
		
		//view contest object
		ViewContest : {
			RemaingTime : 0,
			EndTime : 0,
			Timer : null,
			TimerDiv : "#running_timer",
			//need 
			Initialize : function(){
				//tab binding
				
				jQuery(".inline li a").each(function(i,item){
					var sel = item.id+"_content";
					jQuery(item).bind("click", function(){
						sel = item.id+"_content";
						jQuery("#"+item.id).addClass("on");
						jQuery(".tab-content:not(#"+sel+")").hide();
						jQuery(".inline li a:not(#"+item.id+")").removeClass("on");
						jQuery("#"+sel).show();
					});
				});
				//bind player lists.
				jQuery("#positions li a").each(function(i,item){
					var sel = item.id+"-salaries";
					jQuery(item).bind("click",function(){
						sel = item.id+"-salaries";
						jQuery("#"+item.id).addClass("on");
						jQuery(".table-content:not(#"+sel+",#header)").hide();
						jQuery("#positions li a:not(#"+item.id+")").removeClass("on");
						jQuery("#"+sel).show();
						jQuery("#salaries-position").html(item.title);
					});
				});
				
				//DRS+ mixed sports.
				jQuery(".positions li a").each(function(i,item){
					var sel = item.id+"-salaries";
					jQuery(item).bind("click",function(){
						sel = item.id+"-salaries";
						jQuery("#"+item.id).addClass("on");
						jQuery(".table-content:not(#"+sel+",#header)").hide();
						jQuery(".positions li a:not(#"+item.id+")").removeClass("on");
						jQuery("#"+sel).show();
						jQuery("#salaries-position").html(item.title);
					});
				});
				
				//DRS+ added for mixed sport functionality
				jQuery("div#sport_selects a").each(function(i,item){
					jQuery(item).bind("click",function(){
						var sport = item.id.split("-");
						jQuery("ul.positions:not(#positions-"+sport[1]+")").hide();
						jQuery("#positions-"+sport[1]).show();
					});
				});
				
				jQuery("div#sport_selects_scoring a").each(function(i,item){
					jQuery(item).bind("click",function(){
						var sport = item.id.split("-");
						jQuery("div#scoring-wrapper > div").hide();
						jQuery("#"+sport[1]+"-scoring").show();
					});
				});
					
				//display the scoring tab.
				jQuery("#scoring").addClass("on");
				jQuery("#scoring_content").show();
				
				// FIXME
				//start timer..
				this.Timer = setInterval("SnapDraft.UI.ViewContest.UpdateTimer()", 1000);
			},
			UpdateTimer : function(){
				this.RemaingTime--;
				updated_time = this.GetFormattedTime(this.RemaingTime);
				if(updated_time != ""){
					jQuery(this.TimerDiv).html(updated_time);
				}else{
					jQuery("#timer_holder").hide();
				}
			},
			GetFormattedTime : function(time){
				//time holders
				var days = 0;
				var hrs = 0;
				var mins = 0;
				var secs = 0;
				
				if(time >= (60*60*24)){
					//greater then one day left.
					 days = Math.floor(time / (60*60*24));
					 time = (time - (days * (60*60*24)));
				}
				if(time >= (60*60)){
					//greater then one hour left.
					 hrs = Math.floor(time / (60*60));
					 time = (time - (hrs * (60*60)));
				}
				if(time >= (60)){
					//greater then one min left.
					 mins = Math.floor(time / (60));
					 time = (time - (mins * (60)));
				}
				//set the remaining time to secs.
				secs = time;
				
				output = "";
				//now make some output.
				if(days != 0){
					df = (days == 1) ? " Day" : " Days";
					output += days + df+ " ";
				}
				if(hrs != 0){
					hf = (hrs == 1) ? " Hour" : " Hours";
					output += hrs + hf+ " ";
				}
				if(mins != 0){
					mf = (mins == 1) ? " Minute" : " Minutes";
					output += mins + mf+ " ";
				}
//				if(secs != 0){
//					sf = (secs == 1) ? " Second" : " Seconds";
//					output += secs + sf+ " ";
//				}
				return output;
			}
		},
		
		Contest : {
			League : '',
			PerformQualifyingChecks : function(cid, league){
				//perform some basic checks before directing
				//to the contest page.
				jQuery.getJSON(SnapDraft.jsonHandler, {op: 'check-contest-availability', contest_id: cid}, function(request){
					if(request.available){
						//all the pre-qual checks passes, send them to the contest.
						if(!SnapDraft.in_frame){
							if(league.toLowerCase() == "mlb-draft"){
								url = SnapDraft.URLs.goToLiveDraft.replace("{league}", league);
							}else{
								url = SnapDraft.URLs.goToContest.replace("{league}", league);
							}
							url = url.replace("{id}", cid);
							document.location.href = url;
						}else{
							if(!SnapDraft.is_facebook){
								if(league.toLowerCase() == "mlb-draft"){
									url = SnapDraft.URLs.goToLiveDraft.replace("{league}", league);
								}else{
									url = SnapDraft.URLs.goToContest.replace("{league}", league);
								}
								url = url.replace("{id}", cid);
								top.location.href = url;
							}else{
								url = SnapDraft.URLs.goToContest.replace("{league}", league);
								url = url.replace("{id}", cid);
								document.location.href = url;
							}
						}
					}else{
						//there are some issues, display the errors.
						var message = "We were unable to enter you into the specified contest\n\n";
						message += request.error.message;
						if(request.error.type == "alert"){
							alert(message);
						}else{
							var confirmed = confirm(message);
							if(confirmed){
								if(!SnapDraft.in_frame){
									eval(request.error.callback);
								}else{
									if(request.failure_code == "MONEY"){
										if(SnapDraft.is_facebook){
											eval(request.error.callback);
										}else{
											top.location.href = request.error.callback_url;	
										}
									}else{
										eval(request.error.callback);
									}
								}
							}else{
								//do nothing.
							}
						}

					}
				});
			},
			EnterContest : function(options){
				//handler for not logged in users.
				document.location.href = options.secureURL+'?ref=/'+options.league+'/pick_winner.php?contest='+options.cid;
			},
			EnterContestFromPreview : function(cid){
				if(jQuery("#pend_balance").length > 0){
					//it was opened by the pick winner page, bind the 
					//enter button to just callback to teh current page
					if(!jQuery("#contest_check_"+cid).checked){
						jQuery("#contest_check_"+cid).attr("checked","checked");
						updateBalance();
					}
					tb_remove();
				}else{
					//TODO
					SnapDraft.UI.Contest.PerformQualifyingChecks(cid,this.League.toLowerCase());
				}
			},
			EditLineup : function(cid,league){
				if(league.toLowerCase() == "mlb-draft"){
					url = SnapDraft.URLs.goToLiveDraft.replace("{league}", league.toLowerCase());
				}else{
					url = SnapDraft.URLs.Contest.editLineup.replace("{league}", league.toLowerCase());
				}
				url = url.replace("{id}", cid);
				document.location.href = url;
			}
		},
		//user specific.
		User : {
			ForgotPassword : function(){
				//TODO, implement
				jQuery("#btn_fpw_close").bind("click", function(){
					tb_remove();
					jQuery(this).unbind();
					jQuery("#btn_fpw_send").unbind();
				});
				jQuery("#btn_fpw_send").bind("click", function(){
					jQuery.getJSON(SnapDraft.jsonHandler, 
						{ op: 'forgot-password', email : jQuery("#fpw_email").val()}, 
						function(request){
							if(request.status){
								alert("We have sent an email to "+jQuery("#fpw_email").val()+" with your login information.");
							}else{
								alert(request.error_message);
								return false;
							}

							jQuery("#btn_fpw_send").unbind();
							jQuery("#btn_fpw_close").unbind();
							tb_remove();
						});
				});
				tb_show('Forgot Username/Password', '#TB_inline?height=154&width=400&inlineId=forgot_password', null, '<b>Loading Dialog...</b><br />Please wait' );
			}
		},
		
		//lineup related
		LineUp : {
			Initialize : function(){
				jQuery("#btnMore").bind("click", function(){
					var src = jQuery(this).attr("src");
					jQuery(".contest_toggle").slideToggle("normal");
					if(src == "/images/button-moregames.png"){
						src = "/images/button-hidegames.png";
					}else{
						src = "/images/button-moregames.png";
					}
					jQuery(this).attr("src", src);
				});
			}
		},
		
		//standings page
		Standings : {
			LastGame : 606,
			CurrentGame : 606,
			CurrentPage : 0,
			CurrentMonth : 0,
			MaxPage : 0,
			
			Initialize : function(){
				//bind the tabs.
				jQuery("#contest_tabs > ul > li > a").each(function(i,item){
					var id = jQuery(this).attr("id");
					var t = id.split("_");
					var gid = t[1];
					
					jQuery(this).bind("click", function(){
						jQuery("#contest_tabs > ul > li > a:not(#"+id+")").removeClass("on");
						jQuery(this).addClass("on");
						SnapDraft.UI.Standings.CurrentGame = gid;
						if(SnapDraft.UI.Standings.LastGame != gid){
							SnapDraft.UI.Standings.LastGame = gid;
							//reset the page counter;
							SnapDraft.UI.Standings.CurrentPage = 0;
						}
						//callback
						SnapDraft.UI.Standings.LoadStandings();
						
					});
				});
				//bind the drop down
				jQuery("#select_month").bind("change", function(){
					var val = jQuery(this).val();
					SnapDraft.UI.Standings.CurrentMonth = val;
					SnapDraft.UI.Standings.LoadStandings();
				});
				//bind the nav buttons
				jQuery(".lb_next").bind("click", function(){
					if(SnapDraft.UI.Standings.CurrentPage < SnapDraft.UI.Standings.MaxPage){
						SnapDraft.UI.Standings.CurrentPage++;
						SnapDraft.UI.Standings.LoadStandings();
					}else{
						return;
					}
				});
				jQuery(".lb_prev").bind("click", function(){
					if(SnapDraft.UI.Standings.CurrentPage == 0){
						return;
					}else{
						SnapDraft.UI.Standings.CurrentPage--;
						SnapDraft.UI.Standings.LoadStandings();
					}
				});
			},
			LoadStandings: function(){
				jQuery.post(
					SnapDraft.URLs.loadStandings,
					{game_id: SnapDraft.UI.Standings.CurrentGame, page: SnapDraft.UI.Standings.CurrentPage, month: SnapDraft.UI.Standings.CurrentMonth},
					function(data){
						jQuery("#standings_table").html(data);
					}
				);
			}
		},
		
		//registration/payment methods
		DisplayStateOptions : function(which){
			if(which == "US"){
		 		jQuery("#usState").show();
		 		jQuery("#caState").hide();
		 		jQuery("#userState").hide();
		 		jQuery("#chooseCountry").hide();
		 	}else if(which == "CAN"){
		 		jQuery("#caState").show();
		 		jQuery("#usState").hide();
		 		jQuery("#userState").hide();
		 		jQuery("#chooseCountry").hide();
		 	}else if(which == "INTL"){
		 		jQuery("#caState").hide();
		 		jQuery("#usState").hide();
		 		jQuery("#userState").show();
		 		jQuery("#chooseCountry").show();
		 	}
		},
		CheckPaymentMethod : function(elm){
			if(elm.value == "PP"){
				//handle PayPal
				jQuery("#cc_details").hide();
				jQuery("#pp_details").show();

				jQuery("#cc_information :input").attr("disabled","disabled");
				jQuery("#cc_name").addClass("disabled").removeClass("formstyle1");
				jQuery("#cc_number").addClass("disabled").removeClass("formstyle1");
				jQuery("#cc_exp_month").addClass("disabled").removeClass("formstyle1");
				jQuery("#cc_exp_year").addClass("disabled").removeClass("formstyle1");
				
			}else{
				//display cc fields
				jQuery("#pp_details").hide();
				jQuery("#cc_details").show();

				jQuery("#cc_information :input").attr("disabled","");
				jQuery("#cc_name").removeClass("disabled").addClass("formstyle1");
				jQuery("#cc_number").removeClass("disabled").addClass("formstyle1");
				jQuery("#cc_exp_month").removeClass("disabled").addClass("formstyle1");
				jQuery("#cc_exp_year").removeClass("disabled").addClass("formstyle1");
			}
		},
		SetTotalDeposit : function(amt){
			if(amt != "-"){
				amt = "$"+amt;
			}
			jQuery("#total_amount").html(amt);
		},
		SetTotalCost : function(amt){
			if(amt != "-"){
				amt = "$"+amt;
			}
			jQuery("#total_cost").html(amt);
		},
		SetTotals : function(val){
			this.SetTotalCost(val);
			var sel_class = jQuery("#deposit option:selected").attr('class');
			if(sel_class.substring('promo') != -1 && sel_class != ""){
				var cls = jQuery("#deposit option:selected").attr('class');
				var promo = cls.split('_');
				val = (parseInt(val)+parseInt(promo[1])).toFixed(2);
			}
			this.SetTotalDeposit(val);
		},
		DisplayExistingLogin : function(val){
			if(val == "no"){
				jQuery("#login-table").hide();
			}else{
				jQuery("#login-table").show();
			}
		},
		BindStepOne : function(){
			this.BindExistingLogin();
			this.BindNextEvent();
		},
		BindNextEvent : function(){
			jQuery("#btn_next").bind("click", function(){
				if(jQuery("#agreed").is(":checked")){
					//its all good..
					if(jQuery(".ui-radio-existing_user:checked").val() == "yes"){
						//if they are existing user, make sure we have some login info present.
						if(jQuery("#user_id").val() != "" && jQuery("#user_password").val() != ""){
							//continue.
							jQuery("#login-form").submit();
						}else{
							alert("Please enter both a user id and password to continue.");
							return false;
						}
					}
				}else{
					//they havent agreed.
					alert("You must agree to the terms and conditions to continue.");
					return false;	
				}
			});
		},
		BindExistingLogin : function(){
			jQuery(".ui-radio-existing_user").bind("click", function(){
				SnapDraft.UI.DisplayExistingLogin(this.value);
			});
			SnapDraft.UI.DisplayExistingLogin("no");
		},
		BindStepTwo : function(){
			jQuery("#sign_btn_back").bind("click", function(){
				history.back();
			});
			jQuery("#sign_btn_submit").bind("click", function(){
				//make sure they have selected an amount.
				SnapDraft.UI.Registration.Validate();
				return false;
			});
		},
		DisplayContestInfo : function(cid){
			var pop = window.open(SnapDraft.URLs.viewContest+cid+"&as_popup=1", "_view"+cid, "width=720,height=470");
			pop.focus();
		}
	}
};

var SnapDraftUpdater = {
	
	initialized: false,
	timer: null,
	lastUpdate: null,
	useJSON: true,
	removeHighlightTime: 5000,
	addContestRow : null,
	delay : null,
	enabled: true,
	
	doCallBack : function(){
	if(this.enabled){
		jQuery.getJSON(SnapDraft.jsonHandler, {lu : this.lastUpdate}, function(data){
			//if we have a change in the file, then send to the processor
			SnapDraftUpdater.setNextCall(data.delayTime);
			SnapDraftUpdater.lastUpdate = data.lastUpdate;
			if(data.hasChanges){
				//process.
				SnapDraftUpdater.cleanTable();
				SnapDraftUpdater.StripeTables();
				SnapDraftUpdater.processChanges(data);
			}else{
				SnapDraftUpdater.cleanTable();
				SnapDraftUpdater.StripeTables();
			}
		});
	}
	},
	setNextCall : function(delay){
		//this.lastUpdate = data.updateTimestamp;
		if(delay == null){
			delay = this.delay;
		}
		this.timer = setTimeout('SnapDraftUpdater.doCallBack()', (delay * 1000));
	},
	DisableUpdater : function(enable_in){
		if(this.enabled){
			if(enable_in != null){
				setTimeout('SnapDraftUpdater.setNextCall();SnapDraftUpdater.enabled = true;', enable_in);
			}
			this.enabled = false;
		}
	},
	cleanTable : function(){		
		jQuery("#contests_container tr").removeClass("highlighted");
	},
	processChanges : function(request){
		// process removals first..
		jQuery.each(request.removals, function(i,item){
			jQuery("#contest_"+item.contest_id).remove();
		});
		//process the changes next...
		jQuery.each(request.changes, function(i,item){
			var val = jQuery("#contest_entries_"+item.contest_id).html();
			if(val != item.team_count){
				jQuery("#contest_"+item.contest_id).removeClass("contest_hidden"); //+DRS, should unhide any 0 contests that now have atleast 1 team
				jQuery("#contest_entries_"+item.contest_id).html(item.team_count);
				jQuery("#contest_"+item.contest_id).addClass("highlighted");
			}
			//var fn = 'SnapDraftUpdater.RemoveHighlight('+item.contest_id+')';
			//setTimeout(fn,this.removeHighlightTime);
		});
		//process the news ones now ;-)
		if(request.additions != false){
			if(request.additions.length > 5){
				document.location.reload();
			}
		}
		if(request.commands != false){
			//process any commands, like forcing a browser refresh
			jQuery.each(request.commands, function(i, item){
				if(item.forceReload){
					document.location.href = item.href;
				}
			});
		}
	},
	StripeTables : function(){
		jQuery("#contests_container").stripe();
	},
	RemoveHighlight : function(id){
		jQuery('#contest_'+id).removeClass("highlighted");
	},
	//TODO
	addContest : function(contest){
		//determine which table to insert into
		var elm;
		switch(contest.game_id){
			case SnapDraft.games.NFL:
				elm = "#NFL-contests";
				break;
			case SnapDraft.games.NBA:
				elm = "#NBA-contests";
				break;
			case SnapDraft.games.NHL:
				elm = "#NHL-contests";
				break;
			case SnapDraft.games.MLB:
				elm = "#MLB-contests";
				break;
		}
		//if we havent copied that cell to our temp storage, only do it once :)
		if(SnapDraftUpdater.addContestRow == null){
			SnapDraftUpdater.addContestRow = jQuery('#tr:last').clone();
		}
		var row = SnapDraftUpdater.parseCopiedRow(contest);
		//fix this
		jQuery(elm+"-data").append(row);
	},
	fillClonedRow : function (contest){
		var row = SnapDraftUpdater.addContestRow;
		
	},
	parseCopiedRow : function (contest){
		var tempRow = SnapDraftUpdater.addContestRow;
		var tempString = SnapDraftUpdater.addContestRow.html();
		var targets = ["rules","cost","name","team_count","entries","prize","cap","date"];
		var replaces = ["New Cell!",contest.cost, contest.name, contest.team_count, contest.entries, contest.prize, contest.cap, contest.date];
		for(i=0;i<targets.length;i++){
			tempString = tempString.replace("{"+targets[i]+"}",replaces[i]);
		}
		tempString = tempString.replace(/{id}/g, contest.contest_id);
		return tempRow.html(tempString);
	},
	stripeTable : function(id){
		jQuery("#"+id).stripe();
	}
};


function tb_detectMacXFF() {
	  var userAgent = navigator.userAgent.toLowerCase();
	  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
	    return true;
	  }
}

function tb_showIframe(){
	  jQuery("#TB_load").remove();
	  jQuery("#TB_window").css({display:"block"});
}

function tb_remove() {
  jQuery("#TB_window").fadeOut("fast");
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    jQuery("body","html").css({height: "auto", width: "auto"});
    jQuery("html").css("overflow","");
  }
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}

(function($) { 
    $.fn.extend({ 
        stripe: function(options) {
            var defaults = { 
                even: "catline1",
                odd: "catline"
            }; 
            var options = $.extend(defaults, options);
            var obj = $(this);
            obj.find('tr:not(:hidden, .prize-totals):odd').removeClass(options.even).addClass(options.odd);
            obj.find('tr:not(:hidden, .prize-totals):even').removeClass(options.odd).addClass(options.even);
        }
    });
})(jQuery);


function Popup(options){
	
	_uri = options.url;
	_name = '';
	_width = 400;
	_height = 200;
	_scroll = 'yes';
	_menu = 'no';
	_top = '100';
	_left = '100';
	_centered = true;
	
	if(options.name){ _name = options.name; }
	if(options.width){ _width = options.width; }
	if(options.width){ _height = options.height; }
	if(options.scrollbars) { _scroll = options.scrollbars; }
	if(options.menubar) { _menu = options.menubar; }
	if(options.top) { _top = options.top; }
	if(options.left) { _left = options.left; }
	if(options.centered) { _centered = options.centered; }
	
	if(_centered){
		_left = (screen.width/2)-(_width/2);
		_top = (screen.height/2)-(_height/2);
	}
	
	var win = window.open(_uri, _name, "width="+_width+",height="+_height+", scrollbars="+_scroll+", menubar="+_menu+", left="+_left+", top="+_top);
	if(options.focus){
		win.focus();
	}
}

var Dialog = {
	zIndex : 1000,
	defaultWidth: 300,
	defaultOptions : {
		draggable : true,
		minmax : false,
		width : 300,
		height : 50,
		top : '200',
		left : '400',
		clickToFront : true,
		overlay : false,
		centered : false
	},	
	Simple : function(text, identifier, options){
		if(jQuery("#"+identifier).length > 0){
			jQuery("#"+identifier).show();
			return false;
		}
		
		var player = $('#contestPopup').clone();
		player.css({
			'display':	'block', 
			'top':		options.top+'px', 
			'left':		options.left+'px', 
			'position':	'absolute', 
			'z-index':	options.zIndex
		});
		player.attr("id", identifier);
		player.find('.contestPopupReturn').html(text);


		// ---------------------------------------------
		// Activate the dragging functionality
		// ---------------------------------------------
		player.draggable
		({
			handle:'.contestPopupHandle2', 
			zIndex: 10000,
			stop: function()
			{
				$(this).css("z-index", options.zIndex);
			}
		});

		// ---------------------------------------------
		// Add the functionality to the close button
		// ---------------------------------------------
		player.find('.contestPopupClose').click
		(
			function()
			{
				$(this).parent().parent().hide();
			}
		);			

		// ---------------------------------------------
		// Add functionality that brings the popup to
		// the front when it is clicked
		// ---------------------------------------------
		player.find('div.contestPopupReturn').click
		(
            function()
            {
            	$(this).parent().css("z-index", options.zIndex);
            }
        );

		// ---------------------------------------------
		// Append the popup to the BODY
		// ---------------------------------------------
		$('body').append(player);

		// ---------------------------------------------
		// Increment values for hte next popup
		// ---------------------------------------------

	},
	Create : function(caption, text, identifier, options){

		if(jQuery("#"+identifier).length > 0){
			jQuery("#"+identifier).show();
			return false;
		}

		_width = this.defaultOptions.width;
		_height = this.defaultOptions.height;
		_top = this.defaultOptions.top;
		_left = this.defaultOptions.left;
		_draggable = this.defaultOptions.draggable;
		_minmax = this.defaultOptions.minmax;
		_clickToFront = this.defaultOptions.clickToFront;
		_centered = this.defaultOptions.centered;
		
		var cloned = jQuery("#contestPopup").clone();
		cloned.find('h1.caption').html(caption);
		cloned.find('div.contestContent').html(text);
		cloned.attr('id', identifier);
		
		//if the options object is there, set which options they passed
		if(options != null){
			if(options.minmax){ _minmax = options.minmax; }
			if(options.draggable){ _draggable = true; }
			if(options.width){	_width = options.width; }
			if(options.height){	_height = options.height; }
			if(options.top){ _top = options.top; }
			if(options.left){ _left = options.left; }
			if(options.clickToFront){ _clickToFront = options.clickToFront; }
			if(options.centered){ _centered = options.centered;	}
		}
		
		if(_draggable){
			cloned.draggable
			({
				handle:'.dragHandle', 
				zIndex: 10000,
				stop: function()
				{
					//jQuery(this).css("z-index", SnapDraft.UI.Dialog.zIndex);
					//SnapDraft.UI.Dialog.zIndex++;
				}
			});
		}
		
		if(!_minmax){
			cloned.find('div.toggleButton').hide();
		}else{
			cloned.find('div.toggleButton').hide();
			cloned.find('h1.caption').bind("dblclick", function(){
				jQuery("#"+identifier+" div.middle").toggle();
				jQuery("#"+identifier+' div.bottom').toggle();
				jQuery(this).toggleClass("maxButton");
			});	
			
		}
		
		if(_clickToFront){
			cloned.find('div.middle:not(img)').click(function(){
				jQuery("#"+identifier).css("z-index", SnapDraft.UI.Dialog.zIndex);
				SnapDraft.UI.Dialog.zIndex++;
            });
		}
		
		cloned.find('.closeButton').click(function(){
        	jQuery("#"+identifier).hide();
        });
		
		cloned.css({
			width: _width,
			height: _height
		});
		
		jQuery("body").append(cloned);
		
		if(_centered){
			cloned.center();
		}else{
			//cloned.center();
			cloned.css({
				'display' :	'block', 
				'width' : _width,
				'height' : _height,
				'top' :	_top, 
				'left' : _left,
				'position' : 'absolute', 
				'z-index' :	this.zIndex
			});
		}
		
		cloned.show();
	}
}
