﻿var city_object_start_item;
var objidforcounter;
var typeforcounter;
var global_widjet_started_flag = 0;
var global_str = "";

jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this[ name.toLowerCase() ]() + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return this[ name.toLowerCase() ]()
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});


$.fn.extend({
    position: function() {
        var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;

        if (elem) {
            // Get *real* offsetParent
            offsetParent = this.offsetParent();

            // Get correct offsets
            offset = this.offset();
            parentOffset = offsetParent.offset();

            // Subtract element margins
            offset.top -= num(elem, 'marginTop');
            offset.left -= num(elem, 'marginLeft');

            // Add offsetParent borders
            parentOffset.top += num(offsetParent, 'borderTopWidth');
            parentOffset.left += num(offsetParent, 'borderLeftWidth');

            // Subtract the two offsets
            results = {
                top: offset.top - parentOffset.top,
                left: offset.left - parentOffset.left
            };
        }

        return results;
    },

    offsetParent: function() {
        var offsetParent = this[0].offsetParent;
        while (offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static'))
            offsetParent = offsetParent.offsetParent;
        return $(offsetParent);
    }
});

function num(el, prop) {
    return parseInt($.curCSS(el.jquery ? el[0] : el, prop, true)) || 0;
};


jQuery.fn.equalHeights = function(px) {
    $(this).each(function() {
        var currentTallest = 0;
        $(this).children().each(function(i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
        //if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};

$(document).ready(function () {

    $('div.lang a').filter(':not(.active)').each(function () {
        var $this = $(this);
        var url = $this.attr('class') || '';
        var rurl = '' + url;
        if (url.indexOf('?') == -1) {
            rurl += '?';
        }
        rurl += '&jsoncheck=1&jsoncallback=?';
        $this.removeAttr('href');
        $.getJSON(rurl, {}, function (data, textStatus) {
            $this.attr('href', url);
            $this.attr('class', 'active');
        });
    })

    if (city_object_start_item != 'undefined'
        && city_object_start_item != null
        && city_object_start_item == '#today_item') {
        StartWidjet();
        global_widjet_started_flag = 1;
    }
    if (typeforcounter != 'undefined' && objidforcounter != 'undefined' && typeforcounter != null && objidforcounter != null) {

        $.ajax({
            type: "GET",
            data: "objecttype=" + typeforcounter + "&objectid=" + objidforcounter,
            url: "/Counter.ashx",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });


    }

    var maxheight = 0;
    var stack = {};

    $('div.verBlock h2').each(function (index) {

        var $this = $(this);

        stack[index] = this;

        if ($this.height() > maxheight) {
            maxheight = $this.height();
        }

        if ((index + 1) % 4 == 0) {

            if (maxheight > $this.parent().height()) {
                $.each(stack, function (i, v) {
                    $(v).height(maxheight).parent().height(maxheight).css({ 'border-top': '1px solid #BFBFBF', 'border-bottom': '1px dashed #BFBFBF', 'padding-bottom': '7px', 'background-image': 'none' });
                });
            }
            maxheight = 0;
            stack = {};
        }
    })
    $.each(stack, function (i, v) {
        $(v).height(maxheight).parent().height(maxheight).css({ 'border-top': '1px solid #BFBFBF', 'padding-bottom': '7px', 'background-image': 'none' });
    });


    var menu = $('#mmenu2Container');
    var active_menu = $('#topmenu li.active');
    var last_menu = undefined;
    var last_submenu = undefined;
    var sfTimer = undefined;
    var restore_menu = function () {
        if (last_menu) {
            //last_menu.addClass("hide");
            last_menu.hide();
        }
        //if (window.console) console.log('hide menu');
    };

    menu.html($('#menuHolder').html());
    $('#menuHolder').remove();
    $('img[src$=.png], .catColumn .first,.tagBlockContainer,.tagBlockContainer div.left,.tagBlockContainer div.left div.right').ifixpng();

    //var start_offset = $('#topmenu ul').position().left || 0;
    //if (window.console) console.log(['marginLeft',start_offset]);

    $('#topmenu li').each(function () {

        var mitem = $(this);
        var id = mitem.attr('id') || '';
        if (id.length == 0 || id.substr(0, 1) != 'm')
            return;
        ///var width = start_offset;
        // mitem.prevAll().each(function() {
        //  width += $(this).outerWidth();
        //});
        var id_suffix = mitem.attr('id').substr(2);
        var sitem = $('#h' + id_suffix, menu);
        var sitems = $('div.item2', sitem);
        var active = mitem.hasClass("active");

        if (sitem.length > 0) {
            sitem.hover(
              function () {
                  //if (window.console) console.log('in subitem menu');
                  last_submenu = this;
                  active_menu.removeClass("active");
                  mitem.addClass("active");

              },
              function () {
                  //if (window.console) console.log('out subitem menu');
                  mitem.removeClass("active");
                  //$(this).addClass("hide");
                  $(this).hide();
                  active_menu.addClass("active");
                  last_submenu = undefined;
                  if (sfTimer) clearTimeout(sfTimer);
              }
            );
            sitems.each(function () {
                var $this = $(this);
                var link = $('a', $this);
                if (link.length > 0) {
                    $this.click(function () { window.location = link.attr("href"); })
                }
                $this.hover(
                 function () { $this.toggleClass("active"); },
                 function () { $this.toggleClass("active"); }
                );
            });
        }
        mitem.hover(
         function () {
             if (sfTimer) clearTimeout(sfTimer);
             restore_menu();
             if (!active) { active_menu.removeClass("active"); mitem.addClass("active"); }
             if (sitems.length > 0) {
                 sitem.css({ "left": mitem.offset().left, "top": mitem.offset().top + mitem.height() });
                 //if (window.console) console.log('show menu');
                 //sitem.removeClass("hide");
                 last_menu = sitem;
                 //sitem.fadeIn(100);
                 sitem.show();
             }
             //sitem.css("left", mitem.position().left);
             //alert(['offset left', mitem.offset().left,'position left', mitem.position().left]);

         },
         function () {
             //if (window.console) console.log('out');
             sfTimer = setTimeout(function () {
                 if (last_submenu == undefined) {
                     restore_menu();
                 }
             }, 100);
             if (!active) { active_menu.addClass("active"); mitem.removeClass("active"); }
         }

        );
    }
    );

    //---------------------------------------------------------------------------------------

    $('div.topanons').serialScroll({
        items: 'li',
        duration: 2000,
        force: true,
        axis: 'xy',
        easing: 'easeOutQuart',
        interval: 10000,
        step: 1
    });

    //---------------------------------------------------------------------------------------

    // news afisha scroll
    $('a#where, a#where2').css('cursor', 'pointer').click(function () {
        $.scrollTo('div#afisha_item');
    }
    );

    //--------------------- payed objects ---------------------------------
    if (typeof swfobject != 'undefined' && $('div#cityAccord').length > 0) {
        var vw = window.viewer || "/scripts/flash/preview.swf"; //+ "?t=" + cacheBuster;
        swfobject.embedSWF(vw, "cityAccord", stageW, stageH, "9.0.124", "/scripts/expressInstall.swf", flashvars, params);
    }

    if (typeof window.galleryimages != 'undefined' && $('div.photogallery').length > 0) {
        jQuery.PictureSlides.set({
            // Switches to decide what features to use
            useFadingIn: true,
            useFadingOut: true,
            useFadeWhenNotSlideshow: true,
            useFadeForSlideshow: true,
            useDimBackgroundForSlideshow: true,
            loopSlideshow: false,
            usePreloading: true,
            useAltAsTooltip: true,
            useTextAsTooltip: false,

            // Fading settings
            fadeTime: 500, // Milliseconds	
            timeForSlideInSlideshow: 2000, // Milliseconds

            // At page load
            startIndex: 1,
            startSlideShowFromBeginning: true,
            startSlideshowAtLoad: false,
            dimBackgroundAtLoad: false,

            // Large images to use and thumbnail settings
            images: window.galleryimages,
            startIndex: window.galleryidx || 0,
            thumbnailActivationEvent: "click",

            // Classes of HTML elements to use
            mainImageClass: "picture-slides-image", // Mandatory
            imageLinkClass: "picture-slides-image-link",
            mainImageFailedToLoadClass: "picture-slides-image-error",
            fadeContainerClass: "picture-slides-fade-container",
            imageTextContainerClass: "picture-slides-image-text",
            previousLinkClass: "picture-slides-previous-image",
            nextLinkClass: "picture-slides-next-image",
            imageCounterClass: "picture-slides-image-counter",
            startSlideShowClass: "picture-slides-start-slideshow",
            stopSlideShowClass: "picture-slides-stop-slideshow",
            thumbnailContainerClass: "picture-slides-thumbnails",
            dimBackgroundOverlayClass: "picture-slides-dim-overlay"
        });
        jQuery.scrollTo('.picture-slides-fade-container');
    }



    StarsActivities();


    //---------------------------------------------------------------------------------------

    if ($('div.buttonsZav').length) {

        ShowCommentsCount();

        $('div.buttonsZav > div').click(function (event) {

            $('div.buttonsZav > div.active').removeClass('active');
            $(this).addClass('active');

            $('#objItems').find('div.show').removeClass('show').addClass('hide');
            $('#objItems').find('#' + this.id + '_item').removeClass('hide').addClass('show');


            if (this.id == 'today') {
                if (global_widjet_started_flag == 0) {
                    StartWidjet();
                    StarsActivities();
                    global_widjet_started_flag = 1;
                }
            }


            if (this.id == 'afisha') {
                var id = $('div.calendar10 > div.active').attr('id');
                var $div_to_show = $('#oAfisha').find('#' + id + '_item');
                $div_to_show.toggleClass('hide', false).toggleClass('show', true);
                $div_to_show.find("div.topbanner").html('<iframe scrolling="no" frameborder="0" marginheight="0" marginwidth="0" src="/CityObjectAfishaBanner.aspx"></iframe>');
                AfihaActivities();
            }


            if (this.id == 'review') {

                MakeReviewBlock();
                GetRateBanner();
            }
            //alert(nn);


            function GetRateBanner() {

                var $banner = $('#review_item > #banner');

                if ($banner.attr("loaded"))
                    return;

                $.ajax({
                    type: "POST",
                    data: "{pass:'~/Controls/Banner/MainPageContentBanner.xml'}",
                    url: "/CityDataService.asmx/ShowRateBanner",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function SetRateBanner(data) {

                        var result = data.d;

                        if (result.length > 0) {
                            $banner.attr("loaded", true);
                            $banner.html(result);
                        }
                    }
                });
            }
        });

        $('#objItems > div.show').toggleClass('hide', true).toggleClass('show', false);
        if (city_object_start_item != 'undefined' && city_object_start_item != null) {
            $('#objItems').find(city_object_start_item).removeClass('hide').addClass('show');
            $('div.buttonsZav').find(city_object_start_item.replace(/_item/, "")).addClass('active');
        }
    }

    //---------------------------------------------------------------------------------------

    if ($('#today_item').length && city_object_start_item != '#today_item') {

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "'}",
            url: "/CityDataService.asmx/GetObjectToDay",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                //alert('!');

                var html = obj.d;
                $('#today_item').html(html);

            },

            failure: function (error) { alert("Error !!!" + error); }

        });
    }

    //---------------------------------------------------------------------------------------

    if (false && $('#desc_item').length && city_object_start_item != '#desc_item') {

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "'}",
            url: "/CityDataService.asmx/GetObjectDesc",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                var html = obj.d;
                $('#desc_item').html(html);
                $('#desc_item img[src$=.png]').ifixpng();
            },

            failure: function (error) { alert("Error !!!" + error); }

        });
    }

    //---------------------------------------------------------------------------------------



    if ($('div.miniGallery').length && city_object_start_item != '#afisha_item') {

        $.ajax({
            type: "POST",
            data: "{}",
            url: "/CityDataService.asmx/GetMiniGallery",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                var html = obj.d;

                $('div.miniGallery').html(html);
                if (html.length > 0)
                    $('div.miniGallery').removeClass('hide');
                else
                    $('div.miniGallery').addClass('hide');

                //alert($('div.miniGallery').html());

                $('div.pics').serialScroll({
                    items: 'li',
                    prev: 'div.scroll a.right',
                    next: 'div.scroll a.left',
                    offset: 0, //when scrolling to photo, stop 230 before reaching it (from the left)
                    start: 0, //as we are centering it, start at the 2nd
                    duration: 1200,
                    force: true,
                    stop: true,
                    lock: false,
                    cycle: false, //don't pull back once you reach the end
                    easing: 'easeOutQuart', //use this easing equation for a funny effect
                    jump: false, //true //click on the images to scroll to them
                    onBefore: function (e, elem, $pane, $items, pos) {
                        /**
                        * 'this' is the triggered element 
                        * e is the event object
                        * elem is the element we'll be scrolling to
                        * $pane is the element being scrolled
                        * $items is the items collection at this moment
                        * pos is the position of elem in the collection
                        * if it returns false, the event will be ignored
			             
				         
                        */
                        //those arguments with a $ are jqueryfied, elem isn't.
                        e.preventDefault();
                        if (this.blur)
                            this.blur();

                        //alert(pos);

                        if (($items.length - pos) < 6)
                            return false;
                    }
                });

            },

            failure: function (error) { alert("Error !!!" + error); }

        });
    }

    //---------------------------------------------------------------------------------------

    if ($('div.calendar10').length) {
        calendar10Click();
    }

    if ($('div.calendar10').length && (typeof window.city_object_start_item != 'undefined' && city_object_start_item != '#afisha_item')) {

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "',block:'Calendar',server_call:false}",
            url: "/CityDataService.asmx/GetObjectAfisha",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                var html = obj.d;

                $('div.calendar10').html(html);
                if (html.length > 0)
                    $('div.calendar10').removeClass('hide');
                else
                    $('div.calendar10').addClass('hide');

                //alert($('div.calendar10').html());

                calendar10Click();
            },

            failure: function (error) { alert("Error !!!" + error); }

        });
    }

    function calendar10Click() {

        //alert('!');

        $('div.calendar10 > div.day').click(function (event) {

            $('div.calendar10 > div.active').removeClass('active');
            $(this).addClass('active');

            var $div_to_hide = $('#oAfisha').find('div.show');
            $div_to_hide.removeClass('show').addClass('hide');
            $div_to_hide.find("div.topbanner").html("");

            var $div_to_show = $('#oAfisha').find('#' + this.id + '_item');
            $div_to_show.removeClass('hide').addClass('show');
            //$div_to_show.find("div.topbanner").html('<iframe scrolling="no" frameborder="0" marginheight="0" marginwidth="0" src="/CityObjectAfishaBanner.aspx"></iframe>');

            event.preventDefault();
        });
    }
    //---------------------------------------------------------------------------------------
    if ($('#oAfisha').length && (typeof window.city_object_start_item != 'undefined' && city_object_start_item != '#afisha_item')) {
        AfihaActivities();
    }

    //---------------------------------------------------------------------------------------

    if ($('#review_list').length && $('#review_add').length) {

        if ($('#paginator1').length)
            Make_paginator1();
        if ($('#paginator2').length)
            Make_paginator2();
    }

    if ($('#review_add').length && $('#review_add').length) {

        ReviewBlockActivities();
    }

    if ($('#rate_block').length && city_object_start_item == '#review_item') {

        RateBlockActivities();
    }

    //---------------------------------------------------------------------------------------

    if ($('#alter_item').length && city_object_start_item != '#alter_item') {

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "'}",
            url: "/CityDataService.asmx/GetObjectAlter",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                var html = obj.d;
                $('#alter_item').html(html);

                $('div.altCategories').find('a.alt_cat').click(function (event) {

                    var $this = $(this);
                    $this.siblings().toggleClass('active', false);
                    $this.toggleClass('active', true);

                    $('#alter_item div.altList').toggleClass('hide', true);
                    var d_id = $(this).attr('id').replace(/alt_cat_/, "alt_div_");
                    $('#' + d_id).toggleClass('hide', false);

                    event.preventDefault();
                });

                $('div.altCategories a.alt_head').click(function (event) {
                    event.preventDefault();
                });


            },
            failure: function (error) { alert("Error !!!" + error); }
        });
    }

    //---------------------------------------------------------------------------------------
    // banner show
    $('iframe.framebanner').each(function () {
        var $this = $(this);
        var thisDOM = $this.get(0);
        var btext = $this.text();
        var doc;
        if (thisDOM.contentDocument) doc = thisDOM.contentDocument;
        else if (thisDOM.contentWindow) doc = thisDOM.contentWindow.document;
        else if (thisDOM.document) doc = thisDOM.document;
        if (doc != null) {

            if ($.browser.msie) {
                iframe.attr({ 'src': "_blank", "frameBorder": "0" });
                doc.write(btext);
                doc.close();
            }
            else
                doc.body.innerHTML = btext;

            var $body = $(doc.body);
            var head = null;
            if (doc.getElementsByTagName) head = doc.getElementsByTagName('head')[0];
            if (head != null) {
                $('link[rel="stylesheet"]').each(function () {
                    $(doc.createElement('link')).attr({ type: 'text/css', href: $(this).attr('href'), rel: 'stylesheet', media: 'screen' }).appendTo(head);
                });
            }

            var width = $this.width();
            var height = $this.height();

            if ($body.outerWidth() > width)
                width = $body.outerWidth();

            if ($body.outerHeight() > height)
                height = $body.outerHeight();

            if ($this.outerWidth() > width)
                width = $this.outerWidth();

            if ($this.outerHeight() > height)
                height = $this.outerHeight();

            if ($.browser.msie == false) {
                var h = $body.get(0).offsetHeight;
                var w = $body.get(0).offsetWidth;
                if (h > height) height = h + 5;
                if (w > width) width = w + 5;
            } else {
                var h = $body.get(0).scrollHeight;
                var w = $body.get(0).scrollWidth;
                if (h > height) height = h + 5;
                if (w > width) width = w + 5;
            }

            $this.css({ 'width': width, "height": height });
        }

    });

})

//---------------------------------------------------------------------------------------

function AfihaActivities() {
    $.ajax({
        type: "POST",
        data: "{url:'" + $("#hdnServiceUrl").attr("value") + "',block:'List',server_call:false}",
        url: "/CityDataService.asmx/GetObjectAfisha",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(obj) {

            var html = obj.d;

            $('#oAfisha').html(html);
            if (html.length > 0)
                $('#oAfisha').removeClass('hide');
            else
                $('#oAfisha').toggleClass('show', false).toggleClass('hide', true);

            //alert($('#oAfisha').html());
        },

        failure: function(error) { alert("Error !!!" + error); }

    });

}
function StarsActivities() {

    $('div.stars > div.e_star').click(function(event) {

        var key = $('#hdnCheckNumber').attr("value");
        if (key == '') return;

        var $this = $(this);
        var arr = $this.attr("id").replace(/e_str_/, "").split("_");    //id = \"{index(1,2,3,4,5)}_{objid}\

        if (arr.length != 2)
            return;

        var $parent = $this.parent();
        var parent_id = $parent.attr("id");

        $parent.toggleClass('midPicConfirm', true);

        $.ajax({
            type: "POST",
            data: "{key:'" + key + "',id:'" + arr[1] + "',val:'" + arr[0] + "'}",
            url: "/CityDataService.asmx/SaveEditorialRate",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(obj) {

                //alert(obj.d);

                var res = '' + obj.d;
                var val = 0;
                if (res.indexOf('|', 0) != -1) {
                    val = parseInt(res.substring(0, res.indexOf('|', 0)));
                    $('#hdnCheckNumber').val(res.substring(res.indexOf('|', 0) + 1));
                }
                else
                    val = parseInt(obj.d)

                if (val == 'undefined' || val == null || val == 0)
                    return;

                //alert(parent_id);

                var $arr = $('#' + parent_id).find('div.e_star');
                $arr.toggleClass('stard0', false).toggleClass('stard1', false);

                for (var i = 0; i < $arr.length; i++) {
                    if (i < val)
                        $arr.eq(i).toggleClass('star0', false).toggleClass('star1', true);
                    else
                        $arr.eq(i).toggleClass('star1', false).toggleClass('star0', true);
                }

                var str = "$('#" + parent_id + "').toggleClass('midPicConfirm', false)";

                setTimeout(str, 1000);
            },

            failure: function(error) { alert("Error !!!" + error); }
        });


    });

    $('div.stars > div.e_star').hover(function() {
        var $this = $(this);
        $this.prevAll('div.e_star').andSelf().toggleClass('stard0', false).toggleClass('stard1', true);
        $this.nextAll().toggleClass('stard1', false).toggleClass('stard0', true);
    },

                            function() { });

    $('div.stars').hover(function() { },

                            function() {
                                var $this = $(this);
                                $this.find('div.e_star').toggleClass('stard0', false).toggleClass('stard1', false);
                            });

}


function StartWidjet() {

    //alert('!!');
    

    if ($('.mainNewsContainer').length) {

        var $news = $('.mainNewsContainer');
        var $active = 0;

        $('li', $news).hover(function() { $news.trigger('stop'); });
        $('li div.second').hover(
        function() { $(this).find('div.itemBg').addClass('active'); },
        function() { $(this).find('div.itemBg').removeClass('active'); });


        if ($news.hasClass("stopanimation"))
            return;

        var $blist = $('td.buttons div.item');
        var $bcontainer = $('td.buttons');
        var items_width = 0;
        $.each($blist, function() { items_width += $(this).width(); });
        var rest_width = $bcontainer.width() - items_width;
        var pad = rest_width / $blist.length / 2;
        $.each($blist, function() {  $(this).css({"padding-left":pad,"padding-right":pad}) });
        
        $blist.click(function() { $news.trigger('stop') });
        $blist.eq($active).addClass('active');
        $news.serialScroll({
            items: 'li',
            duration: 400,
            force: true,
            axis: 'xy',
            prev: 'td.arrowleft',
            next: 'td.arrowright',
            interval: 6000,
            step: 1,
            navigation: 'div.buttonsInner div.item',
            onBefore: function(e, elem, $pane, $items, pos) {
                $blist.eq($active).removeClass('active');
                $blist.eq(pos).addClass('active');
                $active = pos;
            }
        });

    }
}


//---------------------------------------------------------------------------------------

function ShowCommentsCount() {
    $('#review h3 span').remove();
    var c = $('#rcount').val() || '0';
 
 
    $('#review h3').append('<span style="color: gray;font-size: 7pt;padding-left: 4px;"> (' + c + ')</span>')
}

function MakeReviewBlock() {

    if ($('#rate_block').length) {    // && city_object_start_item != '#review_item'

        //alert("!");

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "'}",
            url: "/CityDataService.asmx/GetObjectRateBlock",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (obj) {

                var html = obj.d;

                $('#rcount').remove();

                $('#rate_block').html(html);
                if (html.length > 0) {

                    $('#rate_block').removeClass('hide');

                    RateBlockActivities();
                }
                else
                    $('#rate_block').toggleClass('show', false).toggleClass('hide', true);

                //alert($('#rate_block').html());
            },

            failure: function (error) { alert("Error !!!" + error); }

        });

    }


    //---------------------------------------------------------------------------------------


    if ($('#review_list').length) {

        paginatorCommentsClick(1);
        ShowCommentsCount();
            
    }


    //---------------------------------------------------------------------------------------


    if ($('#review_add').length) {
      //  if (city_object_start_item != '#review_item') {

        $.ajax({
            type: "POST",
            data: "{}",
            url: "/CityDataService.asmx/GetObjectReviewAddBlock",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(obj) {

                var html = obj.d;
                $('#review_add').html(html);

                ReviewBlockActivities();
            },
            failure: function(error) { alert("Error !!!" + error); }
        });

        //}
    }

}

//----------------------------------------------------------------------------


function RateBlockActivities() {

    $('div.stars_active > div').hover(function() {

        var $this = $(this);
        var $parent = $this.parent();

        var text_box_id = $parent.attr('id').replace(/rItemBox_/, "rItemText_");
        var pos = $parent.find('div').index(this);
        var $txt_box = $("#" + text_box_id);

        $this.nextAll().toggleClass('round1', false).toggleClass('round0', true);
        $this.prevAll().andSelf().toggleClass('round0', false).toggleClass('round1', true);
        $txt_box.find("ul.rText > li").toggleClass('hide', true).eq(pos + 1).toggleClass('hide', false);
        $txt_box.parent().toggleClass('ratingAbsent', false).toggleClass('ratingPresent', true);
    },

                            function() { });

    $('div.stars_active').hover(function() { },

                            function() {
                                var $this = $(this);

                                var text_box_id = $this.attr('id').replace(/rItemBox_/, "rItemText_");
                                var $txt_box = $("#" + text_box_id);
                                var pos = $this.attr("selStar");

                                if (pos != "undefined" && pos >= 0) {
                                    pos = parseInt(pos);
                                    $this.find('div').toggleClass('round0', true).toggleClass('round1', false).eq(pos).prevAll().andSelf().toggleClass('round0', false).toggleClass('round1', true);

                                    $txt_box.find("ul.rText > li").toggleClass('hide', true).eq(pos + 1).toggleClass('hide', false);
                                    $txt_box.parent().toggleClass('ratingAbsent', false).toggleClass('ratingPresent', true);
                                }
                                else {
                                    $this.find('div').toggleClass('round1', false).toggleClass('round0', true);
                                    $txt_box.find("ul.rText > li").toggleClass('hide', true).eq(0).toggleClass('hide', false);
                                    $txt_box.parent().toggleClass('ratingPresent', false).toggleClass('ratingAbsent', true);
                                }
                            });


    $('div.stars_active > div').click(function(event) {
        var $this = $(this);
        var $parent = $this.parent();

        var pos = $parent.find('div').index(this);
        $parent.attr("selStar", pos);

        var text_box_id = $parent.attr('id').replace(/rItemBox_/, "rItemText_");
        var val_box_id = text_box_id.replace(/rItemText_/, "rItemID_");

        var val_txt = $("#" + text_box_id + " > ul.rID > li").eq(pos + 1).text();
        $("#" + val_box_id).val(val_txt);

    });

    $('#btnRateSend').click(function(event) {

        if ($(this).attr("added") == "yes") {
            return;
        }

        var key = $('#hdnCheckNumber').attr("value");
        if (key == '') return;

        var str_id = "";
        var str_val = "";

        $('td.ratingPresent > input:hidden').each(function(i) {
            str_id = str_id + this.id.replace(/rItemID_/, "") + ";";
            str_val = str_val + this.value + ";";
        });

        //alert(str_id);
        //alert(str_val);

        $.ajax({
            type: "POST",
            data: "{url:'" + $("#hdnServiceUrl").attr("value") + "',key:'" + key + "',ids:'" + str_id + "',vals:'" + str_val + "'}",
            url: "/CityDataService.asmx/SaveObjectRate",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(obj) {

                var result = obj.d;

                if (result.length > 0) {
                    $('#btnRateSend').attr("added", result);
                    $('#RateThankYou').html(result);
                    var top1 = $('#btnRateSend').attr("top");
                   // $.scrollTo('#review_add', 2000);
                }
            }

        });
        event.preventDefault();
    });
}


//---------------------------------------------------------------------------------------

function ReviewBlockActivities() {
    
    var $btn = $('#btnReviewAdd');

    if ($btn.length) {
        $btn.click(function (event) {

            var key = $('#hdnCheckNumber').attr("value");
            var name = $('#txtReviewName').attr("value");
            var email = $('#txtReviewEmail').attr("value");
            var body = $('#txtReviewBody').attr("value");
            var bsend = $('#chkSendReviewMail').attr("checked");

            if (key == '' || body == '') {
                $('#ReviewErr').toggleClass('hide', false);
                return;
            }
            if (email != '' && !validateEmail(email)) {
                var msg = jQuery('#emailerrmessage').val() || '';
                if (msg != null && msg.length > 0)
                    alert(msg);
                //$('#ReviewErr').toggleClass('hide', false);
                return;
            }

            if (body.lenghth > 1000)
                body = body.substring(0, 999);

            /* if (!validateTxtField(body) || !validateTxtField(name) || !validateTxtField(email)) {
            $('#ReviewErr').toggleClass('hide', false);
            return;
            }*/


            $('#ReviewErr').toggleClass('hide', true);

            $.cookieValue('rate_cookie', 'usr_name', name, '{ expires: 365 }');
            $.cookieValue('rate_cookie', 'usr_email', email, '{ expires: 365 }');

            var postdata = {};
            postdata['url'] = $("#hdnServiceUrl").attr("value");
            postdata['key'] = key;
            postdata['name'] = name;
            postdata['email'] = email;
            postdata['body'] = body;
            postdata['bsend'] = bsend;
            var json = JSON.serialize(postdata);

            $.ajax({
                type: "POST",
                data: json,
                url: "/CityDataService.asmx/AddReview",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (obj) {


                    var res = '' + obj.d;
                    var val = 0;
                    if (res.indexOf('|', 0) != -1) {
                        html = res.substring(0, res.indexOf('|', 0));
                        $('#hdnCheckNumber').val(res.substring(res.indexOf('|', 0) + 1));
                    }
                    else
                        html = obj.d

                    if (html == '1') {
                        $('#txtReviewBody').attr("value", "");
                        paginatorCommentsClick(1);

                        //$.scrollTo('#rate_block', 2000);
                    }
                },
                failure: function (error) { alert("Error !!!" + error); }
            });

        });

    }
}

//---------------------------------------------------------------------------------------

function paginatorCommentsClick(pageNum) {

    $.ajax({
        type: "POST",
        data: "{url:'" + $('#hdnServiceUrl').val() + "',currPage:" + pageNum + ",serverCall:false}",
        url: "/CityDataService.asmx/ShowReviewList",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (obj) {

            var html = obj.d;

            if (html.length > 0) {
                $('div.comments').html(html);
                if ($('#review_item').hasClass("show")) {

                    if ($('#paginator1').length)
                        Make_paginator1();
                    if ($('#paginator2').length)
                        Make_paginator2();
                    ShowCommentsCount();
                }
                //alert('!');
            }
        }
    });

    if (window.event != null)
        window.event.returnValue = false;
}

//---------------------------------------------------------------------------------------

function validateTxtField(pobjWhat)
{
var invalidChars = '\>\<\\\{\}^';

    for (i = 0; i < invalidChars.length; i++) {
        if (pobjWhat.indexOf(invalidChars.charAt(i), 0) > -1) {
            //alert('text contains invalid characters');
            return false;
        }
    }
    return true;
}

function validateEmail(pobjWhat)
{
    var blnEmailErrorAlreadyCreated = false;

    pobjWhat = pobjWhat.toLowerCase();
    addr = pobjWhat;

    if (addr.length == 0) { return false; }

    var invalidChars = '\/\'\>\<\\ ";:?!()[]\{\}^|';

    for (i = 0; i < invalidChars.length; i++) {
        if (addr.indexOf(invalidChars.charAt(i), 0) > -1) {
            //alert('email address contains invalid characters');
            return false;
        }
    }

    for (i = 0; i < addr.length; i++) {
        if (addr.charCodeAt(i) > 127) {
            //alert("email address contains invalid characters.");
            return false;
        }
    }

    var atPos = addr.indexOf('@', 0);

    if (atPos == -1) {
        //alert('email address must contain an @');
        return false;
    }

    if (atPos == 0) {
        //alert('email address must not start with @');
        return false;
    }

    if (addr.indexOf('@', atPos + 1) > -1) {
        //alert('email address must contain only one @');
        return false;
    }

    if (addr.indexOf('.', atPos) == -1) {
        //alert('email address must contain a dot in the domain name');
        return false;
    }

    if (addr.indexOf('@.', 0) != -1) {
        //alert('dot must not immediately follow @ in email address');
        return false;
    }

    if (addr.indexOf('.@', 0) != -1) {
        //alert('dot must not immediately precede @ in email address');
        return false;
    }

    if (addr.indexOf('..', 0) != -1) {
        //alert('two dots must not be adjacent in email address');
        return false;
    }

    var suffix = addr.substring(addr.lastIndexOf('.') + 1);

    if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
        //alert('invalid primary domain in email address');
        return false;
    }

    pobjWhat.value = addr;
    return true;
}
