
//IUR3 Remote API
//(c) www.disney.com 2005



//function IURCommand(reg_url, task, promotion_id, skin, next_url, site_code, member_name,
//password, ageBand, fullScreen, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10,...) {


//SzP: 06/10/2005 - IUR3 version.


//TCW: 26/2/2001 - Rewrote this function to:
//1. allow for more than 10 answers to be submitted
//2. allow for a total length of more than 255 characters to be submitted as answers

//TCW: 18/4/2001 - Changed declaration of answers array to ensure no error in the case when there are less than 8 arguments

var openwin= null;

//this is for vbackward compatibility with IUR2 sites. simply calls launchIUR()
//with the appropriate parameters
function IURCommand() {
	var answers
	if (arguments.length > 8) {
		answers	= new Array(arguments.length - 8);
	} else {
		answers	= null;
	}

	var reg_url	= arguments[0];

	var task	= arguments[1];
	var promotion_id= encodeURIComponent(arguments[2]);
	var skin_name	= encodeURIComponent(arguments[3]);
	var next_url	= encodeURIComponent(arguments[4]);
	var site_code	= encodeURIComponent(arguments[5]);
	var member_name	= encodeURIComponent(arguments[6]);
	var password	= encodeURIComponent(arguments[7]);

	//Loop through and retrieve the answers - arguments 8 to n. (Will retrieve
	//all answers regardless of how many).
	for (var i = 8; i < arguments.length; i++) {
		answers[i - 8] = encodeURIComponent(arguments[i]);
	}

	if( answers==null ) {
		answers = new Array(0);
	}
	
	_launchIURInternal(
			/* target_url */ reg_url, 
			/* task */ task, 
			/* promotion_id */ promotion_id, 
			/* skin_name */ skin_name, 
			/* next_url */ next_url, 
			/* site_code */ site_code, 
			/* member_name */ member_name, 
			/* password */ password,
			/* ageBand */ "",
			/* fullScreen */ "",	
			/* swid */ "",	
			/* answers */ answers,
			/* callbackFunction*/ null); 

}	


function launchIUR() {

	var answers = null;

	// Retrieve arguments 0 - 9
	var reg_url = arguments[0];
	var task = arguments[1];
	var promotion_id = encodeURIComponent(arguments[2]);
	var skin_name	 = encodeURIComponent(arguments[3]);
	var next_url = encodeURIComponent(arguments[4]);
	var site_code = encodeURIComponent(arguments[5]);
	var member_name = encodeURIComponent(arguments[6]);
	var password = encodeURIComponent(arguments[7]);
	var ageBand = encodeURIComponent(arguments[8]);
	var fullScreen = encodeURIComponent(arguments[9]);

	if (arguments[10] instanceof Array) {
		answers = arguments[10]
	} else if (arguments.length > 10 && arguments[10] != null) {
		answers = new Array(arguments.length - 10);
		// Loop through and retrieve the answers - arguments 10 to n. (Will retrieve
		// all answers regardless of how many).
		for (var i = 10; i < arguments.length; i++) {
			answers[i - 10] = encodeURIComponent(arguments[i]);
		}
	}
	if( answers==null ) {
		answers = new Array(0);
	}
	_launchIURInternal(
			/* target_url */ reg_url, 
			/* task */ task, 
			/* promotion_id */ promotion_id, 
			/* skin_name */ skin_name, 
			/* next_url */ next_url, 
			/* site_code */ site_code, 
			/* member_name */ member_name, 
			/* password */ password,
			/* ageBand */ ageBand,
			/* fullScreen */ fullScreen,
			/* swid */ "",	
			/* answers */ answers,
			/* callbackFunction*/ null);
}

//compared to launchIUR this method has an additional SWID parameter
function launchIUR_v2() {

	var answers = null;
	// Retrieve arguments 0 - 10
	var reg_url = arguments[0];
	var task = arguments[1];
	var promotion_id = encodeURIComponent(arguments[2]);
	var skin_name	 = encodeURIComponent(arguments[3]);
	var next_url = encodeURIComponent(arguments[4]);
	var site_code = encodeURIComponent(arguments[5]);
	if (arguments[6].indexOf("@") == -1) {
		var member_name = encodeURIComponent(arguments[6]);
	} else {
		var member_name = arguments[6].replace("+","%2b");
	}
	var password = encodeURIComponent(arguments[7]);
	var ageBand = encodeURIComponent(arguments[8]);
	var fullScreen = encodeURIComponent(arguments[9]);
	var swid	 = encodeURIComponent(arguments[10]);

	if (arguments[11] instanceof Array) {
		answers = arguments[11]
	} else if(arguments.length > 11) {
		answers = new Array(arguments.length - 11);
		// Loop through and retrieve the answers - arguments 11 to n. (Will
		// retrieve all answers regardless of how many).
		for (var i = 11; i < arguments.length; i++) {
			answers[i - 11] = encodeURIComponent(arguments[i]);
		}
	}

	if( answers==null ) {
		answers = new Array(0);
	}
	_launchIURInternal(
			/* target_url */ reg_url, 
			/* task */ task, 
			/* promotion_id */ promotion_id, 
			/* skin_name */ skin_name, 
			/* next_url */ next_url, 
			/* site_code */ site_code, 
			/* member_name */ member_name, 
			/* password */ password,
			/* ageBand */ ageBand,
			/* fullScreen */ fullScreen,
			/* swid */ swid,
			/* answers */ answers,
			/* callbackFunction*/ null);	
}



//compared to launchIUR_v2, answers are supported just as Array
function launchIUR_v3( reg_url, task, promotion_id, skin_name, next_url, site_code, member_name,
					   password, ageBand, fullScreen, swid, answers, callbackFunction )
{
	
	if (member_name.indexOf("@") == -1) {
		member_name = encodeURIComponent(member_name);
	} else {
		member_name = member_name.replace("+","%2b");
	}
	if( answers==null ) {
		answers = new Array(0);
	}
	
	_launchIURInternal(
			/* target_url */ reg_url, 
			/* task */ task, 
			/* promotion_id */ promotion_id, 
			/* skin_name */ skin_name, 
			/* next_url */ next_url, 
			/* site_code */ site_code, 
			/* member_name */ member_name, 
			/* password */ password,
			/* ageBand */ ageBand,
			/* fullScreen */ fullScreen,
			/* swid */ swid,
			/* answers */ answers,
			/* callbackFunction*/ callbackFunction);	
}

//This method is for internal use only, it can change any time
//without notice so never call it directly
function _launchIURInternal() {

	// Declare variables
	htmlString	= "";
	var width	= 460;
	var height	= 420;
	var scrollbars	= 0;
	var resizable	= 0;
	var features	= "";

	// Retrieve arguments 0 - 10
	var reg_url = arguments[0];
	var task = arguments[1];
	var promotion_id = encodeURIComponent(arguments[2]);
	var skin_name	 = encodeURIComponent(arguments[3]);
	var next_url = encodeURIComponent(arguments[4]);
	var site_code = encodeURIComponent(arguments[5]);

	if (arguments[6].indexOf("@") == -1) {
		var member_name = encodeURIComponent(arguments[6]);
	} else {
		var member_name = arguments[6].replace("+","%2b");
	}
	var password = encodeURIComponent(arguments[7]);
	var ageBand = encodeURIComponent(arguments[8]);
	var layout = encodeURIComponent(arguments[9]);
	var swid	 = encodeURIComponent(arguments[10]);

	var fullScreen;
	if (layout == 'true' || layout == 'fullScreen' || layout == 'widget') {
		fullScreen = 'true';
	}

	reg_url = IURjsUtil.fixRegUrl(reg_url);

	var answers = arguments[11];
	var callbackFunction = arguments[12];
/*
	if (arguments[11] instanceof Array) {
		answers = arguments[11]
	} else if (arguments[11] == null) {
		answers = new Array()	 
	} else if(arguments.length > 11) {
		answers = new Array(arguments.length - 11);
		// Loop through and retrieve the answers - arguments 11 to n. (Will retrieve
		// all answers regardless of how many).
		for (var i = 11; i < arguments.length; i++) {
			answers[i - 11] = encodeURIComponent(arguments[i]);
		}
	}
*/
	if (task!='homepage') {
		features = "width=460,height=420,scrollbars=0,resizable=0,menubar=0,toolbar=0,location=0,directories=0,status=0,copyhistory=0";
	}

	if (task == 'sc_modify') {
		task = 'modify'
	}
	if (task == 'guardian_modify') {
		task = 'modify'
	}

	target_url = "";
	target_url += reg_url + "/" + getPageByTask(task) + "?task=" + task;

	function getPageByTask(task) {

		if (task=='homepage') { 
			return "homepage.htm";
		}

		if (task=='invite') {
			return "invite.htm";
		}

		if (task=='password_forgot' || task=='hint') {
			return "hint.htm";
		}

		if (task=='submit_promotion'
			|| task=='member_login'
				|| task=='login'
					|| task=='modify'
						|| task=='modify_details_only') {
			return "login.htm";
		}

		if (task=='member_logout' || task=='logout') {
			return "logout.htm";
		}	 

		if (task=='register_full_screen') {
			return "fullscreeninfo.htm";
		}	 

		return "RegService";
	}

	// -------------------------------------------------------------------------------------------------------------------------------
	// Add paramater pairs if defined and non-zero length
	function AddParam (name, value) {
		if (isNotEmpty(value)) {
			target_url += "&" + name + "=" + value;
		}
	}

	function AddFormParam (name, value) { 
		if (isNotEmpty(value)) {
			htmlString += "<input type='hidden' name='" + name + "' value='" + value + "'>\n";
		} else {
			htmlString += "<input type='hidden' name='" + name + "' value=''>\n";	
		}
	}

	function isNotEmpty(value){

		return (value != null && value.toLowerCase()!= 'null' && value.length != 0 && value != 'undefined');
	}

	AddParam("p",	promotion_id);
	AddParam("skin_name",	skin_name);
	AddParam("next_url",	next_url);
	AddParam("site_code",	site_code);
	AddParam("member_name",	member_name);
	AddParam("ageBand",	 ageBand);
	AddParam("fullScreen", fullScreen); 
	AddParam("swid",	swid);

	// Build up HTML string to write to the new window
	htmlString += "<html><head></head><body>";
	htmlString += "<form id='IURLaunch' name='form0' method='post' action=\"" + target_url + "\">\n";

	var securePasswordSet = false;
	if (target_url.indexOf("https") == 0 ) {
		AddFormParam("password",	password);
		if(password.length > 0){
			securePasswordSet = true;
		}
	}

	// Add the rest of the answer params
	for (var j = 0; j < answers.length; j++) {
		AddFormParam("q" + (j + 1), answers[j]);
	}

	htmlString += "<input type=hidden> </input></form></body></html>\n";
	if(!securePasswordSet && layout == 'widget' && (task == 'login' || task == 'invite' || task == 'member_login' || task == 'submit_promotion')) {
		var argsArray = arguments;
		if( argsArray[0].lastIndexOf('https') != 0 ) {		
			alert( 'Login Widget must be configured to communicate via HTTPS!' );
			return;
		}
		loadLoginWidgetFunctions(argsArray[0], function() {

			AddParam("fullScreen", "true");
			AddParam("loginWidget", "true");

			for (var j = 0; j < answers.length; j++) {
				AddParam("q" + (j + 1), answers[j]);
			}
			showLoginWidget(target_url);
			var cookieAge = 365;
			
			if(callbackFunction=='') {
				callbackFunction = "window.parent.location.reload(true);"
			}
			
			$('body').append("<script>" +
					"pm.unbind();" +
					"function callbackFunc(){"+callbackFunction+"} " +
					"pm.bind('forwardToIUR', function(data) {" +
					"launchIUR_v3(" +
					"	'"+argsArray[0]+"'," +
					"	'"+argsArray[1]+"'," +
					"	'"+encodeURIComponent(argsArray[2])+"'," +
					"	'"+encodeURIComponent(argsArray[3])+"'," +
					"	'"+encodeURIComponent(argsArray[4])+"'," +
					"	'"+encodeURIComponent(argsArray[5])+"'," +
					"	data['member_name']," +
					"	data['password']," +
					"	'"+encodeURIComponent(argsArray[8])+"'," +
					"	'fullScreen'," +
					"	'"+encodeURIComponent(argsArray[10])+"'," +
					"	'"+encodeURIComponent(argsArray[11])+"'" +
					"	);" +
					"},'"+argsArray[0]+"');" +
					"pm.bind('forwardToIURModify', function(data) {" +
					"launchIUR_v3(" +
					"	'"+argsArray[0]+"'," +
					"	'modify'," +
					"	'"+encodeURIComponent(argsArray[2])+"'," +
					"	'"+encodeURIComponent(argsArray[3])+"'," +
					"	'"+encodeURIComponent(argsArray[4])+"'," +
					"	'"+encodeURIComponent(argsArray[5])+"'," +
					"	data['member_name']," +
					"	data['password']," +
					"	'"+encodeURIComponent(argsArray[8])+"'," +
					"	'fullScreen'," +
					"	'"+encodeURIComponent(argsArray[10])+"'," +
					"	'"+encodeURIComponent(argsArray[11])+"'" +
					"	);" +
					"},'"+argsArray[0]+"');" +
					"pm.bind('setCookies', function(data) {" +
					"	setCookie('SWID', data['SWID'], "+cookieAge+", stripSubdomain(document.location.host));" +
					"	setCookie('BLUE', data['BLUE'], "+cookieAge+", stripSubdomain(document.location.host));" +
					"},'"+argsArray[0]+"');" +
					"pm.bind('closeIURLoginWidget', function() {" +
					"	$.modal.close();" +
					"	$('#iur-login-widget-dialog').remove();" +
					"},'"+argsArray[0]+"');" +
			"</script>");
		});
	} else {

		var newdocument;
		if(fullScreen == 'true' || layout == 'iframe'){ 
			newdocument = this.document;
		}else{ // popup handling
			// if openwin and openwin.open exist, and openwin.closed isn't true,
			// then close it
			if (openwin && openwin.open && !openwin.closed) openwin.close();

			// Open a temporary window on the target URL, create the form and
			// immediately submit it to the new target URL.
			if (features=="")
			{ // this stops netscape from opening the homepage in a featureless
				// window (no nav bar no menus etc)
				openwin = this.open("", task);
			} else {
				openwin = this.open("", task, features);
			}
			newdocument = openwin.document;
		}
		newdocument.write(htmlString);
		newdocument.close();
		// the following can not be: newdocument.form0.submit(); because IE 4.5
		// on Mac does not like it
		newdocument.forms[0].submit();
	}
}

//the same logic applies to iurclient.js, we cannot modularize the code yet so
//if anything changes, the logic in that file should be changed as well
function showLoginWidget(target_url){
	$('body').append('<div id="iur-login-widget-dialog" title="LOGIN TO DISNEY" style="overflow:hidden;"><iframe id="modalIframeId" name="modalIframeId" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" title="Dialog Title" allowTransparency="true" style="display:none; background-color: transparent;">Your browser does not support</iframe></div>');

	target_url += '&origin='+document.location.href;
	
	target_url += '&closeUrl='+createWidgetClosePageUrl();
	
	$("#modalIframeId").css("width", "100%");
	$("#modalIframeId").css("height", "100%");

	$("#modalIframeId").attr("src", target_url);

	$('#iur-login-widget-dialog').modal({
		'overlayId' : 'iur-login-widget-modal-overlay',
		'containerId' : 'iur-login-widget-modal-container',
		'dataId' : 'iur-login-widget-modal-data'
	});
	$('#iur-login-widget-modal-overlay').css('background-color','#000');

	// iframe blinking fix in chrome
	var t = setTimeout ('$("#modalIframeId").show();',150);

	return false;
}

function setCookie(c_name,value,exdays,domain){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=value + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	c_value += ((domain==null) ? "" : "; domain="+domain);
	document.cookie=c_name + "=" + c_value;
}
var stripSubdomain = function(urlToStrip){
	if(urlToStrip == 'localhost'){
		return '';
	}
	var numberOfDots = urlToStrip.split('.').length - 1;
	if(numberOfDots > 1 && isNaN(urlToStrip.charAt(0))){
		var positionOfFirstDot = urlToStrip.indexOf('.');
	}else{
		return urlToStrip;
	}
	return urlToStrip.substring(positionOfFirstDot);
}

var IURjsUtil = {

		fixRegUrl: function (reg_url) {
			if (IURjsUtil.isDevInstance(window.location) && IURjsUtil.isNotDevTarget(reg_url)) { 
				reg_url = IURjsUtil.getProtocol(reg_url) + "test" + IURjsUtil.getHost(reg_url); 
			}
			return reg_url;
		},

		isDevInstance: function (location) {
			var host = location.host;
			return (host.substr(0,3) == "dev" || host.substr(0,7) == "staging" || host.substr(0,4) == "test");
		},

		isNotDevTarget: function (target) {
			var targetHost = IURjsUtil.getHost(target);
			return ((targetHost.substr(0,4) != "test") && (targetHost.substr(0,7) != "staging"));
		},	

		getProtocol: function (url) {
			if(url.indexOf("//") != -1) {
				return url.substr(0, url.indexOf("//") + 2);
			} else {
				return '';
			}	
		},

		getHost: function (url) {
			if (url.indexOf("//") != -1) {
				return url.substr(url.indexOf("//") + 2);
			} else {
				return url;
			}	
		}
}

var loadLoginWidgetFunctions = function(reg_url, callback) {
	var scriptsPath = reg_url + '/scripts/';

	if(typeof window['loginWidgetFunctionsLoaded'] == 'undefined'){
		window['loginWidgetFunctionsLoaded'] = true;
		$.getScript(scriptsPath + 'jquery.iurloginmodal.js', function(data, textStatus){
			$.getScript(scriptsPath + 'postmessage.js', function(data, textStatus){
				callback();
			});
		});
	}else{
		callback();
	}
}

function createWidgetClosePageUrl() {
	var actualUrl = document.location.href;
	if( actualUrl.lastIndexOf('/')>0 ) {
		actualUrl = actualUrl.substring( 0, actualUrl.lastIndexOf('/')+1 );
		
	}else {
		actualUrl += '/';
	}
	actualUrl += 'closeWidget.html';
	return actualUrl;
}
