/* Release 5.2 update CenterTile fix */

/*  4.12.1
	© Copyright United Airlines Inc.
	Homepage Deferred File Loader
	Rob O'Brien, Karthikeyan T, S. Davis, Ranjeet Gill. 
*/
var selectedSection = "HP";

var maImg = "/ual/asset/hdg_UnitedNews.gif"; /* the var HR_ER_mode is set if the HP is delivered in ER mode. Used to turn off components */

if (typeof HP_ER_mode == 'undefined') {
    var HP_ER_mode = false;
}

var writeSWNprotocol = (document.location.protocol == 'https:') ? 'https' : 'http'; /*  aff --> */
var affOn = true;
var sbsTimes = true;
var vsAffSwitch = 'F';
var affType = 1; /* insert intl text here */
var affCtryCode = 'us';
var affText1 = 'Search flights';
var affText2 = 'Book with miles';
var affAwardFare = 'Award travel fees up to USD 100.00';
var affPass0Msg = 'Please review the number of passengers and revise the entry if necessary.';
var affPass10Msg = 'The maximum passengers per itinerary is 9. Please revise your entry.';
var affMore1 = 'Upgrades, promotions, class, nonstops...';
var affMore2 = 'Service class, Maximum stops';
var affTripType = 2;
var ualhpdatedummy;
shop_depart = new Array()
shop_depart[0] = ""; /* end aff --> */

function ff30popup(wURL, varToPass) {
    window.open(wURL + varToPass, "ff29", "width=550,height=400,top=20,left=20,menubar=no,status=no,toolbar=no,resizable=yes,scrollbars=yes")
}

/* Fare Finder calendar files. These are dependant upon each other, so we nest them sequentially */
ua.utils.deferLoad('http://www.united.com/ual/asset/date_bimonth.js','script',function(){
	ua.utils.deferLoad('http://www.united.com/ual/asset/populate_bimonthcal1.1.js','script',function(){
		ua.utils.whenDefined({
			object: 'calendarReady',
			success: function(result){
				result.object();
			},
			stopOnReady: false
		});
	});
});

/* Top navigation init */
ua.utils.attachEvent(window,'load',function () {
	writeSWNav2(0);
});

Array.prototype.shuffle = function() {
	var s = [];
	while (this.length) {
		s.push(this.splice(Math.random() * this.length, 1));
	}
	while (s.length) {
		this.push(s.pop());
	}
	return this;
}


/* Load XML file for center tile images */
ua.utils.deferLoad('http://www.united.com/ual/asset/fs9.xml','xml',function(content) {
	var displayCount = 0;
		
	var parseXML = function(xml) {
		var tileArr = [],
			i = 0,
			len = 0,
			tiles = 0,
			maxTiles = 10,
			passCriteria = false,
			alreadyDisplayed = false,
			seeds = 0,
			displayed = [];
			
		/* Field positions, corresponding to tileArr created below. Just makes it easier to read references */
		var url = 0,
			rgb = 1,
			id = 2,
			src = 3,
			weight = 4,
			criteria = 5;
			
		/* Load the tiles into an array */
		$(xml).find("slide").each(function () {
			tileArr.push([
				$(this).attr("url"),
				$(this).attr("rgb"),
				$(this).attr("id"),
				$(this).attr("src"),
				$(this).attr("wt"), // weight
				'true' //$(this).attr("criteria")
			]);
		});
		
		/* 
		 * Do we have weighted tiles? Let's add additional entries 
		 * in the array to increase the chances they get displayed.
		 */
		tiles = tileArr.length;
		for (i=0;i<tiles;i++) {
			seeds = tileArr[i][weight];
			/* We use seeds>1 because we don't want an extra entry if the weight is only 1 */
			while (seeds>1) { 
				tileArr.push(tileArr[i]);
				seeds--;
			}
		}
		
		/* Randomize the tiles */
		tileArr.shuffle();
		
		/* Now create the image elements for the slideshow */
		len = tileArr.length; // Total number of tiles
		i = 0;
		
		/* While the number of displayed tiles is less than our limit, keep going! */
		while ((displayed.length < maxTiles) && (i < len)) {
			/* 
			 * Since tiles can have weight (ie: more than one entry in the array), we
			 * make sure an individual tile is only displayed once
			 */
			alreadyDisplayed = displayed.contains(tileArr[i][0][id]);
			
			/* If the criteria evaluates to true, we'll allow the tile */
			passCriteria = eval(tileArr[i][0][criteria]);
			
			if (!alreadyDisplayed && passCriteria) {
				$("#centertile").append('<a href="' + tileArr[i][0][url] + '" data-color="#' + tileArr[i][0][rgb] + '"><img id="centertile-' + tileArr[i][0][id] + '" width="258" height="350" src="' + tileArr[i][0][src] + '"/></a>');
				displayed.push(tileArr[i][0][id]);
			}
			
			i++;
		}
		
		/* Let the magic begin */
		startSlideshow();
		$('#slideContainer').fadeIn();
	};
	
	var startSlideshow = function(){
	    $('#centertile').cycle({
			fx: 'fade',
			speed: 1000,
			pause: 0,
			next: '#next',
			prev: '#prev',
			before: updateCounter, // function(currSlideElement, nextSlideElement, options, forwardFlag)
			timeout: 5000
		});
	};
	
		
	var updateCounter = function(currSlideElement, nextSlideElement, options, forwardFlag) {
		if (forwardFlag) {
			/* We're going forward */
			if (displayCount >= options.slideCount) {
				displayCount = 0; /* Reset if we've looped around */
			}
			displayCount += 1; 
		} else {
			/* We're going backward */
			if (displayCount <= 1) {
				displayCount = options.slideCount + 1; /* Reset if we've looped around */
			}
			displayCount -= 1; 
		}
		
		var caption = displayCount + ' of ' + options.slideCount;
		
		$('#slideCount').html(caption);
		doTheFade(null,$(nextSlideElement).attr('data-color'));
	};
	
	parseXML(content);
	
	$(document).ready(function() {
		$('#slideControls div').hover(
			function(){
				$(this).toggleClass('hover');
			}
		);
		$('#slideControls #flow').click(
			function(){
				$(this).toggleClass('pause');
				$(this).toggleClass('play');
				$('#centertile').cycle('toggle'); 
			}
		);
	});
}, true);
/* Error: $('#centertile').append('<a href="http://www.united.com/FS9alternate"><img src="http://content.united.com/ual/asset/FS9alternate.jpg" /></a>'); */


/* Flight Status tab */
ua.utils.deferLoad('http://www.united.com/ual/asset/ff30FlightStatus.html','html',function(thePage) {
    $('#ff29pane3').append(thePage);
    $('#ff29pane3').css('display', 'none'); 
	/* $('#flightStatusSelect').append(ff29FlightStatusOptions);  */
    updateDateList();
    document.forms.FlightStatus.reset();
    if (ff29modes == 3) {
        ff29click(3);
    }
});


ua.utils.deferLoad('http://www.united.com/ual/asset/ff30BookWithMiles.html','html',function(content) {
	$('#affAwdSrchOpts').append(content);
	$('#affAwdSrchOpts').css('display', 'none');
});

ua.utils.deferLoad('http://www.united.com/ual/asset/ff29pane2.html','html',function(content) {
	$('#ff29pane2').html(content);
});

/* United Vacations search form */
ua.utils.deferLoad('http://www.united.com/ual/asset/ff30VacationsTopHalf.html','html',function(content) {
	$('#ff29pane1sub4a').append(content);
	$('#ff29pane1sub4a').css('display', 'none');
});

ua.utils.deferLoad('http://www.united.com/ual/asset/ff30VacationsBottomHalf.html','html',function(content) {
	$('#ff29pane1sub4b').append(content); 
	$('#ff29pane1sub4b').css('display','none');
});

ua.utils.deferLoad('http://www.united.com/ual/asset/vo_tiles.js','script',function() {
	$("#divVOtiles").show();
	$('#topSlot').children().css('border', '0px');
	
	if ($.browser.msie) {
	    if ($.browser.version.substr(0, 1) > 6) {
	        $('.voCopy').css("padding-left", "6px");
	    }
	}
	
	if (ua.utils.getCookie("homeArpt")) {
	    document.getElementById('shop_from0').value = getCookie("homeArpt");
	    document.getElementById("vacationO").value = getCookie("homeArpt");
	}
});

/* When the page is done loading, we'll then add the 3rd party pixel tracking iframe */
//ua.utils.attachEvent(window,'load',function () {
setTimeout(function(){
	/* 
	 * Build the request for hp iframe for pixel tracking
	 * pass required parameters to the iframe query string
	 */
	var uValue = escape(document.location),
		rValue = escape(document.referrer),
		iframeQstr = "curLoc=" + uValue + "&refLoc=" + rValue,
		mileageLevel = ua.utils.getCookie('mileageLevel');
	
	if (mileageLevel.length > 0) {
		iframeQstr += '&mpl=' + mileageLevel; 
	}
	
	$(document.body).append('<IFRAME id="unitedMediaplex" name="mediaplexUnited" src="http://www.united.com/ual/asset/hp_mediaplexunited.html?' + iframeQstr + '" width="0" height="0" frameborder="0" ></iframe>');

	$('iframe#unitedMediaplex').load(function() {}); 
},5000);

ua.utils.deferLoad('http://www.united.com/ual/asset/CheckInOnline1.1.js','script',function() {
	var gotMPno = '',
		rememberME = ua.utils.getCookie("rememberME");
	
	$('#ff29pane2').css('display', 'none'); // Added for ECO Redesign June Rel-4.7
	
	if (rememberME.length > 0 && rememberME == "E") {
		gotMPno = ua.utils.getCookie("rememberEMAIL");
	}
	if (rememberME.length > 0 && rememberME == "M") {
		gotMPno = ua.utils.getCookie("getMP");
	}
	if (gotMPno.length > 0) {
		$('input:text[class="ecohpCheckin_MpNumber"]').attr('value', gotMPno);
		document.getElementById('remMP').checked = true;
		$('input:password[class="ecohpCheckin_Password"]').attr('value', '');
		$('input:text[class="ecohpCheckin_MpNumber"]').css('color', 'black');
		$('input:password[class="ecohpCheckin_Password"]').css('color', 'black');
	} else {
		$('input:text[class="ecohpCheckin_MpNumber"]').attr('value', 'MileagePlus # or email address');
		$('input:password[class="ecohpCheckin_Password"]').attr('value', 'Password');
		$('input:text[class="ecohpCheckin_MpNumber"]').css('color', 'gray');
		$('input:password[class="ecohpCheckin_Password"]').css('color', 'gray');
	}
	
	/* Check-In Online Content */
	if (ua.mp.loggedin) {
		$('#ci_logged').show();
		$('#checkInContent').hide();
	} else {
		$('#ci_logged').hide();
		$('#checkInContent').show();
	}
});	


/* Start DOM Ready Function */
$(document).ready(function () {
    document.getElementById('fade1').style.backgroundColor = "";
    document.getElementById('fade2').style.backgroundColor = "";
    document.getElementById('fade1').style.backgroundColor = "#ffffff";
    document.getElementById('fade2').style.backgroundColor = "#ffffff"; /* END Calendar Changes */
    $('#topLoginUserID').css("color", ($('#topLoginUserID').val() == 'MileagePlus # or email address' ? "#666" : "#333"))
    $('#topLoginUserID').focus(function () {
        if ($(this).val() == 'MileagePlus # or email address') {
            $(this).val('');
            $(this).css("color", "#333");
        }
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).val('MileagePlus # or email address');
            $(this).css("color", "#666");
        }
    });
    var e = $("#topLoginUserPass_text");
    var c = $("#topLoginUserPass_password");
    e.focus(function () {
        $(this).css({
            display: "none"
        });
        c.css({
            display: "block"
        });
        c.focus();
        $(this).val("")
    });
    c.blur(function () {
        if ($(this).val() == "") {
            e.val("Password");
            $(this).css({
                display: "none"
            });
            e.css({
                display: "block"
            })
        }
    });
    if (c.val() == "") {
        e.css({
            display: "block"
        });
        c.css({
            display: "none"
        })
    } else {
        e.css({
            display: "none"
        });
        c.css({
            display: "block"
        })
    }
	
    //	Start HP News
    if (window.ualhpNews) {
        var newsReel = "";
        for (ij = 0; ij < ualhpNews.length; ij++) {
            if (ualhpNews[ij].length > 3) {
                var ualColor = String(ualhpNews[ij][4]).trim();
                if (ualColor.length == 7 || ualColor.substr(0, 1) == "#") {
                    newsReel += '<li style="line-height: 1.6;"><a class="fs11 newsItem" href="' + ualhpNews[ij][3] + '" style="color: ' + ualColor + ' !IMPORTANT;">' + ualhpNews[ij][2] + '</a></li>';
                } else {
                    newsReel += '<li style="line-height: 1.6;"><a class="fs11 newsItem" href="' + ualhpNews[ij][3] + '">' + ualhpNews[ij][2] + '</a></li>';
                }
            } else {
                newsReel += '<li style="line-height: 1.6;"><a class="fs11 newsItem" href="' + ualhpNews[ij][3] + '">' + ualhpNews[ij][2] + '</a></li>';
            }
        }
        if ($.browser.msie && parseInt($.browser.version.substr(0, 1)) < 7) {
            $('#unitedNewsContent').append('<div class="carret" style="padding-left: 0px !IMPORTANT; padding-right: 4px !IMPORTANT; margin-left: 5px !IMPORTANT;"><ul>' + newsReel + '</ul></div>');
        } else {
            $('#unitedNewsContent').append('<div class="carret" style="padding-left: 0px !IMPORTANT; padding-right: 4px !IMPORTANT; margin-left: 10px !IMPORTANT;"><ul>' + newsReel + '</ul></div>');
        }
    }
	
    /*  determine login state */
    if (ua.mp.loggedin) {
        var strFirstAndLastName = ua.mp.M.firstName + ua.mp.M.lastName;
        if (strFirstAndLastName != "") {
            if (document.getElementById("nameHold")) {
                if (strFirstAndLastName.length <= 30 && (ua.mp.M.firstName.length <= 15 && ua.mp.M.lastName.length <= 15)) { /* write both */
                    document.getElementById("nameHold").innerHTML = ua.mp.M.firstName + ' ' + ua.mp.M.lastName;
                    document.getElementById("forHold").innerHTML = 'for ';
                } else {
                    if (ua.mp.M.firstName.length <= 15) { /* write first */
                        document.getElementById("nameHold").innerHTML = ua.mp.M.firstName;
                        document.getElementById("forHold").innerHTML = 'for ';
                    }
                }
                if (ua.mp.M.firstName.length > 15) { /* remove "for" */
                    document.getElementById("nameHold").innerHTML = ua.mp.M.firstName;
                }
            }
        }
        if (ua.mp.M.mpLevel != "" && ua.mp.M.mpBal != "") {
            document.getElementById('mpLevelHold').innerHTML = '<nobr>' + ua.mp.M.mpLevel + ' <span style="color:#999;"> | </span> </nobr><nobr>Miles: ' + ua.mp.M.mpBal.commafy() + '</nobr>';
        } 
		
		/* hide the MP login and guest login divs */
        document.getElementById("mileagePlus_login").style.display = "none";
        document.getElementById("joinMPcontainer").style.display = "none";
        document.getElementById("mploggedin").style.display = "block";
        document.getElementById("mpLoggedinContainer").style.display = "block";

        $('#myitins').attr("href", "https://www.ua2go.com/ci/DoLogin.jsp?return_to=itins");
        $('#myitins2').attr("href", "https://www.ua2go.com/ci/DoLogin.jsp?return_to=itins&navSource=HP07&linkTitle=a22myitineraries");
        $('#loginSwap1').attr("href", "https://www.ua2go.com/ci/Login.jsp?return_to=itins&navSource=Dropdown07&linkTitle=itineraries");
        $('#loginSwap2').attr("href", "https://travel.united.com/etc/webcheckin/listPnr.do?navSource=Dropdown07&linkTitle=checkin");
        var divHite = $('div.col3').height();
        if (divHite < 446) {
			$('div.col3').height(446);
		}
    } else { /* Not logged in, display log in content */
        document.getElementById("mploggedin").style.display = "none";
		
        $("#ci_cc").click(function () {
            $('#ci_tktNumber #label_searchValueId').html('Credit card #');
            $('#ci_searchValueId').attr('maxlength', 19)
            $('#ci_searchValueId').attr('value', '')
        });
		
        $("#ci_pnr").click(function () {
            $('#ci_tktNumber #label_searchValueId').html('Confirmation or e-ticket number');
            $('#ci_searchValueId').attr('maxlength', 14);
            $('#ci_searchValueId').attr('value', '')
        });
		
        if (ua.cookies.hasOwnProperty("rememberME")) {
            switch (ua.cookies.rememberME) {
            case "E":
                if (ua.cookies.hasOwnProperty("rememberEMAIL")) {
                    $('input.userId').val(ua.cookies.rememberEMAIL);
                    $(".remMP").check();
                    document.topLogin.userId.value = ua.cookies.rememberEMAIL;
                }
                break;
            case "M":
                if (ua.cookies.hasOwnProperty("getMP")) { // *.united.com
					rememberMP = ua.cookies.getMP;
				} else if (ua.cookies.hasOwnProperty("rememberMP")) {  // ua2go.com
					rememberMP = ua.cookies.rememberMP;
				}
                if (typeof rememberMP != 'undefined') {
                    $('input.userId').val(rememberMP);
                    $(".remMP").check();
                    document.topLogin.userId.value = rememberMP;
                }
                break;
            }
        }
        $('#loggedout').show();
        document.getElementById("mpLoggedinContainer").style.display = "none";
        document.getElementById("mileagePlus_login").style.display = "block";
        document.getElementById("joinMPcontainer").style.display = "block";
    }
	
    try {
        $('#unitedBenefits').show();
		
        if (showToolTips == 1) {
            $('#ci_gli a, #flightNum a').Tooltip({
                track: true,
                delay: 0,
                showURL: false,
                showBody: " - ",
                opacity: 0.90
            });
        }
    } catch (exception) {
    	// Do Nothing 
       	// alert("Caught an exception!\n\n"+exception);
    } 
	
	/* write timestamp @ footer */
    var futdate = new Date();
    var expdate = futdate.getTime();
    $('footerTimestamp').append('<img src="http://www.united.com/ual/asset/vstesthp.gif?timestamp=' + expdate + '" border="0" width="1" height="1">');
    $('div.col3').css('padding', 5);
    $('#myItinsEmplCheckin').addClass('dashTop');
    document.getElementById("flightSRC").selectedIndex = 0; // 229
    document.getElementById("flightCNN").selectedIndex = 0; // 229 
		
    /* Capture the enter event of certain forms on the page */
    $('#topLogin, #cio_MP, #authForm3, #FlightStatus ').keypress(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            switch (this.id) {
            case "topLogin":
                /*   if (ValidateUserId(this)) { */
                if (ValidateUserIdHome(this)) {
                    this.submit()
                }
                break
            case "cio_MP":
                if (ValidateUserId2(this)) {
                    this.submit()
                }
                break
            case "authForm3":
                if (ecodlSubmit3(this)) {
                    this.submit()
                }
                break
            case "FlightStatus":
                if (verify(this)) {
                    this.submit()
                }
                break
            }
        }
    });
}); /* End of DOM Ready Function */

$.fn.check = function () {
    return this.each(function () {
        this.checked = true;
    });
};

var currentUALsite = "US-EN";

function writeStartIn() {
    selObj = document.topLogin.sel_return_to;
    selObj.length = 0;
    for (q = 0; q < StartinSelectLst.length; q++) {
        selObj.options[q] = new Option(StartinSelectLst[q][0], StartinSelectLst[q][1]);
        if (StartinSelectLst[q][2].indexOf(selectedSection) > -1) selObj.options[q].selected = true
    }
}

/* The "unusedParam" is necessary because the flash movie which calls this function 
   passes 2 parameters and we want the second one as our "fade-to color"
 */
function doTheFade(unusedParam, toColor) {
	/* If the toColor doesn't begin with a hash, we'll add it because $.animate() is picky
	 * Using indexOf() is more performant than using RegExp: http://jsperf.com/find-character
	 */
	if (typeof divstofade === 'undefined') {
		divstofade = $('.hpDivsToFade');
	}
    if (toColor.indexOf('#') != 0) {
		toColor = '#' + toColor;
	}
    if (isHexCode(toColor)) {
        divstofade.stop().animate({
            backgroundColor: toColor
        }, 1000);
    }
}

