//utilities

function setClass(classes, c, on, onlyclear) {
    var x = classes.split(' ');
    var i;
    if (on && onlyclear) return classes;
    for (i = 0; i < x.length; i++) {
        if (x[i] == c) {
            if (on) return classes;
            break;
        }
    }
    if (on) {
        x.push(c);
        return x.join(' ');
    }
    if (i > classes.length) return classes;
    return x.slice(0, i).concat(x.slice(i + 1, classes.length)).join(' ');
}
function setError(f, on, defaultError, onlyclear) {
    var control = document.getElementById(f);
    if (control != null) control.className = setClass(control.className, 'error', on, onlyclear);
    if (!(on && onlyclear)) {
        control = document.getElementById((defaultError ? '' : '_') + f + 'Error');
        if (control != null) control.style.display = on ? '' : 'none';
        control = document.getElementById((!defaultError ? '' : '_') + f + 'Error');
        if (control != null) control.style.display = 'none';
    }
}
function setIndicator(f, on) {
    var ind = document.getElementById(f + 'Indicator');
    if (ind != null)
        ind.className = setClass(ind.className, 'indicatorOn', on);
}
function setIndicatorError(f, on) {
    var ind = document.getElementById(f + 'Indicator');
    if (ind != null)
        ind.className = setClass(ind.className, 'error', on);
}

function genericTest(f, enabled, append, oncheck, onlyclear) {
    if (append == null) append = '';
    var elem = document.getElementById(f + append);
    if (elem == null) elem = document.getElementById(f);
    if (elem == null) return true;
    var valid = elem.value.length > 0;
    setError(f + append, enabled && !valid && !oncheck, true, onlyclear);
    return valid;
}
function genericRegexTest(f, enabled, regex, append, oncheck, onlyclear) {
    if (append == null) append = '';
    var val = document.getElementById(f + append).value;
    var empty = (val.length == 0);
    var re = new RegExp(regex);
    var valid = !empty && re.test(val);
    setError(f + append, enabled && !valid && !oncheck, empty, onlyclear);
    return valid;
}
function offsiteLinksTest(enabled, append, oncheck, onlyclear) {
    return true;
}
function timeZoneSettingsTest(enabled, append, oncheck, onlyclear) {
    var st = document.getElementById('timeZoneSettingsField').value.replace(' ', '');
    var valid = st.length > 0;
    setError('timeZoneSettingsField', !valid, true);
    return valid;
}
function javaScriptIncludePathFieldTest(enabled, append, oncheck, onlyclear) {
    var valid = true;  //(document.getElementById('javaScriptIncludePathField').value != 'error')
    setError('javaScriptIncludePathField', !valid, true);
    return valid;
}
function tagNameFieldTest(enabled, append, oncheck, onlyclear) {
    var valid = true;  //(document.getElementById('tagNameField').value != 'error')
    setError('tagNameField', !valid, true);
    return valid;
}

function downloadLinkTypesConfirm() {
    document.getElementById('_downloadLinkTypes').firstChild.data = document.getElementById('downloadLinkTypesField').value
    document.getElementById('_doNotIncludeRightClicks').firstChild.data = document.getElementById('doNotIncludeRightClicks').checked ? 'No' : 'Yes';
}
function dataCollctServerCustomConfirm() {
    document.getElementById('_dataCollct').firstChild.data =
        document.getElementById('dataCollctServerDefault').checked ? 'statse.webtrendslive.com' : 
        document.getElementById('dataCollctServerCustomField').value;
}
function dataCollctServerDefaultConfirm() {
    dataCollctServerCustomConfirm();
}
function trackOffsiteLinksConfirm() {
    var elem = document.getElementById('_trackOffsiteLinks').firstChild;
    elem.data = document.getElementById('offsiteLinks').value;
    if (document.getElementById('regex').checked) elem.data += ' (regex)';
}
function domainFilteringDivertConfirm() {
    document.getElementById('_domainFilteringDivert').firstChild.data =
                'Divert from the domain or subdomain \'' + document.getElementById('domainFilteringDomSub').value + '\' using the DCSID \'' +
                document.getElementById('domainFilteringDCSID').value + '\'';
}
function setQueryParamConfirm() {
    document.getElementById('_queryCookie').firstChild.data = document.getElementById('queryCookie').value;
    document.getElementById('_queryParameter').firstChild.data = document.getElementById('queryParameter').value;
}
function cookieConfirm() {
    document.getElementById('_cookieCrumb').firstChild.data = document.getElementById('cookieCrumb').value;
    document.getElementById('_crumbSeparator').firstChild.data = document.getElementById('crumbSeparator').value;
}
function warehouseQueryParamConfirm() {
    var checked0 = document.getElementById('alternateWTVisitorID').checked;
    var checked1 = document.getElementById('warehouseQueryParam').checked;
    var firstChild = document.getElementById('_WTVisitorID').firstChild;
    if (checked0) {
        var message = 'Use wt.vtid to set the WebTrends visitor ID for Warehouse with ';
        if (checked1)
            message += 'query parameter ' + document.getElementById('warehouseQueryParamField').value;
        else
            message += 'cookie ' + document.getElementById('warehouseCookieField').value;
        firstChild.data = message;
    }
}
function warehouseCookieConfirm() {
    warehouseQueryParamConfirm();
}
function alternateWTVisitorIDConfirm() {
    warehouseQueryParamConfirm();
}
function sessionOnlyCookieConfirm() { }

function toggleConfirmVisibility(f, visible) {
    var elem;
    elem = document.getElementById('_' + f);
    if (elem != null) elem.style.display = visible ? '' : 'none';
    elem = document.getElementById('__' + f);
    if (elem != null) elem.style.display = visible ? '' : 'none';
}
function toggleConfirmationSectionVisibility(name) {
    var elem = document.getElementById(name.substring(1));
    var style = 'none';
    for (var i in elem.childNodes) {
        e = elem.childNodes[i];
        if (e.nodeType == 1 && e.style.display == '') {
            style = '';
            break;
        }
    }
    document.getElementById(name).style.display = style;
}

var regexTests = {
    domainNameTrackField: "^\(\\w|-)+\\.(\\w|-|\\.)+$",
    dcsudIDField: "^(((dcs|DCS)[a-zA-Z0-9]{22}_[a-zA-Z0-9]{4})|DCS[A-Z0-9]{6}_[A-Z0-9]{4})$",
    nonWebTrendsCookieField: "^[^,;\\s]*$",
    warehouseQueryParam: "^[^\\&=\\s]*$",
    warehouseCookie: "^[^,;\\s]*$",
    domainFilteringDCSID: "^(((dcs|DCS)[a-zA-Z0-9]{22}_[a-zA-Z0-9]{4})|DCS[A-Z0-9]{6}_[A-Z0-9]{4})$",
    tagAdDirectorField: "^\\d+$",
    tagQuantcastField: "^p\\-[\\w\\-]{13}$"
};
function runTest(f, enabled, append, oncheck, onlyclear) {
    var regex = regexTests[f];
    if (regex) return genericRegexTest(f, enabled, regex, append, oncheck, onlyclear);
    var exists = eval('(typeof ' + f + 'Test == \'function\')');
    if (!exists) return genericTest(f, enabled, append, oncheck, onlyclear);
    return eval(f + 'Test(' + enabled + ', \'' + append + '\', ' + oncheck + ', ' + onlyclear + ')');
}

function updateKeyUp(f, append, indicator, event) {
    if ((event.keyCode || event.which) != 9)
        var valid = runTest(f, true, append, false, true);
}
function updateField(f, oncheck) {
    var checked = (oncheck ? document.getElementById(f).checked : true);
    var suffix = (oncheck ? 'Field' : '');
    var field = f + suffix;
    if (oncheck) document.getElementById(field).disabled = !checked;
    var enabled = !document.getElementById(field).disabled
    var valid = runTest(f, enabled, suffix, oncheck);
    setIndicator(field, enabled);
    setIndicatorError(field, enabled && !valid && !oncheck);
    var elem = document.getElementById('_' + field);
    if (elem != null) elem.firstChild.data = document.getElementById(field).value;
    toggleConfirmVisibility(field, enabled && valid);
    return valid || !enabled;
}
function updateCheck(f) {
    var checked = document.getElementById(f).checked;
    setIndicator(f, checked);
    toggleConfirmVisibility(f, checked);
    return true;
}
function updateRBFields(rb, include, exclude, oncheck, onlyclear) {
    var elem = document.getElementById(rb);
    var checked = elem.checked && !elem.disabled;
    var valid = true;
    for (var i in include) {
        document.getElementById(include[i]).disabled = !checked || elem.disabled;
        var validX = runTest(include[i], checked && !elem.disabled, '', oncheck, onlyclear);
        toggleConfirmVisibility(include[i], checked && validX && !elem.disabled);
        if (checked) valid = valid && validX;
    }
    for (var i in exclude) {
        document.getElementById(exclude[i]).disabled = checked || elem.disabled;
        var validX = runTest(exclude[i], !checked && !elem.disabled, '', oncheck, onlyclear);
        toggleConfirmVisibility(exclude[i], !checked && validX && !elem.disabled);
    }
    eval(rb + 'Confirm()');
    toggleConfirmVisibility(rb, checked && valid);
    setIndicator(rb, checked);
    setIndicatorError(rb, checked && !valid && !oncheck);
    return valid;
}
var timeZones = {
    "-11": "(GMT-11:00) Midway Island,Samoa",
    "-10": "(GMT-10:00) Hawaii",
    "-9": "(GMT-09:00) Alaska",
    "-8": "(GMT-08:00) Pacific Time (US & Canada); Tijuana",
    "-7": "(GMT-07:00) Mountain Time (US & Canada)",
    "-6": "(GMT-06:00) Central Time (US & Canada),Mexico City",
    "-5": "(GMT-05:00) Eastern Time (US & Canada)",
    "-4": "(GMT-04:00) Antigua,La Paz,Puerto Rico",
    "-3": "(GMT-03:00) Buenos Aires,Georgetown",
    "-2": "(GMT-02:00) Mid Atlantic",
    "-1": "(GMT-01:00) Azores,Cape Verde Islands",
    "0": "(GMT+00:00) Greenwich Mean Time: London,Dublin,Lisbon",
    "1": "(GMT+01:00) Central European Standard Time,West Central Africa",
    "2": "(GMT+02:00) Athens,Istanbul,Jerusalem,Helsinki",
    "3": "(GMT+03:00) Kuwait,Moscow,St.Petersburg,Nairobi",
    "3.5": "(GMT+03:30) Iran",
    "4": "(GMT+04:00) Abu Dhabi,Muscat,Baku",
    "4.5": "(GMT+04:30) Kabul",
    "5": "(GMT+05:00) Islamabad,Karachi,Tashkent",
    "5.5": "(GMT+05:30) Calcutta,Chennai,Mumbai,New Delhi",
    "5.75": "(GMT+05:45) Kathmandu",
    "6": "(GMT+06:00) Astana,Dhaka,Sri Jayawardenepura",
    "7": "(GMT+07:00) Bangkok,Hawaii,Jakarta,Krasnoyark",
    "8": "(GMT+08:00) Beijing,Kuala Lumpur,Perth,Singapore",
    "9": "(GMT+09:00) Tokyo,Seoul,Jayapura,Irkutsk",
    "9.5": "(GMT+09:30) Adelaide,Darwin",
    "10": "(GMT+10:00) Brisbane,Sydney,Hobart,Guam",
    "11": "(GMT+11:00) Magadan,Solomon Is.,New Caledonia",
    "12": "(GMT+12:00) Auckland,Fiji,Kamchatka,Marshall Is."
};
function updateTimeZone() {
    var valid = runTest('timeZoneSettings', true, 'Field', false);
    var value = document.getElementById('timeZoneSettingsField').value;
    document.getElementById('_timeZoneSettings').firstChild.data = timeZones[value];
    return valid;
}
function updateSessionOnlyCookie() {
    updateCheck('sessionOnlyCookie');
    var checked = document.getElementById('sessionOnlyCookie').checked;
    if (checked) {
        document.getElementById('alternateWTVisitorID').checked = false;
        updateWTVisitorID();
    }
    document.getElementById('alternateWTVisitorID').disabled = checked;
    return true;
}
function updateWarehouseWTVisitorID(oncheck, event) {
    if (!event || ((event.keyCode || event.which) != 9)) {
        var valid;
        if (document.getElementById('warehouseQueryParam').checked)
            valid = updateRBFields('warehouseQueryParam', ['warehouseQueryParamField'], ['warehouseCookieField'], oncheck, (event != null));
        else
            valid = updateRBFields('warehouseCookie', ['warehouseCookieField'], ['warehouseQueryParamField'], oncheck, (event != null));
        if (!event || valid) setIndicatorError('WTVisitorID', !oncheck && !valid);
        return valid;
    }
}
function updateWTVisitorID() {
    updateRBFields('alternateWTVisitorID', ['warehouseQueryParam', 'warehouseQueryParamField', 'warehouseCookie', 'warehouseCookieField'], [], true);
    var valid = updateWarehouseWTVisitorID(true);
    var checked = document.getElementById('alternateWTVisitorID').checked;
    setIndicator('WTVisitorID', checked);
    toggleConfirmVisibility('WTVisitorID', checked);
    return valid;
}
function updateAll() {
    var valid = true;
    if (!updateTimeZone()) valid = false;
    if (!updateRBFields('dataCollctServerCustom', ['dataCollctServerCustomField'])) valid = false;
    if (!updateRBFields('downloadLinkTypes', ['downloadLinkTypesField', 'doNotIncludeRightClicks'])) valid = false;
    if (!updateRBFields('trackOffsiteLinks', ['offsiteLinks', 'regex'])) valid = false;
    if (!updateSessionOnlyCookie()) valid = false;
    if (!updateWTVisitorID()) valid = false;
    if (!updateWarehouseWTVisitorID()) valid = false;
    if (!updateRBFields('domainFilteringDivert', ['domainFilteringDomSub', 'domainFilteringDCSID'])) valid = false;
    if (!updateRBFields('cookie', ['cookieCrumb', 'crumbSeparator'])) valid = false;
    if (!updateRBFields('setQueryParam', ['queryCookie', 'queryParameter', 'cookie'])) valid = false;
    $('.updateCheck').each(function() { if (!updateCheck(this.id)) valid = false; });
    $('.updateField').each(function() { if (!updateField(this.id)) valid = false; });
    $('.confirmationSection').each(function() { toggleConfirmationSectionVisibility(this.id); });

    var value = document.getElementById('dcsudIDField').value;
    var tagNameField = document.getElementById('tagNameField');
    if (value.length > 0 && tagNameField.value.length == 0) tagNameField.value = value;
    return valid;
}

//tab slider
	var easingType = '';
	var easingDuration = 200;
	var panelWidth = 960;

function panelSlider(obj)
{
    var slider_panelnumber = $(obj).attr("rel");
    var sliderContainer = $(obj).parents("div").siblings("#subsectionwrapper");
    var slider_panelwidth = $(sliderContainer).width();

    var slider_newwidth = slider_panelnumber * panelWidth;
    $(sliderContainer.children("#subsections")).animate({left: "-" + slider_newwidth}, {duration: easingDuration, easing: easingType});
	$(sliderContainer.children("#subsections")).animate({marginTop: 0}, {duration: easingDuration, easing: easingType});
}

function panelIndicator(panel) {
	var getRel = (($(panel).attr("rel") * 1) * 126) - 16;
	var width = $(panel).width()/2;
	$("#optionsNav ul").attr({tabindex: 0}).animate({backgroundPosition: getRel + width +'px 52px'}, {duration: easingDuration, easing: easingType});
}

function panelLinks(elem)
{
    $(elem).parents("#optionsNav").find(".pusher").removeClass("panelon");
    $(elem).addClass("panelon");
}

function showPanel(obj) {
	var section = $(obj).attr("rel");
	var secHeight = $("#sec"+section).height();	
    $("#subsectionwrapper").fadeTo(easingDuration, 1).animate({height: secHeight + 20}, {duration: easingDuration, easing: easingType});
   }

function hidePanel() {
    $("#subsectionwrapper").fadeTo(easingDuration, 0).animate({height: 0}, {duration: easingDuration, easing: easingType});
	$("#optionsNav a").removeClass("panelon");
   }

// blur form fuctions

function showPanelBlur() {
	var secHeight = $(".subsection").height();
    $("#subsectionwrapper").fadeTo(easingDuration, 1).animate({height: secHeight + 20}, {duration: easingDuration, easing: easingType});
   }

//confirmation

function showConfirmation() {
	$("#confirmation").show().fadeTo(300, 1);
	$("#timeZoneSettingsField").hide();
}

function showConfirmationHide() {
	$("#confirmation").fadeOut(300, 0).hide("slow");
	$("#timeZoneSettingsField").show();
}

//upload error

function errorUploadOn() {
	$(".errorUploadOn").show().fadeTo(300, 1);
}

function errorUploadOff() {
	$(".errorUpload").fadeOut(300, 0).hide("slow");
}

// reset form 

function resetForm() {
	$("form")[0].reset();
	$("#optionsNav .indicators span").removeClass("indicatorOn").removeClass("error");
}

function newWindow() {
	$('a[rel="external"]').attr({ target: "new" });
}

// help hover states
$.fn.helpHover = function() {
	var helpFields = $(".siteDomain fieldset input, .timeZone fieldset select, .dcsid fieldset input, .dataCollection fieldset input, .eventTracking fieldset input, .visitorTracking fieldset input, .domainFiltering fieldset input");
	
	var easingDuration = 300;
	 		$(this).hover(function () {
			$(this).addClass("helpwrapper")
			$(this).find(".help").show().stop().fadeTo(easingDuration, 1);
					}, function () {
			$(this).removeClass("helpwrapper");
			$(this).find(".help").show().stop().fadeTo(easingDuration, 0);
			return false
	});

	helpFields.focus(function(){
	        $(this).parents("fieldset").addClass("helpwrapper");
			$(this).parents("fieldset").show().find(".help").stop().show().fadeTo(easingDuration, 1);
			return false
	});
	helpFields.blur(function(){
	        $(this).parents("fieldset").removeClass("helpwrapper");
			$(this).parents("fieldset").show().find(".help").stop().show().fadeTo(easingDuration, 0);
			return false
	});
};

// add first-child support 
function firstChild() {
	$(".section:first-child").addClass("first-child");
}

//add last-child support
function lastChild() {
	$(".section:last-child, .subsection.eventTracking:last-child, .helpModule dl:last-child").addClass("last-child");
}
var currentLocation = null;
//onload
$(document).ready(function() {
    $("#sec0, #sec1, #sec2, #sec3, #sec4").prepend('<input type="text" class="hiddenField" rel="forTabSlider"/>');
    $("#sec0").append('<input type="text" class="hiddenField" rel="forTabSlider"/>');
    $(function() {
        var tabindex = 1;
        $('form').each(function() {
            $('input, select', this).not('input[type=hidden]').each(function() {
                var $input = $(this);
                var tabname = $input.attr("name");
                var tabnum = $input.attr("tabindex");
                if (tabnum > 0) {
                    index = tabnum;
                } else {
                    $input.attr("tabindex", tabindex);
                }
                tabindex++;
            });
        });
    });
    // tab through from	
    $(".section input").focus(function() {
        var newLocation = $(this).parents(".subsection").attr("id");
        if (newLocation != currentLocation) {
            var i = newLocation.substr(3, newLocation.length - 3);
            var findAnchor = $(this).parents("#content").find(".pusher")[i];
            panelSlider(findAnchor);
            showPanel(findAnchor);
            var findPanelLinks = $(this).parents("#content").find("#optionsNav").find(".pusher").removeClass("panelon").addClass("panelon")[i];
            panelLinks(findPanelLinks);
            var findPanelIndicator = $(this).parents("#content").find("#optionsNav").find(".pusher")[i];
            panelIndicator(findPanelIndicator);
            currentLocation = newLocation;
            return false;
        }
    });
    // open first panel	
    $('input[tabindex="7"]').focus(function() {
        showPanelBlur(this);
        return false;
    });
    newWindow(this);
    lastChild(this);
    firstChild(this);
    $(".help").hide();
    $('.section fieldset').helpHover();
    //actions 
    $(".pusher").click(function() {
        panelSlider(this);
        showPanel(this);
        panelLinks(this);
        return false;
    });
    $(".pusher").hover(function() {
        panelIndicator(this);
    });
    $("#action .button").click(function() {

        // CHECK THE UPDATE ALL
        if (!updateAll()) {
            $("#container #action #errorMessage p").show().fadeTo(500, 1.0); return;
        }
        else {
            $("#container #action #errorMessage p").hide().fadeTo(500, 1.0);
        }
        hidePanel(this);
        setTimeout('showConfirmation(this);', 500)
        return false;
    });
    $("#downloadButton").click(function() {
        var valid = true;
        if (!updateField('tagNameField')) valid = false;
        if (!updateField('javaScriptIncludePathField')) valid = false;
        if (!valid) return;
        $('#isDownload').val('true');
        document.BuildTag.submit();
        $("#confMessage").show().fadeTo(500, 1);
    });
    $("#uploadButton").click(function() {
        $('#isDownload').val('false');
        document.BuildTag.submit();
    });
    $(".closeError").click(function() {
        errorUploadOff(this);
        return false;
    });
    $("#confirmation .edit").click(function() {
        showConfirmationHide(this);
    });
    $("#intro p").click(function() {
        $(".section h2").animate({ paddingBottom: "30px" }, { duration: 300 });
        setTimeout('$("#uploadTag").show().fadeTo(500, 1); $("#intro p").fadeTo(500, 0).hide();', 300);
        return false
    });
    $(".cancelUpload").click(function() {
        $("#uploadTag").fadeTo(500, 0).hide();
        $("#intro p").show().fadeTo(500, 1);
        $(".errorUpload").fadeTo(500, 0).hide();
        $(".section h2").animate({ paddingBottom: "5px" }, { duration: 300 });
        return false
    });
    $("#uploadTag").parents("#container").find(".errorUpload").siblings("#uploadTag").show().css({ opacity: 1 });
    $(".section h2").parents("#container").find(".errorUpload").siblings(".section").children("h2").css({ paddingBottom: "30px" });
    $(".helpModule").parents("html").removeClass("tagBuilderHelp").addClass("tagBuilderHelpModule");
    $('.updateCheck').click(function() { updateCheck(this.id); });
    $('.updateFieldCheck').click(function() { updateField(this.id, true); });
    $('.updateField').blur(function() { updateField(this.id, false); });
    $('.updateField').keyup(function(e) {
        if ((e.keyCode || e.which || 0) != 9) {
            var valid = runTest(this.id, true, '', false, true);
            if (valid)
                setIndicatorError(this.id, false);
        }
    });
    $('#timeZoneSettingsField').click(function() { updateTimeZone(); });
    $('#timeZoneSettingsField').blur(function() { updateTimeZone(); });
    $('#sessionOnlyCookie').click(function() { updateSessionOnlyCookie(); });
    $('#alternateWTVisitor').click(function() { updateWTVisitorID(); });
    updateRBFields('dataCollctServerCustom', ['dataCollctServerCustomField']);
    updateRBFields('downloadLinkTypes', ['downloadLinkTypesField', 'doNotIncludeRightClicks']);
    updateRBFields('trackOffsiteLinks', ['offsiteLinks', 'regex']);
    updateSessionOnlyCookie();
    updateWTVisitorID();
    updateRBFields('cookie', ['cookieCrumb', 'crumbSeparator']);
    updateRBFields('setQueryParam', ['queryCookie', 'queryParameter', 'cookie']);
    updateRBFields('domainFilteringDivert', ['domainFilteringDomSub', 'domainFilteringDCSID']);
    $('.updateCheck').each(function() { updateCheck(this.id); });
    $('.updateFieldCheck').each(function() { updateField(this.id, true); });
    $('.confirmationSection').each(function() { toggleConfirmationSectionVisibility(this.id); });
});