var     IS_FAVORITE_USERS_PAGE = false,
        IS_ALBUMS_PAGE         = false,
        IS_PHOTOS_PAGE         = false,
        CAN_UPLOAD_PHOTOS      = false,
        globalAJAX             = new TAjax();

jQuery.fn.extend({getCDATA: function() {
    var html = $(this).html();//this[0].innerHTML;
    if (html == null) {
        return null;
    }
    var opening = "DATA[";
    var closing = "]]";
    var b = html.indexOf(opening);
    var e = html.lastIndexOf(closing);
    var beg = (b >= 0) ? (b + opening.length) : 0;
    var end = (e >= 0) ? e : html.length;
    return html.substr(beg, end - beg);
    /*
     if($.browser.msie) {
     return this[0].childNodes[0].nodeValue;
     }
     return this[0].childNodes[1].nodeValue;
     */
}});



//------------------------------------------------------------------

function TTabsControl(tabsLocator, changeHash, followHashChanges)
{
    var self = this;

    this.hashes        = {};
    this.curWindowHash = null;
    this.tabsLocator   = tabsLocator;

    var aElems = $(tabsLocator).find('a').click(function ()
    {
        // скрыть открытую сейчас вкладку
        self.getContainerByLink( $(tabsLocator).find('a.selected').removeClass('selected') ).hide();
        // показать вкладку, соответствующую текущей ссылке
        self.getContainerByLink( $(this).addClass('selected') ).show();

        if (changeHash) {
            // если нужно обновить хэш в url страницы, делаем это (подставляется значение href ссылки)
            self.updateWindowHash( $(this).attr('href') );
        }

        return false;
    });

    // обратная связь - учитывать изменения хэша url'а и открывать нужные вкладки
    if (followHashChanges) {
        aElems.each(function (ind) {
            var windowHash = self.getWindowHashByTabLink( $(this).attr('href') );
            self.hashes[windowHash] = ind;
        });
        setInterval(function ()
        {
            self.readWindowHash();
        },
                200);
    }
};

TTabsControl.prototype = {
    getContainerByLink: function (aElem) {
        return $( aElem.attr('href') );
    },

    getWindowHashByTabLink: function (tabLink) {
        return tabLink.replace('#', '#/');
    },

    updateWindowHash: function (tabLink) {
        try {
            this.curWindowHash   = this.getWindowHashByTabLink(tabLink);
            window.location.hash = this.curWindowHash;
        } catch (e) {}
    },

    readWindowHash: function () {
        var hash = window.location.hash;
        window.status = (hash in this.hashes);
        if (hash != this.curWindowHash && (hash in this.hashes))
            $(this.tabsLocator).find('a').eq(this.hashes[hash]).click();
        else
            if (hash == '') {
                $(this.tabsLocator).find('a').eq(0).click();
            }
    }
};


// TPopupIcon
function PopupIcon(elem) {
    var self = this;
    this.elem    = elem;
    this.timer   = null;
    this.curElem = null;
    this.onGetPopupPosition = null;
    this.elem.mouseover(function () {
        if (self.timer) {
            clearTimeout(self.timer);
            self.timer = null;
        }
    }).mouseout(function () {
        self.timer = setTimeout(function () {
            self.hideIcon();
        }, 30);
    });
}

PopupIcon.prototype = {

    _initElements: function (elems) {
        var self = this;
        $(elems).mouseover(function () {
            if (self.timer) {
                clearTimeout(self.timer);
                self.timer = null;
            }
            self.showIcon($(this));
            self.curElem = this;
        }).mouseout(function () {
            self.timer = setTimeout(function () {
                self.hideIcon();
            }, 30);
        });
    },

    getCurrentElem: function () {
        return this.curElem;
    },

    showIcon: function (forElem) {
        var elemSize = yapyap.utils.geometry.getElementSize(forElem),
            pos      = [];

        if (this.onGetPopupPosition) {
            pos = this.onGetPopupPosition(elemSize, {w: this.elem.get(0).offsetWidth, h: this.elem.get(0).offsetHeight});
        }
        else {
            pos = {
                x: elemSize.l,
                y: elemSize.t - this.elem.get(0).offsetHeight + 1
            };
        }
        if (pos.x && pos.y) {
            this.elem.css({
                'left': pos.x,
                'top' : pos.y,
                'visibility': 'visible'
            });
        }
        if (pos.w)
            this.elem.css('width', pos.w);
        if (pos.h)
            this.elem.css('height', pos.h);
    },

    hideIcon: function () {
        this.elem.css('visibility', 'hidden');
    }
};
//------------------------------------------------------------------


function sendFeedbackForm(callbackSuccess, callbackError) {
    var ajaxData = {
        url   : '/ajax/Portal/sendFeedback',
        params: $('#feedback_form').serialize(),
        callbackServerError: function(responseData){
            if (callbackError)
                callbackError(responseData);
        },
        callbackAnswerOk: function(responseData){
            if (responseData) {
                if (callbackSuccess)
                    callbackSuccess(responseData);
            }
            else
                if (callbackError)
                    callbackError(responseData);
        },
        callbackAnswerHasErrors: function(responseData){
            if (callbackError)
                callbackError(responseData);
        },
        callbackEndRequest: null
    };
    globalAJAX.sendAJAXPostRequest(ajaxData, TIMEOUTS.AJAX_SEND_FEEDBACK, null);
}

function sendRegForm(callbackSuccess, callbackError) {
    var ajaxData = {
        url   : '/ajax/Portal/sendFeedback',
        params: $('#regback_form').serialize(),
        callbackServerError: function(responseData){
            if (callbackError)
                callbackError();
        },
        callbackAnswerOk: function(responseData){
            if (responseData) {
                if (callbackSuccess)
                    callbackSuccess();
            }
            else
                if (callbackError)
                    callbackError();
        },
        callbackAnswerHasErrors: function(responseData){
            if (callbackError)
                callbackError();
        },
        callbackEndRequest: null
    };
    globalAJAX.sendAJAXPostRequest(ajaxData, TIMEOUTS.AJAX_SEND_FEEDBACK, null);
}

function hideAllDialogs() {
   $('#registration, #remind, #inner-login, #feedback, #albumOptions, #widget-code, #download_data_synk , #backup_form , #bindFriendsPanel, #photoLinksMenu, #photoToolsMenu, #menuEdit, #contactsToos'  ).hide();
    $('#showPhotoToolsMenu , #showPhotoLinksMenu').removeClass('hide-menu').addClass('show-menu');
}
// blocker layer

var _$blockerLayerTemplate = $('<div id="blocker_layer"></div>');
var _$blockerLayer = null;

function showBlockerLayer () {
    var _$outer = $('#outer');
    if (_$blockerLayer == null) {
    	_$blockerLayer = _$blockerLayerTemplate.clone();
    	_$blockerLayer.appendTo(_$outer);
    }
    updateBlockerLayerSize();
};

function updateBlockerLayerSize () {
    var _$outer = $('#outer');
	if (_$blockerLayer != null) {
		var hOuter = _$outer.height();
	    var wOuter = _$outer.width();
	    _$blockerLayer.css({ width: wOuter, height: hOuter });
	}
}

function hideBlockerLayer () {
	if (_$blockerLayer != null) {
		_$blockerLayer.remove();
		_$blockerLayer = null;
	}
};

function showGlobalProgress () {
	if (_$blockerLayer != null) {
		_$blockerLayer.addClass('loading');
	}
};

function hideGlobalProgress () {
	if (_$blockerLayer != null) {
		_$blockerLayer.removeClass('loading');
	}
};

var agreementResizing = function () {
    var infoElem = $('#user_agreement'),
            infoH    = ($.browser.opera ? window.innerHeight : $(window).height()) - 280;
    if (infoH < 360)
        infoH = 250;
    else if (infoH > 450)
        infoH = 450;
    infoElem.height(infoH);
    $('#user_agreement').outerHeight((infoH - 110) + 'px');

};



$(document).ready(function() {
    agreementResizing();

    setInterval(updateBlockerLayerSize, 500);

    if (IS_PHOTOS_PAGE) {
        $('#widgetCode').focus(function(){
            this.select();
        });
    }

    //-------------------------------------------------
    $('.subscriber-name').prepend('<em></em>');

    // Login form on secondary pages
    if ($('#inner-login').size()) {
        $('#enter, #enter-inn, #enter-sms, #enter_login').click(function() {
            hideAllDialogs();
            showBlockerLayer();
            $('#inner-login').fadeIn('normal');
            $('#input_name').focus();
        });
        $('#inner-login a.close-service').click(function() {
            hideBlockerLayer();
            $('#inner-login').hide();
        });

        // Check & submit secondary login form  
        var formLoginElem = $('#inner-login form');
        $('#inner-login .complete a').click(function(){
            // setTimeout() -- fix for IE
            setTimeout(function(){
                formLoginElem.submit();
            }, 0);
        });
        formLoginElem.submit(function(){
            var loginElem = formLoginElem.find('input[name=authLogin]'),
                    passElem  = formLoginElem.find('input[name=authPassword]');
            if (!yapyap.utils.string.trim(loginElem.val())) {
                loginElem.val('').focus();
                return false;
            }
            if (!yapyap.utils.string.trim(passElem.val())) {
                passElem.val('').focus();
                return false;
            }
            return true;
        });
    }

    $('#logout').click(function(){
        setTimeout(function(){
            $('#inner-logout form').submit();
        }, 0);
    });

    //enter in index-page
    $('#login_form a.enter').click(function(){
        // setTimeout() -- fix for IE
        setTimeout(function(){
            $('#login_form').submit();
        }, 0);
    });

    // Forgot password form
    $('#wrong_and_remaind').click(function(){
        hideAllDialogs();
        $('#remind').fadeIn('normal');
        $('#remind-mail').focus();
    });

    // Feedback form
    $('#feedback_show').click(function () {
        hideAllDialogs();
        showBlockerLayer();
        $("#feedback .img_captcha").attr({ 
          src: '/action/Html/showCaptcha?captchaVarName=footerFeedbackCaptcha'
        });
        $('#feedback').fadeIn('normal').find('.success').hide();
        $('#feed_name').focus();

    });
    $('#feedback a.close-service').click(function(){
        $('#feedback').hide();
        hideBlockerLayer();
    });


    $('#feedback_form').submit(function(){
        if ($('#feedback').hasClass('progress'))
            return false;

        if (yapyap.utils.string.trim($('#feed_text').val()) == '') {
            $('#feed_text').focus();
        }
        else {
            var fields = $('#feedback').addClass('progress').find('textarea, input');
            sendFeedbackForm(function (response) {
                fields.removeAttr('disabled');
                $('#feedback').removeClass('progress');
                $('#feedback .success').show();
                $('#feedback .error').hide();
                $('#feed_text').val('');
                $('#feedback').hide();
                hideBlockerLayer();
            }, function (response) {
                fields.removeAttr('disabled');
                $('#feedback').removeClass('progress');
                $('#feedback .success').hide();
                if (response.errors && response.errors.wrongCaptcha) {
                    $('#feedback .error').show();
                }
                else {
                    alert('Ошибка сервера при отправке сообщения.\nПовторите отправку еще раз.');
                }
            });
            fields.attr('disabled', 'disabled');
        }
        return false;
    });

    // minimize header
    $('#headerToggler').click(function()  {
        if ($.cookie("headerIsHidden") == null ) {
            $.cookie("headerIsHidden", "true",  {  path:  '/',  expires:  100  });
            $('#header_outer').addClass('collapsed_head');
            $('#headerToggler').html("Развернуть меню<span></span>");
            $('#headerToggler').removeClass('hide_menu').addClass('show_menu');
        } else {
            $.cookie("headerIsHidden", null, { path: '/', expires: -1 });
            $('#header_outer').removeClass('collapsed_head');
            $('#headerToggler').html("Свернуть меню<span></span>");
            $('#headerToggler').removeClass('show_menu').addClass('hide_menu');
        }
        return false;
    });
    //hide srvice blocks
    $(document).keyup(function(event){
        if (event.keyCode == 27) {
            $('div.service, #contactsToos, #addToContactsMenu, #menuEdit, #addToContactsMenu').fadeOut();
            hideBlockerLayer();
        }
    });

    // menus in tools

    $('#showMenu').click(function() {
        if ($('#menuEdit').is(":hidden"))

        {
            hideAllDialogs();
            $('#menuEdit').slideDown();
            $(this).removeClass('show-menu') ;
            $(this).addClass('hide-menu') ;
        } else {
            $('#menuEdit').slideUp();
            $(this).addClass('show-menu') ;
            $(this).removeClass('hide-menu') ;
        }
        
    });
  
    $('#showPhotoToolsMenu').click(function() {
        if ($('#photoToolsMenu').is(":hidden"))

        {
            hideAllDialogs();
            $('#photoToolsMenu').slideDown();
            $(this).removeClass('show-menu') ;
            $(this).addClass('hide-menu') ;
        } else {
            $('#photoToolsMenu').slideUp();
            $(this).addClass('show-menu') ;
            $(this).removeClass('hide-menu') ;
        }
        });


    $('#showPhotoLinksMenu').click(function() {
        if ($('#photoLinksMenu').is(":hidden"))

        {
            hideAllDialogs();
            $('#photoLinksMenu').slideDown();
            $(this).removeClass('show-menu') ;
            $(this).addClass('hide-menu') ;
        } else {
            $('#photoLinksMenu').slideUp();
            $(this).addClass('show-menu') ;
            $(this).removeClass('hide-menu') ;
        }
    });

    // Album Page
    $('#showAlbumOptions').click(function () {
        hideAllDialogs();
        showBlockerLayer();
        $('#menuEdit').fadeOut('fast');
        $('#albumOptions').show();
        $('#inptAlbumName').focus();
    });
    $('#albumOptions a.cancel, #albumOptions a.close-service ').click(function () {
        $('#albumOptions').fadeOut('fast');
        hideBlockerLayer();
    });

    $('#show-widget-code').click(function () {
        hideAllDialogs();
        showBlockerLayer();
        $('#widget-code').show();
    });
    $('#widget-code a.close-service').click(function(){
        $('#widget-code').fadeOut('fast');
        hideBlockerLayer();
    });

    $('#showAlbumOptions, #show-widget-code').click(function(){
    	    $('#menuEdit').hide();
            $('#showMenu').addClass('show-menu') ;
            $('#showMenu').removeClass('hide-menu') ;

        });


    /*
    // alert overloading
    window.ORIGINAL_ALERT = window.alert;
    window.alert = function (str) {
        var blockLayerIsInitedByThisAlert = $('#blocker_layer').size() == 0;
        hideAllDialogs();
        showBlockerLayer();

        var $alertNode = $('<div class="acrossAlert service rc mod_shadow">' +
          '<h2>Сервисное сообщение</h2>' +
          '<p class="alertContent"></p>' +
          '<div class="btns"><input type="submit" id="doneAlert" class="blue-button ok rc2" value="Ok, закройте это окно"/></div>' +
          '<a title="Закрыть" class="close-service" href="javascript:void(0)"><img height="14" width="14" alt="Close" src="/img/i/close-service.gif"/></a>' +
          '</div>');
        $alertNode.appendTo('#outer');
        $alertNode
            .find('.alertContent').html(str).end()
            .find("a.close-service, #doneAlert").click(
                function ()
                {
                    $alertNode.fadeOut().remove();
                    if (blockLayerIsInitedByThisAlert)
                    {
                        hideBlockerLayer();
                    }
                }
            );

    }; */

});


