﻿/*
Global single file JS:

contains: 
PUI
PSideNav
PSlider
PValidation
PAccount
PToolkit
PSearch

*/

PUI = {

    searchPosts: function (txtClientId, ddlClientId) {
        document.location.href = "/" + PUI.culture + "/Resources/Posts/Search/" + $("#" + ddlClientId).val() + "/1?q=" + $("#" + txtClientId).val();
    },

    lastHoverNode: null,
    navHoverQueue: [null, null, null],

    "initRQL": function () {
        $("body.anon").find("a.rql").click(function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            PUI.showRQL($(this).attr("href"));
        });
    },

    "showRQL": function (href) {
        $.blockUI({
            css: {
                width: '300px',
                height: '385px',
                allowBodyStretch: true,
                border: 'none',
                backgroundColor: 'transparent'
            },
            centerFull: true,
            message: $("#" + PUI.rqlDivId)
        });
        PUI.hdnMasterRefUrl.value = href;
    },

    "initHeader": function () {
        var tobeMinied = [];
        $("#mainNav .node").each(function (eli, el) {
            $(el).find(".subnavNode").each(function (elii, ell) {
                if ($(ell).hasClass("miniTrue")) tobeMinied.push(ell);
            });
        });
        if (tobeMinied.length % 2 != 0) alert("Incorrect number of mini nodes in sitemap detected");
        else {
            for (var xx = 0; xx < tobeMinied.length; xx += 2) {
                var xx1 = $(tobeMinied[xx]);
                var xx2 = $(tobeMinied[xx + 1]);
                xx1.next("div.sep").remove();
                var html1 = xx1.html();
                PToolkit.clearChildNodes(tobeMinied[xx]);
                xx1.append('<div class="mini1">' + html1 + '</div>');
                xx1.append('<div class="mini2">' + xx2.html() + '</div>');
                xx2.remove();
            }
        }
        $("#mainNav a.off").each(function (eli, el) {
            el.onmouseover = function () {
                var node = $(el).parent().parent().find("div.activeDiv").parent();
                var idd = node.attr("id");
                var pos = parseInt(idd.split(/_/ig)[1], 10);
                var activeDiv = $(el).parent().parent().find("div.activeDiv").first();
                if (pos == 0) {
                    $("#endLeft").show();
                    $("#notEndLeft").hide();
                    $("#endRight").hide();
                    $("#notEndRight").show();
                    PUI.addorremoveEnd(true, activeDiv.find("td.cl img").first());
                    PUI.addorremoveEnd(false, activeDiv.find("td.cr img").first());
                } else if (pos < PUI.mainNavMainNodeCount - 1) {
                    $("#endLeft").hide();
                    $("#notEndLeft").show();
                    $("#endRight").hide();
                    $("#notEndRight").show();
                    PUI.addorremoveEnd(false, activeDiv.find("td.cl img").first());
                    PUI.addorremoveEnd(false, activeDiv.find("td.cr img").first());
                } else {
                    $("#endLeft").hide();
                    $("#notEndLeft").show();
                    $("#endRight").show();
                    $("#notEndRight").hide();
                    PUI.addorremoveEnd(false, activeDiv.find("td.cl img").first());
                    PUI.addorremoveEnd(true, activeDiv.find("td.cr img").first());
                }
                PUI.navHoverQueue = [false, false, false];
                if (PUI.lastHoverNode != null && PUI.lastHoverNode != idd) {
                    PUI.revertMainNavActiveStage(PUI.lastHoverNode);
                }
                activeDiv.removeClass("hide");
                activeDiv.find("td.activeMode").removeClass("activeMode").addClass("overlayMode");
                $(node).find("table.active img").each(function (eli, el) {
                    if ((pos == 0 && eli != 0) || (pos != 0 && pos < PUI.mainNavMainNodeCount - 1) || (pos == PUI.mainNavMainNodeCount - 1 && eli == 0))
                        PUI.toggleMainNavActiveStageImage(el, true);
                });
                $(el).parent().parent().find("div.inactiveDiv").addClass("hide");
                $("#midSubnavContent").empty();
                $("#midSubnavContent").html($(el).parent().parent().find("div.subnavcontent").first().html());
                $("#navOverLay table").removeClass("hide");
                activeDiv.hover(function () { }, function () { PUI.navHoverQueue[0] = true; PUI.checkNavOff(); setTimeout("PUI.checkNavOffDelayed();", 100); });
                $("#navOverLay").hover(function () { PUI.navHoverQueue[2] = true; }, function () { $(document).mousemove(function (e) { }); PUI.navHoverQueue[1] = true; PUI.checkNavOff(); });
                PUI.lastHoverNode = node;
                node.addClass("currentTabNode");
                var bubble = document.getElementById("bubble");
                bubble.style.left = "0px";
                var elSize = PToolkit.getSize(document.getElementById(node.attr("id")));
                var overlaySize = PToolkit.getSize(bubble);
                var elPos = node.position();
                var factor = ((elSize.width + overlaySize.width) / 2);
                var threshold = 280;
                var overlayPos = (
                                pos == 0 ? elPos.left :
                                    (pos < PUI.mainNavMainNodeCount - 1 ?
                                        elPos.left + (elPos.left < threshold ? 0 : -1 * factor) + (elPos.left * (elPos.left > threshold ? factor : -1 * factor) / 974) :
                                        elPos.left - overlaySize.width + elSize.width
                                    )
                                );
                bubble.style.left = parseInt(overlayPos, 10) + "px";
            }
        });
    },
    "initSideNav": function () {
        $(window).scroll(PUI.positionSideNav);
        PUI.positionSideNav();
    },
    "positionSideNav": function () {
        var st = parseInt($(window).scrollTop(), 10);
        if (st < 15) { st = 15; }
        $('#myNav').animate({ 'top': st + "px" }, { "duration": 300, "queue": false });
    },
    "defaultHeader": function () {
        if ($("#options .loggedout").length > 0) {
            $("#options .forgotpass").hide();
            $("#options .loggedout").show();
        }
    },

    "toggleHeader": function (b) {
        if (b && $("#optionsControl").hasClass("open")) return;
        $("#optionsControl").toggleClass("open");
        if ($("#optionsControl").hasClass("open")) {
            $("#optionsControl img").css("margin-top", "-63px");
            $("#options").slideDown(400);
        } else {
            $("#options").slideUp(400, PUI.defaultHeader);
            $("#optionsControl img").css("margin-top", "0");
        }
        return false;
    },


    "bopened": false,
    "initBrands": function () {

        // Hide inside contents
        $("#brands .inner").hide();

        // Turn on default first option
        $("#brands .petbrands:eq(0)").addClass("on");
        $("#brands .petbrands:gt(0)").hide();

        // Click toggle
        $("#brands .expand").click(PUI.toggleBrands);

        $(".bpet a").click(function () {
            if (!$(this).hasClass("on")) {

                var olc = $(".bpet a.on").removeClass("on").attr("class");
                var nwc = $(this).attr("class").replace(/\s*left\s*/ig, '');
                $(this).addClass("on");

                $("#brands .petbrands.on").hide(500).removeClass("on");
                $("#brands .petbrands." + nwc).show(500).addClass("on");

            }
            return false;
        });
    },
    "checkNavOffDelayed": function () {
        if (PUI.navHoverQueue[0] && !PUI.navHoverQueue[1] && !PUI.navHoverQueue[2]) {
            PUI.navHoverQueue = [false, false, false];
            PUI.checkNavOff(true);
        }
    },
    "checkNavOff": function (override) {
        if (override || (PUI.navHoverQueue[0] && PUI.navHoverQueue[1])) {
            var activeDiv = PUI.lastHoverNode.find("div.activeDiv").first()
            activeDiv.hover(function () { }, function () { });
            activeDiv.find("td.cm").removeClass("overlayMode").addClass("activeMode");
            $("#navOverLay").hover(function () { }, function () { });
            PUI.revertMainNavActiveStage(PUI.lastHoverNode);
            $("#navOverLay table").addClass("hide");
        }
    },
    "addorremoveEnd": function (b, el) {
        if (b && $(el).attr("src").indexOf("-end.gif") == -1) {
            el.attr("src", el.attr("src").replace(/\.gif$/ig, '-end.gif'));
        } else if (!b) {
            el.attr("src", el.attr("src").replace(/\-end.gif$/ig, '.gif'));
        }
    },
    "revertMainNavActiveStage": function (node) {
        var activeDiv = node.find("div.activeDiv").first();
        if (activeDiv.hasClass("realActiveTab")) {
            activeDiv.find("img").each(function (eli, el) {
                PUI.toggleMainNavActiveStageImage(el, false);
            });
            activeDiv.find("td.cm").removeClass("overlayMode").addClass("activeMode");
            PUI.addorremoveEnd(false, activeDiv.find("td.cl img").first());
            PUI.addorremoveEnd(false, activeDiv.find("td.cr img").first());
        } else {
            activeDiv.addClass("hide");
            node.find("div.inactiveDiv").removeClass("hide");
        }
        node.removeClass("currentTabNode");
    },
    "toggleMainNavActiveStageImage": function (el, b) {
        if (b) {
            $(el).attr("src", $(el).attr("src").replace(/active/ig, 'overlay'));
        } else {
            $(el).attr("src", $(el).attr("src").replace(/overlay/ig, 'active'));
        }
    },
    "toggleBrands": function () {

        // Brand images are hidden completely until the brand window is opened for the first time
        if (!PUI.bopened) {
            $(".petbrands img").attr("src", function () { return $(this).attr("rel"); });
            PUI.bopened = true;
        }
        $(this).toggleClass("open"); 						// Toggle on/off state


        if ($(this).hasClass("open")) {							// if now open
            $("#brands .inner").slideDown(250);
            $("#brands").animate({ marginTop: "-148px" }, 300);
            $("#brands .option img").css("margin-top", "-38px");
        } else {												// if now closed
            $("#brands .inner").slideUp(200);
            $("#brands").animate({ marginTop: "-38px" }, 200);
            $("#brands .option img").css("margin-top", "0");
        }

        return false; 										// return false to cancel anchor click through
    }

};


PUI.hdnMasterRefUrl = null;


PUI.showModalGallery = function (dvid) {
    $.blockUI({
        css: {
            width: '935px',
            height: '925px',
            allowBodyStretch: true,
            border: 'none',
            backgroundColor: 'transparent'
        },
        centerFull: true,
        message: $("#" + dvid)
    });
}


PUI.share = {};

PUI.share.shareFB = function () {
    PUI.share.gotoShareUrl('Share - FBFAN', 'http://www.facebook.com/sharer.php?u=%%uri%%&t=%%title%%');
}

PUI.share.shareTwitter = function (msg) {
    if (msg != "") {
        PUI.share.gotoShareUrl('Share - Twitter', 'http://twitter.com/home?status='+escape(msg)+' %%uri%%');
    } else {
        PUI.share.gotoShareUrl('Share - Twitter', 'http://twitter.com/home?status=%%title%% %%uri%%');
    }
}

PUI.share.gotoShareUrl = function (click_tag, share_uri) {
    PUI.trackGoogle(click_tag);
    window.open(share_uri.replace(/%%title%%/ig, escape(PUI.share.pageTitle)).replace(/%%uri%%/ig, PUI.share.shareUri));
}

PUI.share.setShareUrl = function (url) {
    $("#" + PUI.share.hdnUrlField).val(url);
    PUI.share.shareUri = url;
}

PUI.share.showShare = function (dvid) {
    $.blockUI({
        css: {
            width: '640px',
            height: '927px',
            allowBodyStretch: true,
            border: 'none',
            backgroundColor: 'transparent'
        },
        centerFull: true,
        message: $("#" + dvid)
    });
    $("#" + dvid + " input[type=text]").attr("value", "");
    $("#" + dvid + " textarea").val("");
    $("#" + dvid + " .error").addClass("hide");
}

PUI.getCreateAnimalUrl = function (type) {
    if (PUI.isLoggedIn()) {
        return "/" + PUI.culture + "/MyPawsway/MyPetProfile/Create/BasicInfo/" + type;
    }
    return "/" + PUI.culture + "/PetPals/CreatePetProfile/";
}

PUI.isLoggedIn = function () {
    return $('#SideNavPetScrollBar').size() > 0;
}

PUI.trackGoogle = function (tag) {
    if (PUI.pageTracker) PUI.pageTracker._trackPageview(tag + PUI.oId == "" ? "" : " [oid: " + PUI.oId + "]");
}

PUI.changeCulture = function () {
    var locs = { "en": "fr", "fr": "en" };
    var queryString = "";
    if (document.location.href.match(/\?/ig) != null) {
        var splits = document.location.href.split('?');
        for (i = 1; i < splits.length; i++) queryString += '?' + splits[i];
    }
    var re = new RegExp("(/" + PUI.culture + "/)|(/" + PUI.culture + "#?$)", "ig");
    var oldUrl = document.location.href;
    var newUrl = (oldUrl.replace(/\?.*$/ig, '').replace(re, "/" + locs[PUI.culture] + "/") + (queryString == "" ? "" : queryString));
    if (newUrl == oldUrl) newUrl = "/" + locs[PUI.culture];
    document.location.href = newUrl;
}





/////////////////////////
//
// PSideNav
//
/////////////////////////

/*
PNavigation
- handles side navigation based scripts
*/

PSideNav = {}

PSideNav.petCount = 0;
PSideNav.petsPerRange = 2;
PSideNav.currentIndex = 0;
PSideNav.upEnabled = true;
PSideNav.downEnabled = true;

PSideNav.initialize = function () {

    PSideNav.petCount = $('.profileItem').size();
    if (PSideNav.petCount == 0) {
        $('#SideNavPetScrollBar').hide();
    } else if (PSideNav.petCount > 1) {
        $('#SideNavPetScrollBar').show();
        PSideNav.checkValues();
    } else {
        $("#myNav .myNavOpen .profilePets").css("height", "83px");
    }
    if (PSideNav.petCount < 3) {
        $('#SideNavAddPet').show();
        $("a.sidenav_scrolla").hide();
    } else {
        $('#SideNavAddPet').hide();
        $('#SideNavAddPetInside').show();
    }
}

PSideNav.checkValues = function () {
    var curIn = $("input[id$='hdnCurrentIndex']").val()
    if (curIn.length > 0) {
        PSideNav.currentIndex = curIn;
    }
    if (PSideNav.currentIndex == 0) {
        PSideNav.disableUpArrow();
    }
    else {
        PSideNav.enableUpArrow();
    }
    if ((PSideNav.currentIndex + 1) * PSideNav.petsPerRange >= PSideNav.petCount) {
        PSideNav.disableDownArrow();
    }
    else {
        PSideNav.enableDownArrow();
    }
}

PSideNav.scrollDown = function () {
    if (PSideNav.downEnabled) {
        PSideNav.currentIndex = PSideNav.currentIndex + 1;
        PSideNav.checkValues();
        PSideNav.DoAnimation();
    }
}

PSideNav.scrollUp = function () {
    if (PSideNav.upEnabled) {
        PSideNav.currentIndex = PSideNav.currentIndex - 1;
        PSideNav.checkValues();
        PSideNav.DoAnimation();
    }
}

PSideNav.DoAnimation = function () {
    var toScroll = ((PSideNav.currentIndex * -160));
    $("#SideNavProfilePets").animate({
        top: toScroll + "px"
    }, {
        duration: 300,
        specialEasing: {
            width: 'linear',
            height: 'easeOutBounce'
        }
    });
}

PSideNav.enableUpArrow = function () {
    var src = $('#SideNavPetScrollUp').attr('src');
    src = src.replace('mynav_up', 'mynav_on_up');
    $('#SideNavPetScrollUp').attr('src', src);
    PSideNav.upEnabled = true;
}

PSideNav.enableDownArrow = function () {
    var src = $('#SideNavPetScrollDown').attr('src');
    src = src.replace('mynav_down', 'mynav_on_down');
    $('#SideNavPetScrollDown').attr('src', src);
    PSideNav.downEnabled = true;
}

PSideNav.disableUpArrow = function () {
    var src = $('#SideNavPetScrollUp').attr('src');
    src = src.replace('mynav_on_up', 'mynav_up');
    $('#SideNavPetScrollUp').attr('src', src);
    PSideNav.upEnabled = false;
}

PSideNav.disableDownArrow = function () {
    var src = $('#SideNavPetScrollDown').attr('src');
    src = src.replace('mynav_on_down', 'mynav_down');
    $('#SideNavPetScrollDown').attr('src', src);
    PSideNav.downEnabled = false;
}


/////////////////////////
//
// PSlider
//
/////////////////////////


function PSlider() {

    /* Start position */
    var position = 0;
    /* Max number of items to scroll */
    var maxLength = 2;
    /* Offset */
    var offset = 515;
    /* Right trigger (item that causes it to scroll right) */
    var rightTrigger = '.FooterNavRight';
    /* Left trigger (item that causes it to scroll left) */
    var leftTrigger = '.FooterNavLeft';
    /* Div that actually moves */
    var toMove = '.gallery';
    /* Wrapper element, all others are children of this */
    var starterElem = '';
    var me = this;

    this.init = function (elem) {
        starterElem = elem;

        var width = (offset * (maxLength + 1)) + 'px'
        $(elem).find(toMove).css('width', width);
        $(elem).find(rightTrigger).click(this.addPos);
        $(elem).find(leftTrigger).click(this.removePos);
    }

    this.initAll = function (elem, pos, maxL, offs, rt, lt, toM) {
        position = pos;
        maxLength = maxL;
        offset = offs;
        rightTrigger = rt;
        leftTrigger = lt;
        toMove = toM;
        me.init(elem);
        me.toggleTriggers();
    }

    this.addPos = function () { if (position < maxLength) { position = position + 1; }; me.setPos(); me.toggleTriggers(); return false; }
    this.removePos = function () { if (position > 0) { position = position - 1; }; me.setPos(); me.toggleTriggers(); return false; }
    this.setPos = function () {
        $(starterElem).find(toMove).animate({
            left: "-" + (position * offset) + "px"
        }, {
            duration: 600,
            specialEasing: {
                width: 'linear',
                height: 'easeOutBounce'
            }
        });
    }
    this.toggleTriggers = function () {
        if (position == 0) {
            $(starterElem).find(leftTrigger).addClass(leftTrigger.replace('.', '') + 'Disabled');
        }
        else {
            $(starterElem).find(leftTrigger).removeClass(leftTrigger.replace('.', '') + 'Disabled');
        }
        if (position >= maxLength) {
            $(starterElem).find(rightTrigger).addClass(rightTrigger.replace('.', '') + 'Disabled');
        }
        else {
            $(starterElem).find(rightTrigger).removeClass(rightTrigger.replace('.', '') + 'Disabled');
        }
    }
}



/////////////////////////
//
// PValidation
//
/////////////////////////


function PValidation() {

    var _elements = new Array();
    var me = this;

    this.setElement = function () {
        if (arguments.length == 1) {
            ell = arguments[0];
            key1 = arguments[0].id;
        } else {
            key1 = arguments[0];
            ell = arguments[1];
        }
        var defaults = { element: ell, jquery: $(ell), isValid: false, onError: function () { }, onPass: function () { }, eventId: false };
        if (arguments.length == 3) defaults = $.extend({}, defaults, arguments[2] || {});
        _elements[key1] = defaults;
    }

    this.getElement = function (key) {
        return _elements[key];
    }

    this.setIsElementValid = function (key, b) {
        if (_elements[key]) {
            _elements[key].isValid = b;
        }
    }

    this.isValid = function () {
        var bb = true;
        for (eachEl in _elements) {
            if (!_elements[eachEl].isValid) {
                bb = false;
                _elements[eachEl].onError(_elements[eachEl].element);
            } else {
                _elements[eachEl].onPass(_elements[eachEl].element);
            }
        }
        return bb;
    }

    this.clearTimeout = function (key) {
        if (!_elements[key]) return;
        if (_elements[key] != false)
            clearTimeout(_elements[key].eventId);
        _elements[key].eventId = false;
    }

    this.setEventId = function (key, id) {
        if (!_elements[key]) return;
        _elements[key].eventId = id;
    }

}

function PEventHandler() {
    var me = this;
    this.element = null;
    this.timerId = -1;
    this.onEvent = function (data) { alert('Please override the onData function first'); }
}


function PDateValidator(y, m, d, optional) {
    var me = this;
    this.yearElement = y;
    this.monthElement = m;
    this.dayElement = d;
    this.isOptional = optional || false;
    this.isValid = function () {
        var yv = $(me.yearElement).val();
        var mv = $(me.monthElement).val();
        var dv = $(me.dayElement).val();
        if (me.isOptional) {
            return yv == "" &&
                    mv == "" &&
                    dv == "";
        }
        if (yv == "" || dv == "" || mv == "") return false;
        var yvi = parseInt(yv);
        var mvi = parseInt(mv);
        var dvi = parseInt(dv);
        var date = new Date(yvi, mvi - 1, dvi);
        return date.getFullYear() == yvi && date.getMonth() == mvi - 1 && date.getDate() == dvi;
    }
    this.getDate = function () {
        var yv = $(me.yearElement).val();
        var mv = $(me.monthElement).val();
        var dv = $(me.dayElement).val();
        var yvi = parseInt(yv);
        var mvi = parseInt(mv);
        var dvi = parseInt(dv);
        return new Date(yvi, mvi - 1, dvi);
    }
}



function PChain(el, nxt, prv, fn) {

    var me = this;

    el.onblur = el.onkeyup = function (e) {
        var charCode = -1;
        try {
            if (event.keyCode) charCode = event.keyCode;
        } catch (exp) { }
        try {
            if (e.which) charCode = e.which;
        } catch (exp) { }
        me.onEvent(el);
        if (charCode == -1) return fn(el, -1);
        var rs = fn(el, charCode);
        if (rs == 0) {
            return false;
        }
        if (rs > 0 && nxt) {
            nxt.focus();
            nxt.value += "";
        }
        if (rs < 0 && prv) {
            prv.focus();
            prv.value += "";
        }
        if (rs > 0) me.onEnd(el);
        return true;
    }

    this.onEnd = function () { }

    this.onEvent = function () { }

}





/////////////////////////
//
// PAccount
//
/////////////////////////

if (typeof PAccount == "undefined") PAccount = {};

PAccount.userNameLength = 6;
PAccount.passwordLength = 6;

PAccount.pets = [];

PAccount.dashboardIndex1 = PAccount.dashboardIndex2 = PAccount.dashboardIndex3 = 0;
PAccount.dashboardArr1 = [];
PAccount.dashboardArr2 = [];
PAccount.dashboardArr3 = [];
PAccount.dashboardPanels1 = null;
PAccount.dashboardPanels2 = null;
PAccount.dashboardPanels3 = null;

PAccount.validateUserName = function (elid, onValidateFn, onStartValidateFn) {
    var txtUsername = document.getElementById(elid);
    var jq = $(txtUsername);
    var username = $.trim(jq.val());
    if (username.length < PAccount.userNameLength) {
        onValidateFn(elid, 1);
        return;
    }
    var handler = new PEventHandler();
    handler.element = txtUsername;
    handler.onEvent = function (data) {
        onValidateFn(elid, data);
    }
    onStartValidateFn(elid);
    PToolkit.callAtlas(null, PCS.Web.WebServices.ValidationWebMethods.Registration.CheckUserName, username,
        PUI.oId == '' ? 0 : parseInt(PUI.oId), handler.onEvent);
}

PAccount.validateEmail = function (elid, onValidateFn, onStartValidateFn) {
    var el = document.getElementById(elid);
    var jq = $(el);
    if ($.trim(jq.val()) == "") {
        onValidateFn(elid, 1);
        return;
    }
    if (jq.val().match(PToolkit.emailRegex) == null) {
        onValidateFn(elid, 1);
        return;
    }
    var handler = new PEventHandler();
    handler.element = el;
    handler.onEvent = function (data) {
        onValidateFn(elid, data);
    }
    onStartValidateFn(elid);
    PToolkit.callAtlas(null, PCS.Web.WebServices.ValidationWebMethods.Registration.CheckEmail, $.trim(el.value),
        PUI.oId == '' ? 0 : parseInt(PUI.oId), handler.onEvent);
}




PAccount.showRememberPass = function () {
    $.blockUI({
        css: {
            width: '300px',
            height: '385px',
            allowBodyStretch: true,
            border: 'none',
            backgroundColor: 'transparent'
        },
        centerFull: true,
        message: $("#" + PUI.forgotpassui)
    });
}



PAccount.sendForgottenPass = function (id, emailSubject) {
    var j = document.getElementById(id);
    var eSubject = $("span[id$='" + emailSubject + "']").html();
    var email = $.trim(j.value);
    var msgIdPrefix = "ForgottenPasswordMsg";
    $("." + msgIdPrefix + "Intro").hide();
    if (email != "") {
        PToolkit.callAtlas(
                null,
                PCS.Web.WebServices.ValidationWebMethods.Registration.SendForgottonPass,
                eSubject,
                email,
                PAccount._handlePasswordRecoveryResponse);

        $("." + msgIdPrefix + "Pass").show();
    }
    else
        $("." + msgIdPrefix + "Fail").show();
}

PAccount._handlePasswordRecoveryResponse = function (b) {
    if (b) {
        $("#dv_forgotpass_error").hide();
        $("#dv_forgotpass_confirm").show();
    } else {
        $("#dv_forgotpass_error").show();
        $("#dv_forgotpass_confirm").hide();
    }
};


PAccount.showChangeEmailDialogue = function (dvid, arg2) {
    $.blockUI($.extend({},
                    {
                        css: {
                            width: '300px',
                            height: '120px',
                            allowBodyStretch: true,
                            border: 'none',
                            backgroundColor: 'transparent'
                        },
                        centerFull: true,
                        message: $("#" + dvid)
                    }, arg2 || {}));
}


PAccount.changeAsYouType = function (el, container, msg) {
    el.onkeyup = function () {
        $(container).text($(this).val() == "" ? msg : $(this).val());
    }
}

PAccount.setThumbnailMedia = function (hdnId, bgId, hc, tc, bgUrl) {
    $(hdnId).val(bgId + "");
    $("#profileHead").css("background", "transparent url(" + bgUrl + ") no-repeat");
    $("#h2Header").css("color", hc);
    $("#h3Tagline").css("color", tc);
}


PAccount.slideMyPCS = function (a) {
    var jel = $("#homeFamilySlider");
    var width = parseInt(jel.css("width").replace(/px/ig, ''));
    var left = parseInt(jel.css("left").replace(/px/ig, ''));
    var next = (a * 296) + left;
    if (next <= -1 * width || next > 0) return;
    //jel.css("left", next + "px");
    jel.animate({ 'left': next + "px" }, { "duration": 300, "queue": false });
}

PAccount.animateDashboardPanel = function (pnl, ind) {
    $(pnl).animate({
        left: (ind * -262) + "px"
    }, {
        duration: 200,
        specialEasing: {
            width: 'linear',
            height: 'easeOutBounce'
        }
    });
}




/////////////////////////
//
// PToolkit
//
/////////////////////////
var PToolkit = {

    // -------------------------------------------------------------------------------------------------
    /**
    * Allows you do something like:
    * 
    * function a(b,c){ alert(b+c); };
    * var params = new Array();
    * params.push(a);
    * params.push(2);
    * params.push(3);
    * PToolkit.doFunction(params); <--- alerts '5'
    */
    doFunction: function (params) {
        call = "params[0](";
        for (i = 1; i < params.length; i++) call += "params[" + i + "]" + (i == params.length - 1 ? "" : ",");
        return eval(call + ")");
    },

    getDimensions: function (el) {
        var fixW = parseInt(el.style.width);
        var fixH = parseInt(el.style.height);
        if (!isNaN(fixW) && !isNaN(fixH)) return { width: fixW, height: fixH };
        if (el.offsetWidth)
            if (el.offsetHeight)
                return { width: el.offsetWidth, height: el.offsetHeight };
        var originalVisibility = el.style.visibility;
        var originalPosition = el.style.position;
        el.style.visibility = 'hidden';
        el.style.position = 'absolute';
        el.style.display = '';
        var originalWidth = el.clientWidth;
        var originalHeight = el.clientHeight;
        el.style.display = 'none';
        el.style.position = originalPosition;
        el.style.visibility = originalVisibility;
        return { width: originalWidth, height: originalHeight };
    },

    getSize: function(obj) {
        if (obj.offsetWidth) if (obj.offsetHeight)
            return { width: obj.offsetWidth, height: obj.offsetHeight };
        var originalVisibility = obj.style.visibility;
        var originalPosition = obj.style.position;
        obj.style.visibility = 'hidden';
        obj.style.position = 'absolute';
        obj.style.display = '';
        var originalWidth = obj.clientWidth;
        var originalHeight = obj.clientHeight;
        obj.style.display = 'none';
        obj.style.position = originalPosition;
        obj.style.visibility = originalVisibility;
        return { width: parseInt(originalWidth), height: parseInt(originalHeight) };
    },


    // -------------------------------------------------------------------------------------------------
    /**
    * Calls .NET's Ajax methods however adds our pre-loader to a given div;
    * 
    *  USAGE:
    *         PToolkit.callAtlas(
    *             [id of DOM element to hold the animated gif or its direct reference],
    *             [Reference to WebMethod, eg: [Web Namespace].WebServices.Foo.Bar],
    *             {ARG1 for Bar()}, __
    *             {ARG2 for Bar()},   |
    *             ....                |---> optional
    *             {ARG# for Bar()}, __|
    *             [reference to function to call onSuccess of Bar()] or null
    *             );
    */
    callAtlas: function () {
        if (arguments.length < 3) return;
        var params = new Array();
        for (argi = 1; argi < arguments.length - 1; argi++) params.push(arguments[argi]);
        if (!this.holder) this.holder = new Object();
        if (!this.holder.events) this.holder.events = new Array();
        if (!this.holder.caller) this.holder.caller = function (iinti) { if (this.events[iinti]) this.events[iinti](); }
        var hndl = new Object();
        hndl.container = null;
        hndl.showImage = function () { }
        if (arguments[0]) {
            if (typeof arguments[0] == "string") hndl.container = document.getElementById(arguments[0]);
            else hndl.container = arguments[0];
            hndl.showImage = function () {
                if (!hndl.showImage) return;
                PToolkit.clearChildNodes(hndl.container);
                if ($.browser.msie) var imgloader = new Image();
                else var imgloader = document.createElement("img");
                imgloader.src = "/img/ui/ajax-loader.gif";
                hndl.container.appendChild(imgloader);
            }
            this.holder.events.push(hndl.showImage);
        }

        hndl.history = arguments[arguments.length - 1];
        hndl.onSuccess = function () {
            hndl.showImage = null;
            if (hndl.container)
                PToolkit.clearChildNodes(hndl.container);
            var mp = new Array();
            if (hndl.history) mp.push(hndl.history);
            for (thisi = 0; thisi < arguments.length; thisi++) mp.push(arguments[thisi]);
            PToolkit.doFunction(mp);
        }
        params.push(hndl.onSuccess);
        setTimeout('PToolkit.holder.caller(' + (PToolkit.holder.events.length - 1) + ')', 1000);
        PToolkit.doFunction(params);
    },

    clearTextNodes: function (node, recursive) {
        if (node.nodeType) {
            if (node.nodeType == 3) {
                node.parentNode.removeChild(node);
            }
            else {
                if (node.childNodes) {
                    for (nui = 0; nui < node.childNodes.length; nui++) {
                        if (node.childNodes[nui]) {
                            if (node.childNodes[nui].nodeType == 3) {
                                node.removeChild(node.childNodes[nui]);
                                continue;
                            }
                            if (recursive) PToolkit.clearTextNodes(node.childNodes[nui], true);
                        }
                    }
                }
            }
        }
    },

    clearChildNodes: function (node) {
        if (!node) return;
        if (!(node.childNodes)) return;
        while (node.childNodes.length > 0)
            node.removeChild(node.firstChild);
    },

    getTextValue: function (node) {
        if (!node) return;
        if (node.nodeType == 3) return node.nodeValue;
        var str = "";
        for (intnode = 0; intnode < node.childNodes.length; intnode++)
            str += PToolkit.getTextValue(node.childNodes[intnode]);
        return str;
    },

    getASPControlById: function (idOfC) {
        var docEl = document.getElementById(idOfC);
        if (!(docEl))
            docEl = document.getElementById(idOfC.replace(/\$/ig, '_'));
        return docEl;
    },

    cleanUserName: function (uname) {
        return uname.replace(/\s+/ig,' ').replace(/[^\.-_0-9A-Za-z ]/ig, ''); ;
    },

    // Returns a "table" element with "r" number of rows, each with "c" number of columns:
    // the output is an object with the following properties:
    // .table:		the reference to the table element
    // .tbody:		the reference to the tbody inside the table
    // .rows:		an array of rows, where each element has two attribues (row and cells)
    getTBL: function (r, c) {
        var tbl = document.createElement("table");
        var tbd = document.createElement("tbody");
        tbl.appendChild(tbd);
        tbl.cellPadding = tbl.cellSpacing = "0";
        var rws = new Array();
        for (irow = 0; irow < r; irow++) {
            var rw = document.createElement("tr");
            var cls = new Array();
            for (icell = 0; icell < c; icell++) {
                var tdd = document.createElement("td");
                rw.appendChild(tdd);
                cls.push(tdd);
            }
            rws.push({ row: rw, cells: cls });
            tbd.appendChild(rw);
        }
        return { table: tbl, tbody: tbd, rows: rws };
    },

    getAge: function (d1) {
        var d2 = new Date();
        return (d2.getYear() - d1.getYear()) - ((d2.getMonth() > d1.getMonth() || d1.getMonth() == d2.getMonth() && d2.getDate() >= d1.getDate()) ? 0 : 1);
    },

    makeDynamicHint: function (input, txt) {
        if (!input) return;
        $(input).removeClass("grey");
        input.onclick = input.onfocus = function () {
            if (this.value == txt) {
                this.value = "";
                $(this).removeClass("grey");
            }
        }
        input.onblur = function () {
            if (this.value == "") {
                //this.value = txt;
                $(this).addClass("grey");
            }
        }
        if ($(input).val() == "") {
            $(input).addClass("grey");
            $(input).val(txt);
        }
    },

    restrictTextarea: function (txtarea, len, extraFn) {
        if (!txtarea) return;
        txtarea.onkeyup = txtarea.onkeydown = function () {
            if ($(this).val().length > len) {
                $(this).val($(this).val().substring(0, len));
            }
            if (extraFn) extraFn(this);
        }
    },

    isFieldOtherField: function (el) {
        return $(el).val().match(/(^other )|( other )|( other$)/ig) != null;
    },

    goToAnchor: function (anc) {
        document.location.href = document.location.href.replace(/#.*/, '') + '#' + anc;
    },

    isValidEmail: function (str) {
        return str.match(PToolkit.emailRegex) != null;
    },

    back: function (n) {
        if (history) history.go(n);
        if (window.history && window.history.go) window.history.go(n);
        if (window.location && window.location.history) window.location.history.go(n);
    }

}







/////////////////////////
//
// PSearch
//
/////////////////////////
PSearch = {};

PSearch.submit = function (txtLocationId, txtKeywordId) {
    var loc = $.trim($("#" + txtLocationId).val());
    var keyword = $.trim($("#" + txtKeywordId).val());
    PSearch.submitKW(loc, keyword);
}

PSearch.submitKW = function (loc, keyword) {
    var fn = function (q) {
        document.location.href = PSearch.cleanUrl() + "?keyword=" + keyword + q;
    }
    PSearch.tryGoogleFirst(loc, fn);
}

PSearch.submitAnimal = function (ddlBreedId) {

    var breed = $.trim($("#" + ddlBreedId + " option:selected").val());
    if (breed == '0') {
        document.location.href = PSearch.cleanUrl();
    }
    else {
        document.location.href = PSearch.cleanUrl() + '?br=' + breed;
    }
}

PSearch.submitMonth = function (ddlMonthId) {
    var month = $.trim($("#" + ddlMonthId + " option:selected").val());
    document.location.href = PSearch.cleanSimple() + '?month=' + month;
}

PSearch.tryGoogleFirst = function (loc, fn) {
    if (typeof PMap == "object") {
        var fnSuccess = function (addr, location) {
            var ml = PMap.getLocationFromGLocation(location[0]);
            if (ml.countryName.toLowerCase() != "ca") {
                fnFail(location);
                return;
            }
            fn('&loc=' + loc + '&prov=' + ml.provinceName + '&city=' + ml.cityName + '&cords=' + ml.GLatLng.lat() + "," + ml.GLatLng.lng());
        }
        var fnFail = function (data) {
            fn('&loc=' + loc);
        }
        PMap.findAddress(loc, fnSuccess, fnFail);
    }
}

PSearch.submitMini = function (txtLocationId, txtKeywordId) {
    var loc = $.trim($("#" + txtLocationId).val());
    var keyword = $.trim($("#" + txtKeywordId).val());
    var fn = function (q) {
        document.location.href = '/' + PUI.culture + "/PetPals/Search/All/Latest/1?keyword=" + keyword + q;
    }
    PSearch.tryGoogleFirst(loc, fn);
}

PSearch.cleanQueryStrings = function (url) {
    if (url.indexOf('?') > 0) 
        url = url.split('?')[0];
    return url.match(/^http:\/\/[\d\.]+/ig) != null ?
            url.replace(/(\/)?\/\d+/g, function ($0, $1) {
                return $1 ? $0 : '/1';
            }) : url.replace(/\/\d+/ig, '/1');
}

PSearch.cleanSimple = function () {
    return PSearch.cleanQueryStrings(document.location.href);
}
PSearch.cleanUrl = function () {
    var url = document.location.href.match(/\/search\//ig) == null ?
        '/' + PUI.culture + "/PetPals/Search/All/Latest/1" : document.location.href;
    return PSearch.cleanQueryStrings(url);
}

PSearch.goToSearchIndex = function (ind) {
    var url = document.location.href;
    url = url.match(/\/\d+/ig) == null ? url + (url.match(/\/$/) == null ? '/' : '') + ind : url.replace(/\/\d+/ig, '/' + ind);
    document.location.href = url;
}

/* Assumes the use of the SearchResult && SearchPopup Controls */
PSearch.PopupStart = function (ucId, modifier, offsetLeft, offsetTop) {
    $(modifier + '.PetResult').mouseenter(function () {
        var posit = $(this).position();
        var info = $(this).parent().siblings('input[type="hidden"]').val();
        var infoArray = eval(info);
        //Set to current pet name
        $("#" + ucId + "_search_conversation_header div").html(infoArray[0]);
        //Set to current pet breed
        $("#" + ucId + "_breed").html(infoArray[1]);
        //Set to current pet hearts
        $("#" + ucId + "_search_heart_count div").html(infoArray[2]);
        var isDog = infoArray[3];
        //var imgDogCat = $('#search_conversation_catordog').attr('src');
        var imgDogCat = $("#" + ucId + "_search_conversation_header div");
        if (isDog == true) {
            $(imgDogCat).removeClass('search_conversation_header_cat').addClass('search_conversation_header_dog');
        }
        else {
            $(imgDogCat).removeClass('search_conversation_header_dog').addClass('search_conversation_header_cat');
        }

        $("#" + ucId + "_search_conversation_catordog").attr('src', imgDogCat);
        $("." + ucId + "_search_profile_link").attr('href', infoArray[4]);
        //show the menu directly over the placeholder

        $("div[id$='" + ucId + "_petNameOverlaySmall']").css({ "left": (posit.left + offsetLeft) + "px", "top": (posit.top + offsetTop + 12) + "px", "position": "absolute" })
                .show()
                .mouseleave(function () { PSearch.HidePopups(ucId); })
                .addClass("clickable")
                .bind('click', function () {
                    document.location.href = infoArray[4];
                });
        $("img[id$='" + ucId + "_imgPetOverlay']").css({ "left": (posit.left + -6 + offsetLeft) + "px", "top": (posit.top - 6 + offsetTop) + "px", "position": "absolute" }).show();
        //Timer 
        $(this).oneTime(1000, "ShowFull", function () { PSearch.ShowFull(ucId); });
        $('#main').addClass("BigZed");
    });

}

PSearch.HidePopups = function (ucId) {
    $("div[id$='" + ucId + "_petNameOverlaySmall']").hide();
    $("img[id$='" + ucId + "_imgPetOverlay']").hide();
    $("div[id$='" + ucId + "_search_conversation_full']").hide();
    $('.PetResult').stopTime("ShowFull");
    $('#main').removeClass("BigZed");
}

PSearch.ShowFull = function (ucId) {
    $("div[id$='" + ucId + "_search_conversation_full']").show();
    $("div[id$='" + ucId + "_petNameOverlaySmall']").removeClass("clickable").unbind('click');
}



///////////////////////////////////////////
// inits
///////////////////////////////////////////

$(document).ready(function () {
    PUI.initHeader();
    PUI.initBrands();
    PUI.initSideNav();
    PUI.initRQL();

    $("select.uniformField, input.uniformField").uniform();

    // PSlider
    $('.petbrands').each(function () {

        var sizeOfGal = $(this).find('.gallery a').size();
        var maxScroll = Math.ceil(sizeOfGal / 5);
        var slider = new PSlider();
        slider.initAll(this, 0, maxScroll - 1, 515, '.FooterNavRight', '.FooterNavLeft', '.gallery');
    });
});
