﻿function guidePageLoad() {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (!prm.get_isInAsyncPostBack()) {
            prm.add_endRequest(onEndRequestMyGuide);
            guideToolBoxUpdate();
        }
    
    }

    function CreateNewGuide() {
        eval(uiLnkCreateNewGuidePostback);
    }   

    function onEndRequestMyGuide(sender, args) {
        var caller = sender._postBackSettings.panelID;
        caller = caller.substr(caller.indexOf('|') + 1);
        caller = caller.replace(/\$/g, "_");
        
        if(jQuery('#' + caller).parents(guideToolsClass).length){
            guideToolBoxUpdate();

            buildMyGuideToolsForm();
            return;
        }
        
    }
    function guideToolBoxUpdate()
    {
        guide.updateStatus(postbackGuideToolsCount++);
        initFancyBoxMyGuide();
        jQuery(function(){
            guide.showSendPopup();
            guide.hideSendPopup();

            jQuery('#toFriendPopup input[id$="Captcha"]').focus(function(){
                jQuery('#toFriendPopup .wrongCaptcha').fadeOut();
            });
        });  
       
    }

    function initFancyBoxMyGuide()
    {
        jQuery(function () {
            jQuery("#fancybox-content a.close").live("click", function () {
                jQuery.fancybox.close();
                return false;
            });
            jQuery("a.mobilePopupLink").fancybox({
                'onClosed': function () {
                    jQuery('#mobilePopup .error').hide();
                    jQuery('#mobilePopup .emailInput').val('');
                }
            
            });
            

            jQuery("a.toFriendPopupLink").fancybox({
                'scrolling': 'no',
                'onClosed': function () {
                    jQuery('#toFriendPopup .error,#toFriendPopup .wrongCaptcha').hide();
                    jQuery('#toFriendPopup input[type="text"], #toFriendPopup textarea').val('');
                }
            });

            jQuery("a.createGuidePopupLink").fancybox({
                'scrolling': 'no'
            });
        });
        
    }

    jQuery(function(){
        buildMyGuideToolsForm();
        
    })

    function buildMyGuideToolsForm()
    {
        jQuery('.myGuideTools .row').each(function() {
            if (!jQuery(this).find('.gottenInfo').length) {
                jQuery(this).children('.txtInput, .btnWrapper').show();
            }
            else {
                jQuery(this).children('.txtInput, .btnWrapper').hide();
            }
        });
        
    }


function MyGuideRequest(externalEntityId, entityType, lcid, control, action, dbOwnerId) {
    this.externalEntityId = externalEntityId;
    this.entityType = entityType;
    this.lcid = lcid;
    this.control = control;
    this.action = action;
    this.dbOwberId = dbOwnerId;
}

function MyGuide() {
}
jQuery.extend(MyGuide.prototype, {
    constants: {
        guideHandlerUrl: "/layouts/MyGuide/ChangeMyGuide.ashx?entityid=##entityid##&entityType=##entityType##&action=##action##&lcid=##lcid##&dbOwnerId=##dbOwnerId##",
        entityType: "##entityType##",
        itemIdParameter: "##entityid##",
        actionParameter: "##action##",
        lcidParameter: "##lcid##",
        dbOwnerIdParameter: "##dbOwnerId##",
        guideStatusTemplate: " (##amount##)",
        guideElementsAmountTemplate: "##amount##"
    },

    addToMyGuide: function (externalEntityId, entityType, lcid, dbownerId, control) {

        var request = new MyGuideRequest(externalEntityId, entityType, lcid, jQuery(control).parent(), "Add", dbownerId);

        this.animateAddToMyGuide(control);

        this.sendChangeMyGuideRequest(this.constructAddToMyGuideUrl(request), request);



    },

    removeFromMyGuide: function (externalEntityId, entityType, lcid, dbownerId, control) {
        var request = new MyGuideRequest(externalEntityId, entityType, lcid, jQuery(control).parent(), "Remove", dbownerId);

        this.sendChangeMyGuideRequest(this.constructAddToMyGuideUrl(request), request);
    },

    updateStatus: function (postbackCount) {
        var loading = new WoCo.loading;

        var request = new MyGuideRequest("-1", "Place", "0", null, "Update");

        this.sendChangeMyGuideRequest(this.constructAddToMyGuideUrl(request), request);
        if (postbackCount) {
            new WoCo.FormHints('.txtInput');
            new WoCo.RoundedBox('.myGuideTools .roundedBox');
            loading.hide();

        }
        jQuery('.myGuideTools .row .btnWrapper a').click(function () {
            if (!!jQuery(this).parents('.row').find('input[type="text"]').val()) {
                loading.show();
            }
        });

    },

    constructAddToMyGuideUrl: function (myGuideRequest) {
        var url = this.constants.guideHandlerUrl.replace(this.constants.itemIdParameter, myGuideRequest.externalEntityId);
        url = url.replace(this.constants.entityType, myGuideRequest.entityType);
        url = url.replace(this.constants.actionParameter, myGuideRequest.action);
        url = url.replace(this.constants.lcidParameter, myGuideRequest.lcid);
        url = url.replace(this.constants.dbOwnerIdParameter, myGuideRequest.dbOwberId);

        return url;
    },


    sendChangeMyGuideRequest: function (handlerUrl, myGuideRequest) {
        jQuery.ajax({
            type: "POST",
            url: handlerUrl,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "text",
            data: {},
            success: function (msg) {
                myGuide.notifyAddToMyGuideSucceed(myGuideRequest, msg);

            }
        });
    },

    notifyAddToMyGuideSucceed: function (myGuideRequest, guideChangeResponseJson) {
        try {
            $('html, body').animate({ scrollTop: 0 }, 'slow');

        } catch (ex) {
           
        }
        var guideChangeResponse = eval('(' + guideChangeResponseJson + ')');
        var isSwap = true;

        this.updateMyGuideStatus(guideChangeResponse);

        if (!myGuideRequest.control) {
            return;
        }

        //show guide added notification
        if (myGuideRequest.action == "Add") {

            var guidePopup = jQuery('#myGuidePopup');
            guidePopup.html(guideChangeResponse.PopupNotificationHtml);
            guidePopup.show();
            setTimeout(function () { guidePopup.hide() }, 5000);
        }
        //swap add and remove from my guide
        else {
            if (myGuideRequest.control && myGuideRequest.control.find('a.guideLink').hasClass('removeParentBox')) {
                myGuideRequest.control
                .parents('.eventItem')
                .animate({ opacity: 0 }, 500, function () { jQuery(this).hide() });
                isSwap = false;
            }
        }
        if (isSwap) {
            this.swapChangeGuideLinks(myGuideRequest);
        }



    },

    swapChangeGuideLinks: function (myGuideRequest) {
        if (myGuideRequest.control) {
            var addLink = jQuery(myGuideRequest.control).find('a.addToGuide');
            var removeLink = jQuery(myGuideRequest.control).find('a.removefromGuide');

            if (myGuideRequest.action == "Add") {
                removeLink.show();
                addLink.hide();
            }
            else {
                addLink.show();
                removeLink.hide();
            }
        }
    },

    updateMyGuideStatus: function (guideChangeResponse) {
        var myGuideStatusLink = jQuery('a[id*=uiLnkMyGuideStatus]');
        var myGuideStatusLinkText = myGuideStatusLink.text();
        myGuideStatusLink.text(guideChangeResponse.GuideStatus);
    },

    animateAddToMyGuide: function (link) {

        var startPos = jQuery(link).offset();
        var clonedObj = jQuery('.addToMyGuideNotify.original').clone();
        clonedObj.prependTo('body');
        clonedObj.css({ 'top': (startPos.top - 160) + 'px', 'left': startPos.left + 'px' });
        clonedObj.show();
        clonedObj.removeClass('original');

        clonedObj.show(1000);

        jQuery('.addToMyGuideNotify.original').hide();

        setTimeout(function () { clonedObj.remove(); }, 3000);
    },

    showSendPopup: function () {
        jQuery('a.fancylink').fancybox({
            'scrolling': 'no'
        });
        jQuery('.sendPopupResp').each(function () {
            var thisText = jQuery(this).text().toLowerCase();
            var link = jQuery(this).prev('a');
            if (thisText.indexOf('wrong') > -1) {
                jQuery('#toFriendPopup .wrongCaptcha').show();
                jQuery('a.toFriendPopupLink').click();
                jQuery('.sendPopupResp').children('h2').text('default');
            } else if (thisText != 'default') {
                jQuery(link).click();
            }
        });
    },

    hideSendPopup: function () {
        jQuery('.sendPopupResp').each(function () {
            if (jQuery(this).children('h2').text() != 'default' && jQuery(this).children('h2').text() != 'wrongcaptcha') {
                jQuery('#mobilePopup input.emailInput,#toFriendPopup input[type = text],#toFriendPopup textarea').val('');

                _gaq.push(['_trackPageview', 'My Guide just has been sent to friend']);
                _gaq.push(['LocalRollup._trackPageview', 'My Guide just has been sent to friend']);
                _gaq.push(['GlobalRollup._trackPageview', 'My Guide just has been sent to friend']);

                setTimeout(function () {
                    jQuery('#fancybox-outer #fancybox-close').click();
                }, 3000);
                setTimeout(function () {
                    jQuery('.sendPopupResp').children('h2').text('default');
                }, 4000);
            }

        });

    }

});

var myGuide = new MyGuide();

jQuery(document).ready(function () {
    myGuide.updateStatus(0);
});

