/********************************************************************************************************
 *						INITIAL LOAD						*
 ********************************************** START ***************************************************/
$(document).ready(function() {						   
	$("#footer .deleteDiv").click(function() {
		$(this).parents("#footer").animate({ bottom: '-25px', opacity: '0.0' }, 250);
		return false;
	});
	
	var browser = false;
	var version = false;
	jQuery.each(jQuery.browser, function(i, val, x) {
		if (val) {
			browser = i;
		}
		else if(i == "version") {
			version = val;
		}
	});
	
	if(browser != "msie") {
		resizeCover();
		centerElm("share");

		$(window).resize(onWindowResize);
		$(window).scroll(onWindowResize);
	}
	
	loadFavoriteIcons();
	loadItemReactionsIcons();
	loadShareWithAFriendIcons();
});

function resizeCover() {
	var window_height = $(document.body).height() + $(window).height();
	
	$('#coverup').css("height", window_height);
}

function onWindowResize() {
	resizeCover();
	centerElm("sign_up");
	centerElm("share");
	//centerElm("form_alert_message");
	centerElm("fb_api_show_des_info_popup_div");
	centerElm("fb_api_show_wrong_subscriber_id_div");
	centerElm("fb_api_show_wrong_dob_div");
}

function centerElm(elm_id) {
	var window_width = $(window).width();
	var window_height = $(window).height();
	
	var elm_width = $("#" + elm_id).width();
	var elm_height = $("#" + elm_id).height();
	
	elm_width = elm_width > 0 ? (elm_width / 2) : 0;
	elm_height = elm_height > 0 ? (elm_height / 2) : 0;
	
	window_width = window_width > 0 ? (window_width / 2) : 0;
	window_height = window_height > 0 ? (window_height / 2) : 0;
	
	var left = Math.round(window_width - elm_width);
	var top = Math.round(window_height - elm_height);
	
	left = left > 0 ? left : 0;
	top = top > 0 ? top : 0;
	
	top += document.documentElement.scrollTop ? document.documentElement.scrollTop : 0;
	
	$("#" + elm_id).css("left", left);
	$("#" + elm_id).css("top", top);
	
	/*** START: OTHER WAY TO CENTER OBJECTS ***/
	/*
	// Determine how much the visitor had scrolled
	var scrolledX, scrolledY;
	if(self.pageYOffset) {
		scrolledX = self.pageXOffset;
		scrolledY = self.pageYOffset;
	} else if(document.documentElement && document.documentElement.scrollTop) {
		scrolledX = document.documentElement.scrollLeft;
		scrolledY = document.documentElement.scrollTop;
	} else if(document.body) {
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	// Determine the coordinates of the center of the page
	var centerX, centerY;
	if(self.innerHeight) {
		centerX = self.innerWidth;
		centerY = self.innerHeight;
	} else if(document.documentElement && document.documentElement.clientHeight) {
		centerX = document.documentElement.clientWidth;
		centerY = document.documentElement.clientHeight;
	} else if(document.body) {
		centerX = document.body.clientWidth;
		centerY = document.body.clientHeight;
	}
	
	var leftOffset = scrolledX + (centerX - $("#" + elm_id).width()) / 2;
	var topOffset = scrolledY + (centerY - $("#" + elm_id).height()) / 2;

	$("#" + elm_id).css("left", leftOffset);
	$("#" + elm_id).css("top", topOffset);
	*/
	/*** END: OTHER WAY TO CENTER OBJECTS ***/
}

function showLoadingBar() {
	centerElm("loading_bar");
	
	//$("#loading_bar").css("display", "block");
}

function hideLoadingBar() {
	$("#loading_bar").css("display", "none");
}

/********************************************************************************************************
 *						ITEMS							*
 ********************************************** START ***************************************************/

function getItemModelByController(controller) {
	var model = false;
	switch(controller) {
		case "stories": model = "story"; break;
		case "events": model = "event"; break;
		case "drinks": model = "drink"; break;
		
		default : model = false;
	}
	return model;
}

/********************************************************************************************************
 *					FORM VALIDATION							*
 ********************************************** START ***************************************************/
function loginFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	var login_submit_button = document.getElementById('login_submit_button');
	if(login_submit_button) {
		login_submit_button.disabled = true;
	}
	
	return true;
}

function registrationFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	var registration_submit_button = document.getElementById('registration_submit_button');
	if(registration_submit_button) {
		registration_submit_button.disabled = true;
	}
	
	return true;
}

function forgotPasswordFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	var forgot_password_submit_button = document.getElementById('forgot_password_submit_button');
	if(forgot_password_submit_button) {
		forgot_password_submit_button.disabled = true;
	}
	
	return true;
}

function resetPasswordFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	else {	
		try {
			if(cform.password.value != cform.password_confirmation.value) {
				alert('Password and Confirm Password fields must be the same.');
				return false;
			}
		}
		catch(e) {
			return false;
		}
	}
	
	var reset_password_submit_button = document.getElementById('reset_password_submit_button');
	if(reset_password_submit_button) {
		reset_password_submit_button.disabled = true;
	}
	
	return true;
}

function profileFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	var profile_submit_button = document.getElementById('profile_submit_button');
	if(profile_submit_button) {
		profile_submit_button.disabled = true;
	}
	
	return true;
}

function getFriendInFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	var getfriendin_submit_button = document.getElementById('getfriendin_submit_button');
	if(getfriendin_submit_button) {
		getfriendin_submit_button.disabled = true;
	}
	
	return true;
}

function idYourBottleFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		message = message ? message.toString().replace(/\n/g, "<br/>") : message;
		$("#form_alert_message .message").html(message);
		document.getElementById('form_alert_message').className = 'idyourbottle';
		$("#form_alert_message").css("display", "block");
		
		window.setTimeout("hideFormAlertMessage();", 4000);
		
		return false;
	}
	
	var idyourbottle_submit_buton = document.getElementById('idyourbottle_submit_buton');
	if(idyourbottle_submit_buton) {
		idyourbottle_submit_buton.disabled = true;
	}
	
	return true;
}

function shareFormCheck(cform, attrs) {
	var message = getPSCFormCheckMessage(cform, attrs);
	if(message) {
		alert(message);
		//showFormAlertMessage(message);
		return false;
	}
	
	//the loading button is in the /views/elements/share page.
	
	var share_submit_buton = document.getElementById('share_submit_buton');
	if(share_submit_buton) {
		share_submit_buton.disabled = true;
	}
	
	return true;
}

function getPSCFormCheckMessage(cform, attrs) {
	var errors = attrs.errors;
	var confirm_element = attrs.confirm_element;
	var wrong_elms = attrs.wrong_elms;
	
	if(errors != 0) {
		var elm;
		var message = "";
		for(var i = 0; i < wrong_elms.length; ++i) {
			elm = wrong_elms[i];
			if(elm.message) {
				message += elm.message + "\n";
			}
		}
		return message;
	}
	return false;
}
 
function showFormAlertMessage(message) {
	message = message ? message.toString().replace(/\n/g, "<br/>") : message;
	$("#form_alert_message .message").html(message);
	document.getElementById('form_alert_message').className = 'default';
	
	centerElm("form_alert_message");
	
	$("#form_alert_message").css("display", "block");
	
	return false;
	
}

function hideFormAlertMessage() {
	$("#form_alert_message").css("display", "none");
	$("#form_alert_message .message").html("");
	
	return false;
}

function showSubmitMissingStatus(oRes) {
	var response = eval('(' + oRes + ')');
	
	var missingZipElement = $("#enter_zipcode_popup");
	
	if (response['status'] == 'success') {
		//alert('missingzip: success!');
		missingZipElement.children("h1").text("Got it! Thank you.");
		missingZipElement.children("p, form").remove();
		setTimeout("hideSubmitMIssingStatus()", 3000);
	} else {
		//alert('missingzip: fail! - ' + oRes);
		missingZipElement.children("h1").text("Whoops");
		missingZipElement.children("p + p").remove();
		missingZipElement.children("p").html('Looks like there was an error updating your information. Please try again, or if you keep getting the error email us at <a href="mailto:concierge@patronsocialclub.com">concierge@patronsocialclub.com</a>');
		//setTimeout("hideSubmitMIssingStatus()", 3000);
	}
}
function hideSubmitMIssingStatus() {
	$("#enter_zipcode_popup").fadeOut(400);
	$("#coverup").fadeOut(800);
	MyLib.FlashHandler.addRemovedFlashObjects();
}

function missingRadioChange() {//begin U.S. resident radio selection updates country selection to U.S.
	if (document.getElementById('intlmiss1').checked) {//begin US choice
		document.getElementById('missing_country').selectedIndex = 0;
	} //end U.S. resident radio selection updates country selection to U.S.
}

if (typeof dump != 'function') {//begin: TODO: remove
	function dump(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;

		// The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j<level+1;j++) level_padding += "    ";

		if(typeof(arr) == 'object') { // Array/Hashes/Objects
		for(var item in arr) {
		var value = arr[item];

		if(typeof(value) == 'object') { // If it is an array,
		dumped_text += level_padding + "'" + item + "' ...\n";
		dumped_text += dump(value,level+1);
		} else {
		dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
		}
		}
		} else { // Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
		} 

}//end TODO: remove

function submitMissingFormCheck(cform, attrs) {
	if (document.getElementById('intlmiss1').checked) {//begin US choice
		if (!cform.missing_zip.value.match(/^[0-9]{5}(\-[0-9]{4})?$/)) return false; //check for validly formatted zip
		else return true;
	}//end US choice
	else if (document.getElementById('intlmiss2').checked) {//begin non-US choice
		if (!cform.missing_country.options[cform.missing_country.selectedIndex].value.match(/[a-z][a-z]/i)) return false;
		else if (cform.missing_country.options[cform.missing_country.selectedIndex].value == 'US') return false;
		else return true;
	}//end non-US choice
	else return false; //no choice reflected
}

/********************************************************************************************************
 *					SET FAVORITE FUNCTIONS						*
 ********************************************** START ***************************************************/
function loadFavoriteIcons() {
	setFavoriteIconOnClick("story");
	setFavoriteIconOnClick("event");
	setFavoriteIconOnClick("drink");
	setFavoriteIconOnClick("drink_summer");
	initFavoriteIconStatus("story");
	initFavoriteIconStatus("event");
}

function setFavoriteIconOnClick(prefix) {
	$(".set_favorite_" + prefix).each(function(index, elm) {
		var controller = getFavoriteIconController(prefix);
		elm.onclick = function() {
			var id = getFavoriteIconID(this);
			
			if(controller && id) {
				var date = new Date();
				setFavorite("/" + controller + "/setfavorite/" + id + "?time=" + date.getTime(), elm, {"controller" : controller, "id" : id});
				
				// set google analytics for favoriting
				if(typeof pageTracker != "undefined") {
					pageTracker._trackEvent("Get a Friend In", "Success", controller, id);
				}
			}
			return false;
		}
	});
}

function setFavoriteIconID(prefix, id) {
	$(".set_favorite_" + prefix).each(function(index, elm) {
		elm.setAttribute("id", "set_favorite_" + prefix + "_id_" + id);
	});
}

function getFavoriteIconID(elm) {
	var id = elm.getAttribute("id");
	if(id) {
		id = id.split("_");
		id = id.length > 1 ? id[id.length - 1] : 0;
	}
	return id;
}

function initFavoriteIconStatus(prefix) {
	$(".set_favorite_" + prefix).each(function(index, elm) {
		var controller = getFavoriteIconController(prefix);
		var id = getFavoriteIconID(elm);
		
		setFavoriteIconImage(elm, 0);
		
		//var img = getFavoriteIconImage(elm);
		//img.src = '/img/mostloved/heart_loading.gif';
		
		if(controller && id) {
			var date = new Date();
			var url = "/" + controller + "/favoriteexists/" + id + "?time=" + date.getTime();
			$.get(url, {},
				function(data) {
					setFavoriteIconImage(elm, data);
				}
			);
		}
	});
}

function getFavoriteIconController(prefix) {
	var controller = false;
	switch(prefix) {
		case "story": controller = "stories"; break;
		case "event": controller = "events"; break;
		case "drink": controller = "drinks"; break;
		case "drink_summer": controller = "drinks"; break;
		
		default : controller = false;
	}
	return controller;
}

function getFavoriteIconImage(elm) {
	var img = elm.getElementsByTagName("img");
	img = img.length > 0 ? img.item(0) : false;
	
	return img;
}

function setFavoriteIconImage(elm, status) {
	var img = getFavoriteIconImage(elm);
	if(img) {
		img.setAttribute("src", status == 1 ? "/img/mostloved/heart_red.gif" : "/img/mostloved/heart.gif");
	}
}

function setFavorite(url, elm, options) {
	var img = getFavoriteIconImage(elm);
	if(img.getAttribute("src").indexOf("red") > 0) {
		setFavoriteIconImage(elm, 0);
	}
	else {
		setFavoriteIconImage(elm, 1);
	}
	
	$.get(url, {},
		function(data) {
			setFavoriteIconImage(elm, data);
			
			if(data == 1 && !ISUK) {
				setFavoriteToFacebook(data, options);
			}
		}
	);
	return false;
}

function trackShare(notes) {
	var date = new Date();
	var url = "/stories/trackshare/" + notes + "?time=" + date.getTime();
	alert(url);
	$.get(url, {},
		function(data) {}
	);
	return false;
}
/*********************************** END: SET FAVORITE FUNCTIONS ****************************************/

/********************************************************************************************************
 *					ITEMS REACTIONS FUNCTIONS					*
 ********************************************** START ***************************************************/
function loadItemReactionsIcons() {
	setItemReactionIconOnClick();
	
	initItemReactionsIconsStatus();
}

function initItemReactionsIconsStatus() {
	$(".item_reaction").each(function(index, elm) {
		var url = elm.getAttribute("exists_href");
		if(url) {
			$.get(url, {},
				function(data) {
					if(data == 1) {
						$(elm).addClass("active");
					}
				}
			);
		}
	});
}

function setItemReactionIconOnClick() {
	$(".item_reaction").each(function(index, elm) {
		elm.onclick = function() {
			var theElm = $(this);
			if (!theElm.hasClass('loading') && !theElm.hasClass('active')) {
				theElm.addClass('loading');
		
				var url = elm.href ? elm.href.toString() : false;
				if(url) {
					var date = new Date();
					url += "?time=" + date.getTime();
					$.get(url, {},
						function(data) {
							if(data == 1) {
								//on success, tell user that it worked
								theElm.removeClass('loading').addClass('active');
								
								if(!ISUK) {
									var parts = url.split("/");
									var controller = parts[3];
									var reaction_type = parts[5];
									var item_id = parts[6];
									item_id = item_id.split("?");
									item_id = item_id[0];
									
									reactionToFacebook(data, {"controller" : controller, "reaction_type" : reaction_type, "id" : item_id});
								}
								
							} else {
								alert("There was an error trying to execute this action.\nPlease try again later");
								theElm.removeClass('loading');
							}
						}
					);
				}
			}
			return false;
		}
	});
}
/*********************************** END: ITEMS REACTIONS FUNCTIONS *************************************/

/********************************************************************************************************
 *					SHARE ITEMS FUNCTIONS						*
 ********************************************** START ***************************************************/
function loadShareWithAFriendIcons() {
	setShareWithAFriendIconOnClick();
}

function setShareWithAFriendIconOnClick() {
	$(".share_item").each(function(index, elm) {
		elm.onclick = function() {
			var url = elm.href ? elm.href.toString() : false;
			if(url) {
				showShareWithAFriendPopup(url);
			}
			return false;
		}
	});
}

function setShareWithAFriendIconHref(prefix, id) {
	$("." + prefix + "_share").each(function(index, elm) {
		var url = elm.href ? elm.href.toString() : false;
		if(url) {
			var pos = url.lastIndexOf("/");
			if(pos) {
				url = url.substring(0, pos + 1);
			}
			url += id;
			elm.href = url;
		}
	});
}

function showShareWithAFriendPopup(url) {
	$("#share").each(function(index, elm) {
		var iframe = document.createElement("iframe");
		iframe.style.width = '395px';
		iframe.style.height = '285px';
		iframe.scrolling = "no";
		iframe.boder = 0;
		iframe.frameBorder = 0;
		iframe.scrolling = "no";
		iframe.style.overflow = "hidden";
		iframe.src = url;
		
		elm.appendChild(iframe);
	});
	
	$('#coverup').css({'display' : 'block', 'opacity' : '0'}).fadeTo(800, 0.8);
	$("#share").fadeIn(800);
}

function hideShareWithAFriendPopup() {
	$('#coverup').fadeOut(800);
	$('#share').fadeOut(800);
	
	$("#share iframe").each(function(index, elm) {
		var parent = elm.parentNode;
		if(parent) {
			parent.removeChild(elm);
		}
	});
}


function setSendSMSIconOnClick() {
	$(".sms_item").each(function(index, elm) {
		elm.onclick = function() {
			var url = elm.href ? elm.href.toString() : false;
			if(url) {
				showSendSMSPopup(url);
			}
			return false;
		}
	});
}

/*********************************** END: SHARE ITEMS FUNCTIONS ******************************************/

/********************************************************************************************************
 *					FACEBOOK FUNCTIONS						*
 ********************************************** START ***************************************************/
function setFacebookShareIconHref(prefix, id) {
	$("." + prefix + "_facebook_share").each(function(index, elm) {
		var url = elm.href ? elm.href.toString() : false;
		if(url) {
			var pos = url.lastIndexOf("/");
			if(pos) {
				url = url.substring(0, pos + 1);
			}
			url += id;
			elm.href = url;
		}
	});
}

function shareInFacebook(elm) {
	var u = location.href;
	var t = document.title;
	
	if(u) {
		u += (u.indexOf('?') >= 0 ? "" : "?") + "&pid=27";
	}
	
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=1, status=0, width=626, height=436');
	//openPopup('/facebook/popup?action=share&u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t), 626, 436, true, true, 'sharer');
	
	var url = elm.href ? elm.href.toString() : "";
	if(url) {
		$.get(url, {},
			function(data) {}
		);
	}
	
	return false;
}

function setFavoriteToFacebook(data, options) {
	try {
		// var options = {
		// 			"func" : setFavoriteToFacebookAction, 
		// 			"params" : new Array(data, options),
		// 			"perms" : "publish_stream",
		// 			"oncomplete" : checkSetFavoriteToFacebookResult,
		// 			"onerror" : setFavoriteToFacebookError
		// 		};
		// 		MyFBWorkFlow.setMyFacebookOptions(options);
		// 		MyFBWorkFlow.executeAllowApi();
		
		FB.login(function(response) {
		  if (response.session) {
		    if (response.perms) {
		      // user is logged in and granted some permissions.
		      // perms is a comma separated list of granted permissions
				setFavoriteToFacebookAction(data, options);
		    } else {
		    }
		  } else {
		    // user is not logged in
		  }
		}, {perms:'publish_stream'});
		
	}
	catch(e) {
		alert(e.message ? e.message : e);
	}
}

//this needs to be in a different function because the browsers cache the requests. So each request should have a time variable.
function setFavoriteToFacebookAction(data, options) {
	var query_string = "&value=" + data;
	if(options) {
		query_string += options.controller ? "&model=" + getItemModelByController(options.controller) : "";
		query_string += options.id ? "&id=" + options.id : "";
	}
	var date = new Date();
	date = date.getTime();

	var url = "/facebook/executeaction/publishsetfavoritestream?" + query_string + "&time=" + date;
	
	return MyLib.AjaxHandler.gets(url, {"result_type" : 2});
}

function checkSetFavoriteToFacebookResult(result) {
	if(result == 1) {
		//alert("Loved item published successfully in your facebook wall.");
	}
	else {
		//alert("There was a problem to post your love action in your facebook wall.\nPlease try again later.");
	}
}

function setFavoriteToFacebookError(error) {
	if(error == "LIMIT REACHED") {
		//alert("Sorry we cannot publish this stream to your facebook wall because you exceed facebook streams limit.");
	}
	else {
		//alert("There was an exception to post your love action in your facebook wall.\nPlease try again later.");
	}
}

function reactionToFacebook(data, options) {
	try {
		// var options = {
		// 			"func" : reactionToFacebookAction, 
		// 			"params" : new Array(data, options),
		// 			"perms" : "publish_stream",
		// 			"oncomplete" : checkReactionToFacebookResult,
		// 			"onerror" : reactionToFacebookError
		// 		};
		// 		MyFBWorkFlow.setMyFacebookOptions(options);
		// 		MyFBWorkFlow.executeAllowApi();
		
		FB.login(function(response) {
		  if (response.session) {
		    if (response.perms) {
		      // user is logged in and granted some permissions.
		      // perms is a comma separated list of granted permissions
				reactionToFacebookAction(data, options);
		    } else {
		    }
		  } else {
		    // user is not logged in
			var x = 1;
		  }
		}, {perms:'publish_stream'});
		
	}
	catch(e) {
		alert(e.message ? e.message : e);
	}
}

//this needs to be in a different function because the browsers cache the requests. So each request should have a time variable.
function reactionToFacebookAction(data, options) {
	var query_string = "&value=" + data;
	if(options) {
		query_string += options.controller ? "&model=" + getItemModelByController(options.controller) : "";
		query_string += options.id ? "&id=" + options.id : "";
		query_string += options.reaction_type ? "&reaction_type=" + options.reaction_type : "";
	}
	var date = new Date();
	date = date.getTime();

	var url = "/facebook/executeaction/publishreactionstream?" + query_string + "&time=" + date;
	
	return MyLib.AjaxHandler.gets(url, {"result_type" : 2});
}

function checkReactionToFacebookResult(result) {
	if(result == 1) {
		//alert("Loved item published successfully in your facebook wall.");
	}
	else {
		//alert("There was a problem to post your love action in your facebook wall.\nPlease try again later.");
	}
}

function reactionToFacebookError(error) {
	if(error == "LIMIT REACHED") {
		//alert("Sorry we cannot publish this stream to your facebook wall because you exceed facebook streams limit.");
	}
	else {
		//alert("There was an exception to post your love action in your facebook wall.\nPlease try again later.");
	}
}
/*********************************** END: FACEBOOK FUNCTIONS ******************************************/

/********************************************************************************************************
 *					POPUP FUNCTIONS							*
 ********************************************** START ***************************************************/
var isMSIE = navigator.userAgent.indexOf("MSIE") != -1;
var showModalDialog = false;
var popup_removed_flash_elms = new Array();

function simulatePopup(url, width, height, scrollable, resizable, window_name) {
	var window_id = window_name.toString().split(' ').join('');	
	
	/******** START: IFRAME HTML ********/
	var main_div = document.createElement('div');
	main_div.id = window_id;
	main_div.style.display = "block";
	main_div.style.position = "absolute";
	main_div.style.backgroundColor = "#FFF";
	
	//TODO: resizable feature
	//TODO: set main_div css
	
	var iframe = document.createElement('iframe');
	iframe.src = url;
	iframe.width = width;
	iframe.height = height;
	iframe.scrolling = typeof(scrollable) == "undefined" || !scrollable || scrollable == 0 ? "no" : "auto";
	iframe.style.border = "0px solid #FFF";
	
	main_div.appendChild(iframe);
	
	document.body.appendChild(main_div);
	
	centerElm(window_name);
	/******** END: IFRAME HTML ********/
	
	/******** START: FLASH OBJECTS ********/
	var removed_elms = MyLib.FlashHandler.removeAllFlashObjects();

	var index = -1, popup_removed_flash_elm;
	for(var i = 0; i < popup_removed_flash_elms.length; ++i) {
		popup_removed_flash_elm = popup_removed_flash_elms[i];
		if(popup_removed_flash_elm.id == window_id) {
			index = i;
			break;
		}
	}
	
	if(index >= 0) {
		popup_removed_flash_elms[index].elms = removed_elms;
	}
	else {
		popup_removed_flash_elms.push({"id" : window_id, "elms" : removed_elms});
	}
	/******** END: FLASH OBJECTS ********/

	return main_div;
}

function closeSimulatedPopup(window_name) {
	var window_id = window_name.toString().split(' ').join('');	
	
	var elm = document.getElementById(window_id);
	if(elm) {
		var parent_node = elm.parentNode;
		if(parent_node) {
			parent_node.removeChild(elm);
			
			/******** START: FLASH OBJECTS ********/
			var index = -1;
			for(var i = 0; i < popup_removed_flash_elms.length; ++i) {
				popup_removed_flash_elm = popup_removed_flash_elms[i];
				if(popup_removed_flash_elm.id == window_id) {
					index = i;
					break;
				}
			}
		
			if(index >= 0) {
				var removed_elms = popup_removed_flash_elms[index].elms;
				//MyLib.FlashHandler.addRemovedFlashObjects(removed_elms);
				
				popup_removed_flash_elms[index] = popup_removed_flash_elms[popup_removed_flash_elms.length - 1];
				popup_removed_flash_elms.pop();
			}
			/******** END: FLASH OBJECTS ********/
		}
	}
}

function openPopup(url, width, height, scrollable, resizable, window_name) {
//alert(url+", "+width+", "+height+", "+scrollable+", "+resizable+", "+window_name);
	var x = parseInt(screen.availWidth / 2.0) - (width / 2.0);
	var y = parseInt(screen.availHeight / 2.0) - (height / 2.0);

	var scroll = typeof(scrollable) == "undefined" || !scrollable || scrollable == 0 ? "no" : "yes";
	var resize = typeof(resizable) == "undefined" || !resizable || resizable == 0 ? "no": "yes";
	window_name = typeof(window_name) == "undefined" || !window_name || window_name == 0 ? "PSC_POPUP" : window_name;
	
	if(width > screen.availWidth || width <= 0 || typeof(width) == "undefined" || width >= screen.width) width = screen.availWidth;
	if(height > screen.height || height <= 0 || typeof(height) == "undefined" || height >= screen.height) height = screen.availHeight;
	
	x = Math.round(x);
	y = Math.round(y);
	if(x < 0) x = 0;
	if(y < 0) y = 0;
	
	width = Math.round(width);
	height = Math.round(height);

	var win = null;
	if(showModalDialog && isMSIE) {
		var features = "resizable:"+resize+";scroll:"+scroll+";status:no;center:yes;help:no;dialogWidth:" + width + "px;dialogHeight:" + height + "px;";
	//alert(url+", "+window+", "+features);	
		win = window.showModalDialog(url, window, features);
	}
	else {
		if(isMSIE)  {
			resize = "yes";
		}
		
		var features = "left=" + x + ",top=" + y + ",width=" + width + ",height=" + height + ",toolbar=0,resizable="+ resize +",status=no,scrollbars="+ scroll;
	//alert(url+", "+window_name+", "+features);	
		win = window.open(url, window_name, features); 
	}

//alert(win);	
	if(win) {
		if(typeof win.resizeTo == "function") {
			win.resizeTo(width,height);
		}
		if(typeof win.moveTo == "function") {
			win.moveTo(x,y);
		}
		if(typeof win.focus == "function") {
			win.focus();
		}
	}/*
	else {
		url += (url.indexOf("?") == -1 ? "?" : "&") + "simulated_popup_name=" + window_name;
		simulatePopup(url, width, height, scrollable, resizable, window_name);
	}*/
	return win;
}
/*********************************** END: POPUP FUNCTIONS ******************************************/

