var flashvars = false;
var params = {};
var attributes = {};
var currentTab = 1;
var page = "";
var dir = "";
tcHolderSettings = {
    antiAlias: true
}
var resultFromCookie = false;
var curvyCornersNoAutoScan = true;
var textSize = "normal";
var addthis_config = "";

function $import(src) {
    var scriptElem = document.createElement('script');
    scriptElem.setAttribute('src', src);
    scriptElem.setAttribute('type', 'text/javascript');
    document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

$("html").addClass("jqueryhide");

$(document).ready(function () {
    addthis_config = {
        services_exclude: 'print',
        services_compact: 'email, facebook, twitter, plusone, myspace, google, favorites, digg, delicious, stumbleupon, more',
        ui_offset_left: 35,
        ui_offset_top: 5,
        data_track_clickback: true,
        data_ga_tracker: pageTracker
    }
    addthis.init();	
	
	// check to see if we're in FF; G+ not supported in versions under 3.6
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		
		if (ffversion<3.6) {
			$('.google-plus').css("display","none");
			$('.fb-link').css("width","48px");
		}
	}
	
	productSelectorCalloutFunctions();
	$("html").removeClass("jqueryhide");
   
    $('#content a').filter(function () {
        var theHref = this;
        if (theHref.hostname && theHref.hostname !== location.hostname) {
            $(theHref).not(".noAutoIcon").addClass("offSite");
            $(theHref).not(".noAutoLink").attr('target', '_blank').bind('click keypress', function (event) {
                var code = event.charCode || event.keyCode;
                if (!code || (code && code == 13)) {
                    if (pageTracker) {
                        var fixedLink = this.href;
                        fixedLink = fixedLink.replace(/https?:\/\/(.*)/, "$1");
                        fixedLink = '/outgoing/' + fixedLink;
                        pageTracker._trackPageview(fixedLink);
                    };
                };
            });
        } else if ($(theHref).attr("target") == "_blank") {
            $(theHref).not(".noAutoLink").bind('click keypress', function (event) {
                var code = event.charCode || event.keyCode;
                if (!code || (code && code == 13)) {
                    if (pageTracker) {
                        var fixedLink = this.href;
                        fixedLink = fixedLink.replace(/https?:\/\/(.*)/, "$1");
                        fixedLink = '/downloads/' + fixedLink;
                        pageTracker._trackPageview(fixedLink);
                    };
                };
            });
        }
    });
    
    changeText(true);
    $("#textLink").click(function (e) {
        e.preventDefault();
        changeText(false);
    });
    $("#printLink").click(function (e) {
        e.preventDefault();
        window.print();
    });
    if ($.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
        $("img").each(function (i, e) {
            if (!$(e).attr("title")) $(e).attr("title", "");
        });
    }
    if ($.browser.msie) {
        $("#menu li").bind("mouseenter mouseleave", function (e) {
            $(this).toggleClass("over");
            if ($(this).hasClass("arrowed")) {
                $(this).toggleClass("arrowedOver");
            }
        });
        $("#contactBody fieldset, #reqinfoBody fieldset, #contactBody a.button, #reqinfoBody a.button, #locatorDiv").cornerz({
            radius: 10,
            corners: "tr, tl, br, bl"
        });
		 if ($.browser.version.substr(0, 1) != "6") {
			$("#icons").css("width","299px");
			$("#topLinks").css("width","399px");
			$(".fbFrame").css("width","91px");
		 }
		
        $('#tabs .tab').cornerz({
            radius: 10,
            corners: "tr tl"
        });
        $('#tcHolder').cornerz({
            radius: 10,
            corners: "tr br bl"
        });
        if ($.browser.version.substr(0, 1) == "6") {
            $("#sampleCall img").attr("src", "/images/shared/sample.gif");
            $("#greenCall img").attr("src", "/images/shared/green.gif");
        }
		
		//if($.browser.version.substr(0,1) == "6" || $.browser.version.substr(0,1) == "7" || $.browser.version.substr(0,1) == "8"){
			if($.browser.version.substr(0,1) == "6"){
			$("#carousel_btn_container img").attr("src","/images/shared/carousel_nav_btn.gif");
			$("#carousel_artofliving img").attr("src","/images/shared/carousel_art_of_living.gif");
			$("#carousel_underwear img").attr("src","/images/shared/carousel_underwear.gif");
			$("#carousel_walgreens img").attr("src","/images/shared/carousel_walgreens.gif");
			//$("#carousel_cvs img").attr("src","/images/shared/carousel_cvs.gif");
			
			$(".shopIcon img").attr("src","/images/shared/shop_icon.gif");
		}
		
		// G+ is not supported in IE7 and under, so hide it
		if ($.browser.version.substr(0,1) == "6" || $.browser.version.substr(0,1) == "7") {			
			$('.google-plus').css("display","none");			
		}		
    }
    $("ul.sub li:has(ul)").addClass("arrowed");
    page = parseUri(window.location).file;
    dir = parseUri(window.location).directory;
    $("#menu a.topMenu").each(function (i) {
        if (dir == parseUri($(this).attr('href')).directory) {
            $(this).parent().addClass("on");
        }
    });
    $('dt').each(function (index, elem) {
        $(this).attr("id", "dt-" + index);
        $(elem).click(function () {
            $(this).toggleClass("on");
            id = $(this).attr("id");
            id = "#dd-" + id.substr(3);
            $(id).toggle();
        });
    });
    $('dd').each(function (index) {
        $(this).attr("id", "dd-" + index);
    });
    switch ($("body").attr("id")) {
    case "contactBody":
        contactFunctions();
        break;
    case "locatorBody":
        locatorFunctions();
        break;
    case "assessmentBody":
        assessmentFunctions();
        $("#prodSelDiv").hide();
        break;
    case "requestBody":
        requestFunctions();
        $("#sampleCall").hide();
        break;
    case "reqinfoBody":
        requestInfoFunctions();
        break;
    case "protectionBody":
        protectionFunctions();
        break;
    case "prodSubBody":
        prodSubFunctions();
        break;
    case "prodHomeBody":
        prodHomeFunctions();
        break;
    }
    if ($("#countryDefault").length != 0) {
        initCountry();
    }
    $("table tbody").each(function (index, elem) {
        $(elem).children("tr:odd").addClass("alt");
    });
    page = page.slice(0, page.lastIndexOf("."));
    $("#tabs .tab").attr("id", function (index) {
        return "tab-" + (index + 1);
    }).click(function () {
        onTab = "#tab-" + currentTab;
        onTC = "#tc-" + currentTab;
        $(onTab).removeClass("focused");
        $(this).addClass("focused");
        $(onTC).hide();
        tcid = $(this).attr("id");
        currentTab = tcid.substr((tcid.lastIndexOf("-") + 1));
        tcid = "#tc-" + currentTab;
        $(tcid).show();
        $.cookie(page, currentTab, {
            path: '/'
        });
    });
    $(".tc").attr("id", function (index) {
        return "tc-" + (index + 1);
    });
    if ($.cookie(page) && $.cookie(page) != "") {
        onTab = "#tab-" + currentTab;
        $(onTab).removeClass("focused");
        currentTab = $.cookie(page);
        onTab = "#tab-" + currentTab;
        $(onTab).addClass("focused");
    }
    onTC = "#tc-" + currentTab;
    $(onTC).show();
});

function productSelectorCalloutFunctions(){
	 if($('#prodSel').length > 0) $('#prodSel select').sSelect();
	 $("#calloutWomanSizeDiv, #calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv").hide();
	
	 $("#user").bind("change",function(){
		 myVal = $("#user option:selected").val();
		if (myVal == ""){
			$("#calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv, #calloutWomanSizeDiv").hide();
			$("#calloutManSizeDiv").show();
		} else if(myVal == "Loved one (Youth)"){
			$("#calloutManSizeDiv, #calloutWomanSizeDiv, #calloutYouteWomanSizeDiv, #calloutYouteManSizeDiv").hide();
			if($("#gender option:selected").length > 0 && $("#gender option:selected").val() == "Female"){
				$("#calloutYouteWomanSizeDiv").show();
			}
			else $("#calloutYouteManSizeDiv").show();
		} else{
			$("#calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv, #calloutManSizeDiv, #calloutWomanSizeDiv").hide();
			if($("#gender option:selected").val() == "Female"){
				$("#calloutWomanSizeDiv").show();
			}else{
				$("#calloutManSizeDiv").show();
			}
		}
	 });
	 
	 $("#gender").bind("change",function(){
		 myVal = $("#gender option:selected").val();
		 myType = $("#user option:selected").val();
		 
		 if(myType == "Loved one (Youth)"){
			 if(myVal == ""){
				 $("#calloutWomanSizeDiv,#calloutManSizeDiv, #calloutYouteWomanSizeDiv").hide();
				  $("#calloutYouteManSizeDiv").show();
			 } else if (myVal == "Male"){
				 $("#calloutYouteManSizeDiv").show();
				 $("#calloutWomanSizeDiv,#calloutManSizeDiv, #calloutYouteWomanSizeDiv").hide(); 
			 }else if (myVal == "Female"){
				 $("#calloutManSizeDiv,#calloutYouteManSizeDiv, #calloutWomanSizeDiv").hide();
				 $("#calloutYouteWomanSizeDiv").show();	 
			 }
		 } else  {
			 if(myVal == ""){
				 $("#calloutWomanSizeDiv,#calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv").hide();
				  $("#calloutManSizeDiv").show();
			 } else if (myVal == "Male"){
				 $("#calloutManSizeDiv").show();
				 $("#calloutWomanSizeDiv,#calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv").hide(); 
			 }else if (myVal == "Female"){
				 $("#calloutManSizeDiv,#calloutYouteManSizeDiv, #calloutYouteWomanSizeDiv").hide();
				 $("#calloutWomanSizeDiv").show();	 
			 }
	 	}
	 });
	 
	 $("#conBtn").click(function (e) {
        e.preventDefault();
       
        $("#prodSel").submit();
    });
}

function prodImgToggle(s, o, c, e) {
    if (c != "") {
        e = $(c + " img");
    }
    imgsrc = e.attr("src");
    imgsrc = (imgsrc.substring(0, imgsrc.lastIndexOf(s))) + o + ".jpg";
    e.attr("src", imgsrc);
}

function prodHomeFunctions() {
    $(".prodIcon img").mouseenter(function () {
        prodImgToggle(".", "_on", "", $(this));
    }).mouseleave(function () {
        prodImgToggle("_", "", "", $(this));
    });
}

function prodSubFunctions() {
    if ($(".mView").length > 0) {
        prodImgToggle(".", "_on", ".mView.on");
    }
    if ($(".mView4th").length > 0) {
        prodImgToggle(".", "_on", ".mView4th.on");
    }
    $(".mView, .mView4th").click(function () {
        if (!$(this).hasClass("on")) {
            var myClass = ($(this).hasClass("mView4th")) ? ".mView4th" : ".mView";
            var mOn = myClass + ".on";
            prodImgToggle("_", "", mOn);
            $(mOn).removeClass("on");
            $(this).addClass("on");
            rel = $(this).attr("rel");
            $(".imgHolder").hide();
            $(".imgHolder[rel=" + rel + "]").show();
            prodImgToggle(".", "_on", mOn);
        }
    });
    $("area").click(function (e) {
        e.preventDefault();
    }).qtip({
        prerender: true,
        show: 'mouseover',
        hide: 'mouseout',
        content: false,
        text: false,
        title: {
            text: false
        },
        position: {
            adjust: {
                y: 5
            },
            corner: {
                target: 'bottomMiddle',
                tooltip: 'topMiddle'
            }
        },
        style: {
            width: {
                min: 150,
                max: 250
            },
            "font-size": "14px",
            "line-height": "18px",
            padding: 5,
            background: '#e6a158',
            color: 'white',
            textAlign: 'center',
            border: {
                width: 1,
                radius: 4,
                color: '#e6674a'
            },
            tip: 'topMiddle'
        }
    });
}

function protectionFunctions() {
    $("#prodGuide").hrzAccordion({
        containerClass: "ACCcontainer",
        contentContainerClass: "ACCcontentContainer",
        handlePosition: "left",
        childSelector: ".ACCDiv",
        openOnLoad: false,
        fixedWidth: 765,
        closeSpeed: 100,
        openSpeed: 100
    });
    $("#stageMap area, #stageP a").click(function (e) {
        e.preventDefault();
        num = $(this).attr("rel");
        $("#prodGuideHandle" + num).trigger("click");
    });
    $(".iconBox").click(function () {
        rel = $(this).attr("rel");
        num = rel.substr(1);
        arrow = "a" + num;
        if (!$(this).parent().parent().siblings(".arrow").is("." + arrow)) {
            $(this).parent().parent().siblings(".arrow").removeClass("a1 a2 a3 a4 a5").addClass(arrow);
            $(this).parent().children(".iconBox").removeClass("on");
            $(this).addClass("on");
            $(this).parent().parent().siblings(".prodBot").removeClass("pON");
            $(this).parent().parent().siblings(".prodBot[rel=" + rel + "]").addClass("pON");
        }
    });
}

function locatorFunctions() {
    initialize();
    $("#locatorForm").bind("submit", function () {
        showLocations(this.location.value, 1);
        return false;
    });
    $(".locatorButton").click(function (e) {
        e.preventDefault();
        showLocations($('#location').val(), $('#pagenumber').val());
    });
    $("a.prev").click(function (e) {
        e.preventDefault();
        showPrevNextLocations(parseInt($('#pagenumber').val()) - 1);
    });
    $("a.next").click(function (e) {
        e.preventDefault();
        showPrevNextLocations(parseInt($('#pagenumber').val()) + 1);
    });
}



function changeText(fromLoad, Myclass) {
    if (fromLoad) {
        if ($.cookie("text") && $.cookie("text") != "") {
            textSize = $.cookie("text");
            if (textSize != "normal") {
                Myclass = $.cookie("text") + "Text";
                $("body").addClass(Myclass);
            }
        }
    } else {
        temp = (textSize == "normal") ? "large" : (textSize == "large") ? "super" : "normal";
        $("body").removeClass("largeText superText");
        if (temp != "normal") {
            Myclass = temp + "Text";
            $("body").addClass(Myclass);
        }
        textSize = temp;
        $.cookie("text", textSize, {
            expires: 7,
            path: '/'
        });
    }
}
$.fn.clearForm = function () {
    return this.each(function () {
        var type = this.type,
            tag = this.tagName.toLowerCase();
        if (tag == 'form') return $(':input', this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea') this.value = '';
        else if (type == 'checkbox' || type == 'radio') this.checked = false;
        else if (tag == 'select') this.selectedIndex = -1;
    });
};

function requestFunctions() {
    $("#submitMe").click(function (e) {
        e.preventDefault();
        $("#requestSample").submit();
    });
	$("#cancelMe").click(function(e){
		e.preventDefault();
		
		window.parent.closeForm();
	});
    $("a.reset").click(function (e) {
        e.preventDefault();
        $("#requestSample input[type='text']").val('');
		$("#requestSample select option:selected").attr("selected","");
		$("#requestSample input[type='radio']:checked").attr("checked","");
    });
       
}

function requestInfoFunctions() {
    $("#submit").click(function (e) {
        e.preventDefault();
        $("#signUp").submit();
    });
    $("#reset").click(function (e) {
        e.preventDefault();
        $("#signUp").reset();
    })
}

function contactFunctions() {
    $(".formToggle").click(function (e) {
        e.preventDefault();
        $("#contactForm").toggle();
    });
    if (formSubmit == "submit" && $("#contactForm").length > 0) {
        $("#contactForm").show();
        if ($("#prob:checked").val() != null) {
            $("#showFields").show();
        }
        if ($("#noContact:checked").val() != null) {
            $("#contactBoxes").hide();
        }
        if ($("#manage option:selected").val() == "Different incontinence product") {
            $("#manageOtherD").show();
        };
    }
    $("#prob").click(function () {
        if ($("#prob:checked").val() != null) {
            $("#showFields").show();
        } else $("#showFields").hide();
    });
    $("#noContact").click(function () {
        if ($("#noContact:checked").val() != null) {
            $("#contactBoxes").hide();
            $("#contactBoxes input").removeAttr("checked");
        } else {
            $("#contactBoxes").show()
        };
    });
    $("#manage").bind("change", function () {
        if ($("#manage option:selected").val() == "Different incontinence product") {
            $("#manageOtherD").show();
        } else {
            $("#manageOtherD").hide();
        }
    });
    $("#submit").click(function (e) {
        e.preventDefault();
        $("#contactForm").submit();
    });
    $("#reset").click(function (e) {
        e.preventDefault();
        $("#contactForm").reset();
    })
}

function buildBirthYear() {
    var date = new Date();
    for (i = date.getFullYear(); i >= 1900; i--) {
        myOpt = "<option value=\"" + i + "\">" + i + "</option>";
        $("#birthyear").append($(myOpt));
    }
}

function fixPng() {
    DD_belatedPNG.fix(".mini img");
    DD_belatedPNG.fix(".product");
}

function clearCookies() {
    $.cookie('resID', null, {
        path: '/'
    });
    $.cookie('extras', null, {
        path: '/'
    });
    $.cookie('user', null, {
        path: '/'
    });
    resultFromCookie = false;
}


function parseUri(str) {
    var o = parseUri.options,
        m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i = 14;
    while (i--) uri[o.key[i]] = m[i] || "";
    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });
    return uri;
};
parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
