﻿function initGA() {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
}

//page must start with a '/'
function trackPageView(page) {
    try {
        var pageTracker = _gat._getTracker("UA-12373822-1");
        pageTracker._trackPageview(page);
    } catch (err) { }
}

YUI({ combine: true, timeout: 10000 }).use("node", "io-base", function(Y) {
    var getNode = function(id) { return Y.one('#' + id); }
    var hideNode = function(id) { getNode(id).setStyle('display', 'none'); };
    var showNode = function(id) { getNode(id).setStyle('display', 'block'); };

    //gotta define this function globally since we need to add it as a handler
    window.scheduledSubdomainCheck = null;

    window.tryValidateSubdomain = function() {
        Y.io(
            'verifysubdomain.ashx?responseType=raw&subdomain=' + escape(getNode(txtSubdomainId).get('value')),
            {
                method: 'GET',
                timeout: 5000,
                on:
                {
                    start: function(transId, arguments) {
                    },
                    success: function(transId, response, arguments) {
                        if (response.responseText == 'available') {
                            getNode(lblSubdomainErrorId).replaceClass("error", "valid");
                            getNode(lblSubdomainErrorId).set("innerHTML", "Available!");
                        }
                        else {
                            getNode(lblSubdomainErrorId).replaceClass("valid", "error");
                            if (response.responseText == 'unavailable')
                                getNode(lblSubdomainErrorId).set("innerHTML", "This web address is not available. Please try another.");
                            else if (response.responseText == 'invalid')
                                getNode(lblSubdomainErrorId).set("innerHTML", "This web address is not valid. Web addresses may only contain letters, numbers, and hyphens (-)");
                            else
                                getNode(lblSubdomainErrorId).set("innerHTML", "This web address is not valid. Web addresses may only contain letters, numbers, and hyphens (-)");
                        }

                        showNode(lblSubdomainErrorId);
                    },
                    failure: function(transId, response, arguments) {
                        getNode(lblSubdomainErrorId).set("innerHTML", "This web address is not valid. Web addresses may only contain letters, numbers, and hyphens (-)");
                        showNode(lblSubdomainErrorId);
                    },
                    end: function(transId, arguments) {
                        window.scheduledSubdomainCheck = null;
                    }
                }
            });
    };

    window.toSubdomainName = function(text) {
        return text.toLowerCase().replace(new RegExp('[^a-z0-9\-]+', 'g'), ''); //new RegExp('(^\-)|([^a-z0-9\-]+)|(\-$)', 'g'), 'Ü');
        //replace(new RegExp('[^^]\s+[^$]','g'), '™')
    }

    window.onChurchNameChanged = function() {
        if (window.scheduledChurchNameChanged)
            clearTimeout(window.scheduledChurchNameChanged);

        window.scheduledChurchNameChanged = setTimeout(trySubdomainAutoFill, 400);
    }

    trySubdomainAutoFill = function() {
        var txtSiteName = getNode(txtSiteNameId);
        var txtSubdomainName = getNode(txtSubdomainId);

        var oldCalcedSubdomain = null;
        if (txtSiteName.get('defaultvalue'))
            oldCalcedSubdomain = toSubdomainName(txtSiteName.get('defaultvalue'));

        if (oldCalcedSubdomain == null || oldCalcedSubdomain == txtSubdomainName.get('value')) {
            txtSiteName.set('defaultvalue', txtSiteName.get('value'))
            txtSubdomainName.set('value', toSubdomainName(txtSiteName.get('value')));

            onSubdomainTextChanged();
        }
    }

    window.onSubdomainTextChanged = function() {

        if (window.scheduledSubdomainCheck)
            clearTimeout(window.scheduledSubdomainCheck);

        getNode(lblSubdomainErrorId).set("innerHTML", "<img style='float:left' src='images/miniloader.gif' alt='checking'><span style='color:#999'>Checking availiability...</span>")
        showNode(lblSubdomainErrorId);

        window.scheduledSubdomainCheck = setTimeout(tryValidateSubdomain, 400);
    }
});

attachImagePopupHandler = function(Y, imageNodeId, imageUrl, altText, popupImgWidth) {
    //alert('called attachImagePopupHandler with ' + imageNodeId + ', ' + imageUrl);
    var imageNode = Y.one('#' + imageNodeId);
    var dirs = ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
    var bgDivsHtml = "";
    var imgWidth = popupImgWidth;
    var padding = 12;

    for (var i in dirs)
        bgDivsHtml += "<div class=\"popup-bg bg-" + dirs[i] + "\"></div>";

    var screenshotImgId = imageNodeId + "ssimg";
    var screenshotImgUrl = imageUrl + "?width=" + imgWidth;

    if (window.preloadImgGroup == undefined)
        window.preloadImgGroup = new Y.ImgLoadGroup({ name: 'group1', timeLimit: 0.1 });
    window.preloadImgGroup.registerImage({ domId: screenshotImgId, srcUrl: screenshotImgUrl });

    if (imageNode.overlay == undefined) {
        imageNode.overlay = new Y.Overlay({
            zIndex: 1000,
            visible: false,
            width: imageNode.get('clientWidth'),
            x: imageNode.getX(),
            y: imageNode.getY(),
            bodyContent: "<![if !IE]>" + bgDivsHtml + "<![endif]><div style=\"background:#fff;padding:" + padding + "px;\"><img style=\"width:100%\" id=\"" + screenshotImgId + "\" alt=\"" + altText + "\"/><label style=\"margin-top:6px;\">Click anywhere to close popup.</label></div>"
        });

        imageNode.overlay.render(); //render with the imagenode as the parent
        imageNode.overlay.get('boundingBox').setStyle('opacity', '0');
        imageNode.overlay.get('boundingBox').setStyle('overflow', 'visible');
        //imageNode.overlay.get('boundingBox').setStyle('border', '1px solid #ccc');
    }

    var handlerFunc = function(evt) {
        if (imageNode.overlayAnim != undefined)
            imageNode.overlayAnim.stop();

        var visible = evt.type == "mouseover" || (evt.type == "click" && !imageNode.overlay.get('visible'));

        if (visible) {
            imageNode.overlayAnim = new Y.Anim({ node: imageNode.overlay.get("boundingBox"), duration: 0.25, easing: Y.Easing.easeOut,
                to: { opacity: 1, width: imgWidth + padding * 2, xy: [(imageNode.get('winWidth') - imgWidth) / 2 - padding, imageNode.getY() + imageNode.get('clientHeight') / 2 - 250] }
            });
            imageNode.overlayAnim.run();
            imageNode.overlay.set('visible', true);
        }
        else {
            imageNode.overlayAnim = new Y.Anim({ node: imageNode.overlay.get("boundingBox"), duration: 0.25, easing: Y.Easing.easeOut,
                to: { opacity: 0, width: imageNode.get('clientWidth'), xy: imageNode.getXY() }
            });
            imageNode.overlayAnim.run();
            imageNode.overlayAnim.on('end', function() { imageNode.overlay.set('visible', false); });
        }
    };

    //    Y.on("mouseenter", handlerFunc, imageNode);
    //    Y.on("mouseleave", handlerFunc, imageNode);
    Y.on("click", handlerFunc, imageNode);
    Y.on("click", handlerFunc, imageNode.overlay.get('boundingBox'));
};



