﻿/*Global Variables*/
var elqPPS;

var bShowValidator;

var sPreviousCountry;

var bSameValue;

Event.observe(window, "load", window_onLoad);

/* popup controllers */
function moreInfo_onMouseOver(event) {
	var oElement = Event.element(event);
	var oParentPositioning, oScrollOffsets, iLeft, iTop;
	if (oElement.match("img#MoreInfoIcon")) {
		oParentPositioning = $("textContainer").cumulativeOffset();
		oScrollOffsets = document.viewport.getScrollOffsets();
		iLeft = event.clientX - oParentPositioning.left + oScrollOffsets.left + 28;
		iTop = event.clientY - oParentPositioning.top + oScrollOffsets.top - 210;  
		
		var oMoreInfoBubble = $("MoreInfoBubble");
		oMoreInfoBubble.setStyle({left: iLeft + "px", top: iTop + "px"});
		oMoreInfoBubble.removeClassName("hidden");
		
		//add sitecatalyst tracking to hover event.
		var qs = new Querystring(); 
        var programID = qs.get("program")
        var strLink = "Registration - More Info Hover - " + programID;
        s=s_gi(s_account);  
        s.linkTrackVars='eVar8,events';  //use fileID
        s.linkTrackEvents='event16'; //'Registration Hover'
        s.events='event16';
        s.eVar8=programID;
        s.tl(this,'o',strLink);
	}
}

function moreInfo_onMouseOut(event) {
	var oElement = Event.element(event);
	if (oElement.match("img#MoreInfoIcon")) {
		$("MoreInfoBubble").addClassName("hidden");
	}
}

function npmScreenshot_onMouseOver(event) {
    var oElement = Event.element(event);
	var oParentPositioning, oScrollOffsets, iLeft, iTop;
	oParentPositioning = $("OrionNPMScreenshot").cumulativeOffset();
	oScrollOffsets = document.viewport.getScrollOffsets();
	iLeft = event.clientX - oParentPositioning.left + oScrollOffsets.left + 50;
	iTop = event.clientY - oParentPositioning.top + oScrollOffsets.top;  
	
	var oMoreInfoBubble = $("OrionNPMScreenshotLarge");
	oMoreInfoBubble.setStyle({left: iLeft + "px", top: iTop + "px"});
	oMoreInfoBubble.removeClassName("hidden");
		
	//add sitecatalyst tracking to hover event.
	var qs = new Querystring(); 
    var programID = qs.get("program")
    var strLink = "Registration - Screenshot Hover - " + programID;
    s=s_gi(s_account);  
    s.tl(this,'o',strLink);
}

function npmScreenshot_onMouseOut(event) {
	var oElement = Event.element(event);
	$("OrionNPMScreenshotLarge").addClassName("hidden");
}

function spCBubble_onMouseOver(event) {
    var oElement = Event.element(event);
    var oParentPositioning, oScrollOffsets, iLeft, iTop;
    if (oElement.match("span#spCBubble")) {
        oParentPositioning = $("container").cumulativeOffset();
        oScrollOffsets = document.viewport.getScrollOffsets();
        iLeft = event.clientX - oParentPositioning.left + oScrollOffsets.left + 38;
        iTop = event.clientY - oParentPositioning.top + oScrollOffsets.top - 210;

        var oMoreInfoBubble = $("noteBubble");
        oMoreInfoBubble.setStyle({ left: iLeft + "px", top: iTop + "px" });
        oMoreInfoBubble.removeClassName("hidden");
    }
}

function spCBubble_onMouseOut(event) {
    var oElement = Event.element(event);
    if (oElement.match("span#spCBubble")) {
        $("noteBubble").addClassName("hidden");
    }
}

/* form controllers */
function btnSubmit_onClick(event) {
	if (Page_ClientValidate('')) {
	    trackEvent17ForRegistration();
		$("lblTopErrorMessage").hide();
		
		if ($("lblBottomErrorMessage"))
		    $("lblBottomErrorMessage").hide();
		    	
	}
	else {
		$("lblTopErrorMessage").show();
		if ($("lblBottomErrorMessage"))
		    $("lblBottomErrorMessage").show();
		document.documentElement.scrollTop = 0;
	}
	return true;
}

function trackEvent17ForRegistration()
{
    try
    {
        var sProductId = $("C_ProductId").value;
        
		s = s_gi(s_account);
		if (sProductId == '607') //for A/B test
        {
            s.linkTrackVars = "eVar12,prop9,events";
            s.prop9 = "ProceedtoDL_A";
            s.linkTrackEvents = "event17,event43"; 
            s.events = "event17,event43";
        }
        else
        {            
		    s.linkTrackVars = "eVar12,events";	
            s.linkTrackEvents = "event17"; 
            s.events = "event17";	    
        }      
		s.eVar12 = sProductId;
		s.trackingServer = "metrics.solarwinds.com";
		s.tl(this, "o", "Submit");
	}
	catch (eException) 
	{
	}
}

function lstCountry_onChange(event) {
    var oElement = Event.element(event);
    $("txtPhone").disabled = oElement.selectedIndex == 0;
	countryChanged(oElement);
}

function countryChanged(countryControl)
{
    var sCountry = countryControl.value;   
	changeCountryValidation(sPreviousCountry, false);
	changeCountryValidation(sCountry, false);
	changeCountryValidation(sCountry, true);
	showCountryFields(sPreviousCountry, sCountry);
	sPreviousCountry = sCountry;
}

function lstCountry_onKeyUp(event) {
	lstCountry_onChange(event);
}

function txtPhone_onKeyDown(event) {
	if ($("lstCountry").value == "United States") {
		var oEvent;
		var iKeyCode;
		if (window.event) {
			oEvent = window.event;
			iKeyCode = window.event.keyCode;
		}
		else {
			oEvent = event;
			iKeyCode = event.which;
		}
		var bNumber = (iKeyCode > 47 && iKeyCode < 58) || (iKeyCode > 95 && iKeyCode < 106);
		var bArrow = (iKeyCode > 36 && iKeyCode < 41);
		var bDelete = (iKeyCode == 8 || iKeyCode == 46);
		var bTab = (iKeyCode == 9);
		if (bNumber || bArrow || bDelete || bTab) {
			var oElement = Event.element(oEvent);
			var sValue = oElement.value.replace(/-/g, "");
			if (sValue.length == 10) {
				if (bNumber) {
					return false;
				}
			}
		}
		else {
			return false;
		}
	}
}

function txtPhone_onKeyUp(event) {
	if ($("lstCountry").value == "United States" || $("lstCountry").value == "Canada") {
		var oElement = Event.element(event);
		var sValue = oElement.value.replace(/-/g, "");
		var tplPhoneNumber = new Template("#{0}#{1}#{2}-#{3}#{4}#{5}-#{6}#{7}#{8}#{9}");
		var oDigits = {0: "", 1: "", 2: "", 3: "", 4: "", 5: "", 6: "", 7: "", 8: "", 9: ""};
		for (var iCharacter = 0; iCharacter < 10; iCharacter++){
			if (iCharacter == sValue.length)
				break;
			else
				oDigits[iCharacter] = sValue.substr(iCharacter, 1);
		}
		var sNewValue = tplPhoneNumber.evaluate(oDigits).replace(/-+$/g, "");
		oElement.value = sNewValue;
	}
}

function window_onLoad(event) {
	initializeVariables();
	initializeView();
	attachEvents();
	showCountryFields("Please Select...", $("lstCountry").options[$("lstCountry").selectedIndex].value);
}


function attachEvents() {
	Event.observe($("lstCountry"), "keyup", lstCountry_onKeyUp);
	Event.observe($("lstCountry"), "change", lstCountry_onChange);

	$("txtPhone").onkeydown = txtPhone_onKeyDown;
	Event.observe($("txtPhone"), "keyup", txtPhone_onKeyUp);
	//Event.observe($("txtPhone"), "propertychange", txtPhone_onPropertyChange);
	
	Event.observe($("textContainer"), "mouseover", moreInfo_onMouseOver);
	Event.observe($("textContainer"), "mouseout", moreInfo_onMouseOut);
	
	if ($("OrionNPMScreenshot") != null) {
	    Event.observe($("OrionNPMScreenshot"), "mouseover", npmScreenshot_onMouseOver);
	    Event.observe($("OrionNPMScreenshot"), "mouseout", npmScreenshot_onMouseOut);
	}

	Event.observe($("spCBubble"), "mouseover", spCBubble_onMouseOver);
	Event.observe($("spCBubble"), "mouseout", spCBubble_onMouseOut);
}

function changeCountryValidation(sCountry, bStatus) {
	bShowValidator = true;
	switch (sCountry) {
		case "United States" :
			//ValidatorEnable(vldPhoneFormat, bStatus);
			ValidatorEnable(vldState, bStatus);
			ValidatorEnable(vldPostalCode, bStatus);
			break;
		case "Canada" :
			ValidatorEnable(vldProvince, bStatus);
			break;
		case "United Kingdom" :
			ValidatorEnable(vldCounty, bStatus);
			break;
		case "Australia" : 
		    ValidatorEnable(vldAusState, bStatus);
		break;
	}
	bShowValidator = false;
}

function initializeVariables() {
	
	try 
    {
        var pageTracker = _gat._getTracker("UA-2808998-1");
        pageTracker._trackPageview();
    } 
    catch(err) {}
    
    elqPPS = '70';
    if (this.GetElqCustomerGUID)
		document.forms["LicensedRegForm"].elements["elqCustomerGUID"].value = GetElqCustomerGUID();
	
	sPreviousCountry = $("lstCountry").value;
	
	bSameValue = true;
}

function initializeView() {
	changeCountryValidation(sPreviousCountry, true);
}

var lstCountry_states = {
    all: ["grpState", "grpPostalCode", "grpUKCounty", "grpAreaCode", "grpProvince", "grpAusState"],
    visible: {
        "Canada": ["grpProvince"],
        "United Kingdom": ["grpUKCounty"],
        "United States": ["grpState", "grpPostalCode"],
        "Australia": ["grpAusState"]        
    },
    def: ["grpAreaCode"]
};

function showCountryFields(sPreviousCountry, sCountry) {
    
    //Hide all fields
    for(var i = 0; i < lstCountry_states.all.length; i ++) {
        $(lstCountry_states.all[i]).addClassName("Hidden");
    }

    //Show only fiels for selected country
    if(lstCountry_states.visible.hasOwnProperty(sCountry)) {
        lstCountry_states.visible[sCountry].each(function(el){
            $(el).removeClassName("Hidden");
        });
        $("txtAreaProvinceCode").value = "";	
    } else {
        if(sPreviousCountry != "Canada" && sPreviousCountry != "United Kingdom") {
            if (IsCountryAPAC(sCountry) && sCountry.toLowerCase() != "hong kong" && sCountry.toLowerCase() != "macau" && sCountry.toLowerCase() != "singapore" && sCountry.toLowerCase().indexOf("please select") < 0) {
			    $("grpAreaCode").removeClassName("Hidden");
			} else {
			    $("grpAreaCode").addClassName("Hidden");
			    $("txtAreaProvinceCode").value = "";
			}
        }
    }
	
	$("txtPhone").disabled = $("lstCountry").selectedIndex == 0;
}

function validateListBox(sender, args) {
    if (bShowValidator)
        args.IsValid = true;
    else {
        var oListBox = $(sender.controltovalidate);
        args.IsValid = oListBox.selectedIndex > 0;
    }
}

function validateACFormat(sender, args) {
    var oTextBox = $(sender.controltovalidate);
    var sValue = oTextBox.value;
    if (bShowValidator)
        args.IsValid = sValue.match(/^[0-9]{0,4}$/g);
    else {
        args.IsValid = sValue.match(/^[0-9]{0,4}$/g);
    }
}

function validatePhoneFormat(sender, args) {
    var oTextBox;
    var sValue;
    var sCountry = $("lstCountry").value;
    if (bShowValidator || sCountry != "United States") {
        switch (sCountry) {
            case "Afghanistan":
            case "American Samoa":
            case "Antarctica":
            case "Australia":
            case "Bangladesh":
            case "Bhutan":
            case "Brunei Darussalam":
            case "Cambodia":
            case "China":
            case "Christmas Island":
            case "Cocos (Keeling) Islands":
            case "Cook Islands":
            case "Fiji":
            case "French Polynesia":
            case "Guam":
            case "Heard Island and McDonald Is.":
            case "Hong Kong":
            case "India":
            case "Indonesia":
            case "Japan":
            case "Kazakhstan":
            case "Kiribati":
            case "Korea Democratic People’s Republic":
            case "Korea Republic of":
            case "Kyrgyzstan":
            case "Lao People’s Democratic Republic":
            case "Macau":
            case "Malaysia":
            case "Maldives":
            case "Marshall Islands":
            case "Micronesia Federal State of":
            case "Mongolia":
            case "Myanmar":
            case "Nauru":
            case "Nepal":
            case "New Caledonia":
            case "New Zealand":
            case "Niue":
            case "Norfolk Island":
            case "Northern Mariana Islands":
            case "Pakistan":
            case "Palau":
            case "Papua New Guinea":
            case "Philippines":
            case "Pitcairn Island":
                //case "Samoa":
            case "Singapore":
            case "Solomon Islands":
            case "South Georgia":
            case "Sri Lanka":
                //case "Tahiti":
            case "Taiwan":
            case "Tajikistan":
            case "Thailand":
                //case "Timor-Leste":
            case "Tokelau":
            case "Tonga":
            case "Turkmenistan":
            case "Tuvalu":
            case "Uzbekistan":
            case "Vanuatu":
            case "Vietnam":
            case "Wallis and Futuna Islands":
                oTextBox = $(sender.controltovalidate);
                sValue = oTextBox.value;
                $("vldPhoneFormat").innerHTML = " – Must enter 6+ digits";
                args.IsValid = sValue.search(/[^0123456789\-\+]/) == -1 && sValue.replace(/\-/g, "").replace(/\+/g, "").length >= 6;
                break;
            case "Canada":
               	oTextBox = $(sender.controltovalidate);
               	sValue = oTextBox.value;
               	$("vldPhoneFormat").innerHTML = " – Canada requires 10 digits!";
               	args.IsValid = sValue.match(/\d{3}-\d{3}-\d{4}/g);
               	break;
            default:
                args.IsValid = true;
                break;
        }
    }
    else {
        oTextBox = $(sender.controltovalidate);
        sValue = oTextBox.value;
        $("vldPhoneFormat").innerHTML = " - U.S. requires 10 digits!";
        args.IsValid = sValue.match(/\d{3}-\d{3}-\d{4}/g);
    }
}

function validateTextBox(sender, args) {
	if (bShowValidator)
		args.IsValid = true;
	else {
	    var oTextBox = $(sender.controltovalidate);
	    
		args.IsValid = oTextBox.value.length > 0;

	}
}

function IsCountryAPAC(countryName)
{
    switch (countryName)
    {
        case "Afghanistan":
        case "American Samoa":
        case "Antarctica":
        case "Australia":
        case "Bangladesh":
        case "Bhutan":
        case "Brunei Darussalam":
        case "Cambodia":
        case "China":
        case "Christmas Island":
        case "Cocos (Keeling) Islands":
        case "Cook Islands":
        case "Fiji":
        case "French Polynesia":
        case "Guam":
        case "Heard Island and McDonald Is.":
        case "Hong Kong":
        case "India":
        case "Indonesia":
        case "Japan":
        case "Kazakhstan":
        case "Kiribati":
        case "Korea Democratic People’s Republic":
        case "Korea Republic of":
        case "Kyrgyzstan":
        case "Lao People’s Democratic Republic":
        case "Macau":
        case "Malaysia":
        case "Maldives":
        case "Marshall Islands":
        case "Micronesia Federal State of":
        case "Mongolia":
        case "Myanmar":
        case "Nauru":
        case "Nepal":
        case "New Caledonia":
        case "New Zealand":
        case "Niue":
        case "Norfolk Island":
        case "Northern Mariana Islands":
        case "Pakistan":
        case "Palau":
        case "Papua New Guinea":
        case "Philippines":
        case "Pitcairn Island":
        case "Singapore":
        case "Solomon Islands":
        case "South Georgia":
        case "Sri Lanka":
        case "Taiwan":
        case "Tajikistan":
        case "Thailand":
        case "Tokelau":
        case "Tonga":
        case "Turkmenistan":
        case "Tuvalu":
        case "Uzbekistan":
        case "Vanuatu":
        case "Vietnam":
        case "Wallis and Futuna Islands":
            return true;
        default:
            return false;
    }
}

function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}