function SlideKeyNav (event)
{
    var link = false;
    switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
    {
        case 0x25:
            link = 'prev';
            break;
        case 0x27:
            link = 'next';
            break;
    }
    if((link=='prev')&&($('.prev-slide a').css("display")!="none"))
    {
        var post_id = $('.slide-content').attr('id');
        var slide_id = $('.prev-slide a').attr('id');
        var link = $('.prev-slide a');

        prevSlide(post_id, slide_id, link);
    }
    if((link=='next')&&($('.next-slide a').css("display")!="none"))
    {
        var post_id = $('.slide-content').attr('id');
        var slide_id = $('.next-slide a').attr('id');
        var link = $('.next-slide a');
        
        nextSlide(post_id, slide_id, link);
    }
}

$(document).ready(function()
{        
    $(window).scroll(function ()
    {
        var scroll = window.pageYOffset;
        if ($('.single_title_link').offset())
        {
            var manage = $('.single_title_link').offset().top;
            var manage_offset = 20;

            if (scroll > manage - manage_offset)
            {
                $('.single-post-manage').css({'top':'20px', 'position':'fixed'});
            }
            else
            {
                $('.single-post-manage').css({'top':'auto', 'position':'static'});
            }
        }
            
    });
    if($(".slide-content").length>0)
    {
        $(document).bind("keydown", SlideKeyNav);
    }
    $('.next-slide a').click(function ()
    {
        var post_id = $('.slide-content').attr('id');
        var slide_id = $(this).attr('id');
        var link = $(this);
        
        nextSlide(post_id, slide_id, link);
        return false;
    });


    var slide_number = parseInt($('.active-slide').attr('jcarouselindex'));
    var total_slides = parseInt($('.slide-title b').html());    

    $('.prev-slide a').click(function ()
    {
        var post_id = $('.slide-content').attr('id');
        var slide_id = $('.prev-slide a').attr('id');
        var link = $('.prev-slide a');
        
        prevSlide(post_id, slide_id, link);     
        return false;
    });
    if($("#rightAdvertisementTagWidget2 div").length<=2)
    {
        $("#rightAdvertisementTagWidget2").parent().remove();
    }
    if($("#rightAdvertisementTagWidget div").length<1)
    {
        $("#rightAdvertisementTagWidget").parent().parent().remove();
    }
    if ($('.slide-title').html())
    {
        $('.slide-thumb-link').click(function ()
        {
            $('.imageLoaderBg').show();
            $('.imageLoader').show();

            reloadAdvertisement();
            postCounter('post');

            var post_id = $('.slide-content').attr('id');
            var slide_id = $(this).attr('id');

            reloadWPandGAStats(post_id);

            var link = $(this);
            $.ajax({
                    url: '/ajax_slideshow_content.php',
                    dataType: "json",
                    type: 'POST',
                    data: {'post_id':post_id,'slide_id':slide_id},
                    success:function(res)
                    {
                        if (res.key) key = res.key;
                        postCounter('post');

                        $('.active-slide').removeClass('active-slide');
                        $('#slide-' + slide_id).addClass('active-slide');
                        var slide_number = parseInt($(link).parent().attr('jcarouselindex'));
                        var total_slides = parseInt($('.slide-title b').html());
                        if (slide_number < total_slides ) $('.next-slide a').show();
                        else $('.next-slide a').hide();
                        if (slide_number > 1) $('.prev-slide a').show();
                        else $('.prev-slide a').hide();
                        $('#slide-number').html(slide_number);
                        if (res.prev_id)
                        {
                            var new_href = $('.prev-slide a').attr('href').replace(/slide=\d+$/, 'slide=' + res.prev_id);
                            $('.prev-slide a').attr({'id':res.prev_id, 'href':new_href});
                        }
                        else $('.prev-slide a').hide();

                        if (res.next_id)
                        {
                            var new_href = $('.next-slide a').attr('href').replace(/slide=\d+$/, 'slide=' + res.next_id);
                            $('.next-slide a').attr({'id':res.next_id, 'href':new_href});
                        }
                        else $('.next-slide a').hide();

                        $('.slide-content').html(res.slide_content + '<div class="imageLoaderBg"></div><div class="imageLoader"></div>');

                        $('.imageLoaderBg').hide();
                        $('.imageLoader').hide();
                        var slide_number = parseInt($('.active-slide').attr('jcarouselindex'));
                        var total_slides = parseInt($('.slide-title b').html());                        

                        var post_url = $('#post_url').html();
                        var histAPI = !!(window.history && history.pushState);
                        if (histAPI) history.pushState(null, null, post_url+"&slide="+slide_id);
                    }
            });
            return false;
        });
    }
    
	$('.more_link').click(function ()
	{
		var result = displayArchives($(this).html());
		$('.more_link').html(result);
		return false;
	});

	$('.mainmenu-item').hover(
		function ()
		{
			$(this).find('ul.submenu').show();
			$(this).attr('class', 'mainmenu-item-current');
		},
		function ()
		{
			$(this).find('ul.submenu').hide();
			$(this).attr('class', 'mainmenu-item');
		});        
        $('.mainmenu-item-current').hover(
		function ()
		{
			$(this).find('ul.submenu').show();
		},
		function ()
		{
			$(this).find('ul.submenu').hide();
		}); 

    $('#expand-block').click(function ()
    {
        $('.collapse-block').show();
        $('#expand-block').parent().hide();
        $('.advBottom').css('margin-top', '330px');
        return false;
    });

    $('.ae-collapse a').click(function ()
    {
        $('.collapse-block').hide();
        $('#expand-block').parent().show();
        $('.advBottom').css('margin-top', '30px');
        return false;
    });
});

function InputHelperCreate(id, text, cColor) {
    function addEvents(obj) {
        obj.bind('focus', function() {
                InputHelperIn(id, text);
            })
           .bind('blur', function() {
                InputHelperOut(id, text, cColor);
           });
    }

    function switchInput(obj, type, callback){
        if(obj.attr('inpType') == 'password') {
            var ob = $('<input>');
            ob.attr('id', obj.attr('id'));
            ob.attr('class', obj.attr('class'));
            ob.attr('name', obj.attr('name'));
            ob.attr('style', obj.attr('style'));
            ob.attr('inpType', obj.attr('inpType'));
            switch(type){
                case 'password':
                       ob.attr('type', 'password');
                    break;
                case 'text':
                       ob.attr('type', 'text');
                    break;
            }
            obj.parent().append(ob);
            obj.remove();
            obj = ob;
            if(typeof(callback) == 'function'){
                callback(obj);
            }
            addEvents(obj);
        }
        return obj;
    }

    function InputHelperIn(id, text, noClean) {
        var obj = $(id);
        if (obj.val() == text || noClean) {
            obj = switchInput(obj, 'password', function(el){el.focus();});
            obj.css({color: '#000000', fontStyle: 'normal', backgroundColor: '#FFFFCC'});
            if (!noClean) {
                obj.val('');
            }
        }
    }

    function InputHelperOut(id, text, cColor) {
        var obj = $(id);
        if (obj.val() == '' || obj.val() == text) {
            obj = switchInput(obj, 'text');
            obj.css({color: cColor ? cColor : '#b3b3b3', fontStyle: 'normal', backgroundColor: '#FFFFFF'})
               .val(text);
        }
    }

    function InputHelperClear(id, text) {
        var obj = $(id);
        if(obj.val() == text) {
            obj.val('');
        }
    }

    var obj = $(id);
    obj.attr('inpType', obj.attr('type'));
    obj.parents('form:first').submit(function () {
                                        InputHelperClear(id, text)
                                     });
    addEvents(obj);
    if (obj.val() == '' || obj.val() == text) {
        InputHelperOut(obj, text, cColor);
    }
    else {
        InputHelperIn(obj, text, true);
    }
}

function OverCommentHelperCreate() {
    function OverCommentHelperIn(e) {
        var obj = $(e);
        if(obj.children('img').length > 0){
            obj.siblings('a').css({color: "#6688FF"});
            obj.children('img').css({border: '1px solid #333333'})
        }
        else {
            obj.css({color: "#6688FF"});
            obj.siblings('a').children('img').css({border: '1px solid #333333'})
        }
    }

    function OverCommentHelperOut(e) {
        var obj = $(e);
        if(obj.children('img').length > 0) {
            obj.siblings('a').css({color: "#0000FF"});
            obj.children('img').css({border: '1px solid #D7D7D7'})
        }
        else {
            obj.css({color: "#0000FF"});
            obj.siblings('a').children('img').css({border: '1px solid #D7D7D7'});
        }
    }
    var obj = $('.over_comment');
    obj.each(function(i, e) {
            $(e).bind('mouseenter', function() {
                OverCommentHelperIn(e);
            })
            $(e).bind('mouseleave', function() {
                OverCommentHelperOut(e);
        });
    });
}

$(document).ready(function() {
    $('<img>').attr('src', '/wp-content/themes/2009GofG/label/teaser-c-over.png');
    InputHelperCreate("#e-sub-text", "Enter email address");
    InputHelperCreate("#keyword", "Find people in photos");
    InputHelperCreate("#people_keyword", "Find people in photos");
    InputHelperCreate("#right_keyword", "Find people in photos");
    InputHelperCreate("#calendar_keyword", "Find calendar events");
    InputHelperCreate("#calendar_keyword1", "Find calendar events");
    InputHelperCreate("#venues_keyword", "Search By Name");
    InputHelperCreate("#single-venues_keyword", "Find a place");
    InputHelperCreate("#t-box-text", "Anonymous...");
    InputHelperCreate("#t-box-input", "Type word here...");
    InputHelperCreate("#Description", "Please avoid all CAPS", "#7C7C7C");
    InputHelperCreate("#commentTextArea", "Anonymous...please be nice (or it won\'t be accepted!)");
    InputHelperCreate("#signupEmail", "Enter your mail address here....");
    InputHelperCreate("#signupEmail", "Enter Your Email");
    InputHelperCreate("#email", "Email");
    InputHelperCreate("#cpassword", "Password");
    InputHelperCreate("#invite_friends", "friend1@example.com\nfriend2@example.com\nfriend3@example.com");
    OverCommentHelperCreate();
    $("div.creply").hover(
      function () {
        $(this).addClass('creply-over');
        $(this).find('.ireply').addClass('ireply-over');
      },
      function () {
        $(this).removeClass('creply-over')
        $(this).find('.ireply').removeClass('ireply-over');
      }
    );
    $("#slides").easySlider({
            auto: true,
            continuous: true,
            point_navigation: false,
            numeric: true,
            numeric_nav_arrow: true,
            point_nav_arrows: true,
            nextText: '',
            prevText: '',
            /*additional_nav_id: 'story_slide_nav',*/
            speed: 1000,
            pause: 7000/*,
            hoverPause: true/*,
            links_to_first: '#slides li div.story .header a'*/
    });
    $(".top_parties, .bottom_parties").each(function(){
        var ln_parties_id = $(this).attr("id");
        $(this).parent().attr("id","holder"+ln_parties_id);
        $("#"+ln_parties_id).easySlider({
            auto: true,
            continuous: true,
            //point_navigation: true,
            //point_nav_arrows: false,
            //additional_nav_id: 'story_slide_nav',
            pause: 5000,
            controlsShow: false,
            width: true,
            hoverPause: true,
            links_to_first: '#holder'+ln_parties_id+' .top_parties ul li a'
        });
    })
    
});
function vvq_youtube(objectID, videoWidth, videoHeight, videoID) {
	swfobject.embedSWF("http://www.youtube.com/v/" + videoID, objectID, videoWidth, videoHeight, "9.0.0", "", "", {wmode:"transparent"});
}
function vvq_googlevideo(objectID, videoWidth, videoHeight, videoID) {
	swfobject.embedSWF("http://video.google.com/googleplayer.swf?docId=" + videoID, objectID, videoWidth, videoHeight, "9.0.0", "", "", {wmode:"transparent"});
}

// Stage6 is dead. This is only here for backwards compatibility.
function vvq_stage6(objectID, videoWidth, videoHeight, videoID) {
	return false;
}

function vvq_ifilm(objectID, videoWidth, videoHeight, videoID) {
	swfobject.embedSWF("http://www.ifilm.com/efp", objectID, videoWidth, videoHeight, "9.0.0", "", {flvbaseclip:videoID}, {wmode:"transparent"});
}

function vvq_metacafe(objectID, videoWidth, videoHeight, videoID, videoName) {
	swfobject.embedSWF("http://www.metacafe.com/fplayer/" + videoID + "/" + videoName + ".swf", objectID, videoWidth, videoHeight, "9.0.0", "", {playerVars:"playerVars",showStats:"yes",autoPlay:"no"}, {wmode:"transparent"});
}

function vvq_myspace(objectID, videoWidth, videoHeight, videoID) {
	swfobject.embedSWF("http://lads.myspace.com/videos/vplayer.swf", objectID, videoWidth, videoHeight, "9.0.0", "", {m:videoID,type:"video"}, {wmode:"transparent"});
}

function vvq_vimeo(objectID, videoWidth, videoHeight, videoID) {
	swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf?clip_id=" + videoID + "&server=vimeo.com&fullscreen=1&show_title=1&show_byline=1&show_portrait=0&color=01AAEA", objectID, videoWidth, videoHeight, "9.0.0", "", {allowfullscreen:"true",scale:"showAll"}, {wmode:"transparent"});
}

function vvq_flv(objectID, videoWidth, videoHeight, SWFURL, FLVFileURL, PreviewImageURL) {
	swfobject.embedSWF(SWFURL, objectID, videoWidth, videoHeight, "9.0.0", "", {file:FLVFileURL,usefullscreen:"false",image:PreviewImageURL}, {wmode:"transparent",allowFullScreen:"true"});
}

// Get around Internet Explorer's retarded click-to-activate thing by writing the HTML via Javascript
function vvq_quicktime(objectID, videoWidth, videoHeight, videoURL) {
	document.getElementById(objectID).innerHTML = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="' + videoWidth + '" height="' + videoHeight + '"><param name="src" value="' + videoURL + '" /><param name="controller" value="true" /><param name="autoplay" value="false" /><param name="wmode" value="transparent" /><object type="video/quicktime" data="' + videoURL + '" width="' + videoWidth + '" height="' + videoHeight + '" class="mov"><param name="controller" value="true" /><param name="autoplay" value="false" /><p><a href="' + videoURL + '">' + videoURL + '</a></p></object></object>';
}

function vvq_videoWMP(objectID, videoWidth, videoHeight, videoURL) {
	document.getElementById(objectID).innerHTML = '<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject" width="' + videoWidth + '" height="' + videoHeight + '"><param name="url" value="' + videoURL + '" /><param name="allowchangedisplaysize" value="true" /><param name="autosize" value="true" /><param name="displaysize" value="1" /><param name="showcontrols" value="true" /><param name="showstatusbar" value="true" /><param name="autorewind" value="true" /><param name="autostart" value="false" /><param name="volume" value="100" /></object>';
}

function vvq_videoNoWMP(objectID, videoWidth, videoHeight, videoURL, mimeType) {
	document.getElementById(objectID).innerHTML = '<object type="' + mimeType + '" data="' + videoURL + '" width="' + videoWidth + '" height="' + videoHeight + '" class="vvqbox vvqvideo"><param name="src" value="' + videoURL + '" /><param name="allowchangedisplaysize" value="true" /><param name="autosize" value="true" /><param name="displaysize" value="1" /><param name="showcontrols" value="true" /><param name="showstatusbar" value="true" /><param name="autorewind" value="true" /><param name="autostart" value="false" /><param name="autoplay" value="false" /><param name="volume" value="100" /></object>';
}


/*	SWFObject v2.0 rc4 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var X="undefined",P="object",a="visibility:visible",e="visibility:hidden",B="Shockwave Flash",h="ShockwaveFlash.ShockwaveFlash",V="application/x-shockwave-flash",K="SWFObjectExprInst",G=window,g=document,N=navigator,f=[],H=[],Q=null,L=null,S=false,C=false;var Y=function(){var l=typeof g.getElementById!=X&&typeof g.getElementsByTagName!=X&&typeof g.createElement!=X&&typeof g.appendChild!=X&&typeof g.replaceChild!=X&&typeof g.removeChild!=X&&typeof g.cloneNode!=X,t=[0,0,0],n=null;if(typeof N.plugins!=X&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=X){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var d=function(){if(!Y.w3cdom){return}J(I);if(Y.ie&&Y.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=b("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);U()}}}}catch(j){}}if(Y.webkit&&typeof g.readyState!=X){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){U()}},10)}if(typeof g.addEventListener!=X){g.addEventListener("DOMContentLoaded",U,null)}M(U)}();function U(){if(S){return}if(Y.ie&&Y.win){var m=W("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return}}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=X){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=X){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=X){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(Y.pv[0]>0){var k=b(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(Y.webkit&&Y.webkit<312){T(k)}}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(Y.win||Y.mac)){D(H[j])}else{c(k)}}}}A("#"+m,a)}}function T(m){var k=m.getElementsByTagName(P)[0];if(k){var p=W("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(Y.ie&&Y.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=b(i);for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)})}}function D(j){C=true;var o=b(j.id);if(o){if(j.altContentId){var l=b(j.altContentId);if(l){L=l}}else{L=Z(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=Y.ie&&Y.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(Y.ie&&Y.win&&o.readyState!=4){var i=W("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function c(j){if(Y.ie&&Y.win&&j.readyState!=4){var i=W("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(Z(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(Z(j),j)}}function Z(n){var m=W("div");if(Y.win&&Y.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=b(q);if(typeof AE.id==X){AE.id=q}if(Y.ie&&Y.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=b(AE.id)}else{if(Y.webkit&&Y.webkit<312){var AA=W("embed");AA.setAttribute("type",V);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=W(P);s.setAttribute("type",V);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=W("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function b(i){return g.getElementById(i)}function W(i){return g.createElement(i)}function O(k){var j=Y.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(Y.ie&&Y.mac){return}var l=g.getElementsByTagName("head")[0],k=W("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(Y.ie&&Y.win)&&typeof g.createTextNode!=X){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(Y.ie&&Y.win&&typeof g.styleSheets!=X&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}return{registerObject:function(l,i,k){if(!Y.w3cdom||!l||!i){return}var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;A("#"+l,e)},getObjectById:function(l){var i=null;if(Y.w3cdom&&S){var j=b(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=X)){i=j}else{if(typeof k.SetVariable!=X){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!Y.w3cdom||!n||!u||!r||!t||!j){return}r+="";t+="";if(O(j)){A("#"+u,e);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=X){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);A("#"+u,a)})}else{if(m&&!C&&O("6.0.65")&&(Y.win||Y.mac)){A("#"+u,e);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i);A("#"+u,a)})}}},getFlashPlayerVersion:function(){return{major:Y.pv[0],minor:Y.pv[1],release:Y.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(Y.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(Y.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=b(K);if(i){i.parentNode.replaceChild(L,i);L=null;C=false}}}}}();
function fade_bookmark_buttons_in(div_id)
{
	// assign a default id if necessary
	// flag the form as active
	document.getElementById(div_id).isActive = true;

	// only consider the latest in a multi-mouse over/out scenario
	document.getElementById(div_id).activeCall = bookmark_buttons_next_hash();

	// set show admin bar timeout
	var timeout_handler = 'show_bookmark_buttons(\'' + div_id + '\', \'' + document.getElementById(div_id).activeCall + '\');';
	setTimeout(timeout_handler, 50);
} // fade_bookmark_buttons_in()


function fade_bookmark_buttons_out(div_id)
{
	// flag the form as inactive
	document.getElementById(div_id).isActive = false;

	// only consider the latest in a multi-mouse over/out scenario
	document.getElementById(div_id).activeCall = bookmark_buttons_next_hash();

	// set hide admin bar timeout
	var timeout_handler = 'hide_bookmark_buttons(\'' + div_id + '\', \'' + document.getElementById(div_id).activeCall + '\');';
	setTimeout(timeout_handler, 300);
} // end fade_bookmark_buttons_out()


function show_bookmark_buttons(div_id, div_id_call)
{
	// if we're on the active form
	if ( document.getElementById(div_id).isActive )
	{
		document.getElementById(div_id).style.display = 'block';
	}
} // end show_bookmark_buttons()


function hide_bookmark_buttons(div_id, div_id_call)
{
	// if we're no longer on the active form
	if ( !document.getElementById(div_id).isActive
		&& ( document.getElementById(div_id).activeCall == div_id_call )
		)
	{
		document.getElementById(div_id).style.display = 'none';
	}
} // end hide_bookmark_buttons()


function bookmark_buttons_next_hash()
{
	var new_hash = '';
	var digits = '0123456789abcdef';

	while ( new_hash.length < 32 )
	{
		start = Math.floor(Math.random() * digits.length);
		end = start + 1;
		new_hash += digits.substring(start, end);
	}

	return new_hash;
} // end bookmark_buttons_next_hash()var ap_instances = new Array();

function ap_stopAll(playerID) {
	for(var i = 0;i<ap_instances.length;i++) {
		try {
			if(ap_instances[i] != playerID) document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 1);
			else document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 0);
		} catch( errorObject ) {
			// stop any errors
		}
	}
}

function ap_registerPlayers() {
	var objectID;
	var objectTags = document.getElementsByTagName("object");
	for(var i=0;i<objectTags.length;i++) {
		objectID = objectTags[i].id;
		if(objectID.indexOf("audioplayer") == 0) {
			ap_instances[i] = objectID.substring(11, objectID.length);
		}
	}
}

//var ap_clearID = setInterval( ap_registerPlayers, 100 );eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h 3=Z 11(12);h 6=0;h c="";h b=0;h 5=8;h n=(7.O&&7.9);h o=(!7.O&&7.9);h p=(13.14.15("16")>-1);h d=q;f 17(a){2(!d){d=r;6=a;s=7.9(\'P\'+6);k=18("s.Q"+6);c="";2(7.9(\'R\'+6)){l=S(7.9(\'R\'+6).y)}4{l=0}t=0;2(k.z!=19){T(i=0;i<k.z;i++){2(k[i].1a){2(l>0){c=k[i].y+","+c;t++}4{c=S(k[i].y)}}}}4{c=k.y}2(l>0){2(t>0&&t<=l){c=c.1b(0,(c.z-1));u();A()}4 2(t==0){d=q;m(U)}4{d=q;m(1c+" "+l+".")}}4{2(c>0){u();A()}4{d=q;m(U)}}}4{m(G)}}f 1d(a){2(!d){d=r;6=a;u();H()}4{m(G)}}f 1e(a){2(!d){d=r;6=a;u();I()}4{m(G)}}f v(){2(b==1f){w()}2(b<8){b+=10;2(p){b=8;w()}4 2(n){2(j){7.9(\'3-\'+6+\'-e\').g.B=\'C(D=\'+b+\')\'}4{b=8;w()}}4 2(o){2(j){7.9(\'3-\'+6+\'-e\').g.E=(b/8)}4{b=8;w()}}F("v()",8)}4{b=8;d=q}}f u(){2(V){7.9(\'3-\'+6+\'-W\').g.X=\'1g\'}}f w(){2(V){7.9(\'3-\'+6+\'-W\').g.X=\'1h\'}}f A(){2(5>0){5-=10;2(p){5=0}4 2(n){2(j){7.9(\'3-\'+6+\'-e\').g.B=\'C(D=\'+5+\')\'}4{5=0}}4 2(o){2(j){7.9(\'3-\'+6+\'-e\').g.E=(5/8)}4{5=0}}F("A()",8)}4{5=0;3.J();3.x("1i",r);3.x("6",6);3.x("Q"+6,c);3.K=\'1j\';3.L=\'3-\'+6+\'-e\';3.M=v;3.N();b=0;5=8}}f H(){2(5>0){5-=10;2(p){5=0}4 2(n){2(j){7.9(\'3-\'+6+\'-e\').g.B=\'C(D=\'+5+\')\'}4{5=0}}4 2(o){2(j){7.9(\'3-\'+6+\'-e\').g.E=(5/8)}4{5=0}}F("H()",8)}4{5=0;3.J();3.x("1k",6);3.K=\'Y\';3.L=\'3-\'+6+\'-e\';3.M=v;3.N();b=0;5=8}}f I(){2(5>0){5-=10;2(p){5=0}4 2(n){2(j){7.9(\'3-\'+6+\'-e\').g.B=\'C(D=\'+5+\')\'}4{5=0}}4 2(o){2(j){7.9(\'3-\'+6+\'-e\').g.E=(5/8)}4{5=0}}F("I()",8)}4{5=0;3.J();3.x("1l",6);3.K=\'Y\';3.L=\'3-\'+6+\'-e\';3.M=v;3.N();b=0;5=8}}f 1m(a){s=7.9(\'P\'+a);T(i=0;i<s.z;i++){s[i].1n=r}}',62,86,'||if|polls|else|poll_fadeout_opacity|poll_id|document|100|getElementById||poll_fadein_opacity|poll_answer_id|is_being_voted|ans|function|style|var||poll_show_fading|poll_answer|poll_multiple_ans|alert|is_ie|is_moz|is_opera|false|true|poll_form|poll_multiple_ans_count|poll_loading_text|poll_fadein_text|poll_unloading_text|setVar|value|length|poll_process|filter|alpha|opacity|MozOpacity|setTimeout|polls_text_wait|poll_process_result|poll_process_booth|reset|method|element|onCompletion|runAJAX|all|polls_form_|poll_|poll_multiple_ans_|parseInt|for|polls_text_valid|poll_show_loading|loading|display|GET|new||sack|polls_ajax_url|navigator|userAgent|indexOf|Opera|poll_vote|eval|null|checked|substring|polls_text_multiple|poll_result|poll_booth|90|block|none|vote|POST|pollresult|pollbooth|poll_disable_voting|disabled'.split('|'),0,{}));

loginPopUp = (function(){
    
    var self = this;
    self.inited = false;
    self.holder = null;
    self.background = null;
    self.init = function(){
        
        self.background = $('<div></div>').addClass('login-popup-bg').hide();
        self.contentholder = $('<div></div>').addClass('login-popup-content-holder').hide();
        self.contentholder.html("<table class=\"popup-content-table\"><tr><td valign=\"middle\" align=\"center\"><div class=\"login-popup-content\"></div></td></tr></table>");
        self.holder = self.contentholder.find(".login-popup-content");
        self.root = $('<div></div>');        
        $('body').css("position","absolute")
                .css("height","100%")
                .css("width","100%")
                .css("z-index","100000")
                .prepend(self.background)
                .append(self.contentholder);
        self.root.hide();
        self.inited = true;
    };
    self.collectPostData = function(action){
        var res = {};
        switch(action){
            case "reentermail":
                res.isInvalidEmail = self.holder.find("#isInvalidEmail").val();
                res.signupEmail = self.holder.find("#signupEmail").val();
                break;
            case "signupstep2":
                res.signupEmail = $("#signupEmail").val();
                res.inviteid = $("#inviteid").val();
                res.signupLANewsletter = $("#signupLANewsletter").attr("checked")?1:0;
                res.signupNYNewsletter = $("#signupNYNewsletter").attr("checked")?1:0;
                res.signupHmNewsletter = $("#signupHmNewsletter").attr("checked")?1:0;
                res.signupWSNewsletter = $("#signupWSNewsletter").attr("checked")?1:0;
                res.signupEverywhereNewsletter = $("#signupEverywhereNewsletter").attr("checked")?1:0;
                res.signupMiamiNewsletter = $("#signupMiamiNewsletter").attr("checked")?1:0;
                res.signupChicagoNewsletter = $("#signupChicagoNewsletter").attr("checked")?1:0;
                res.signupLondonNewsletter = $("#signupLondonNewsletter").attr("checked")?1:0;
                res.signupAustinNewsletter = $("#signupAustinNewsletter").attr("checked")?1:0;
                res.signupSanfrNewsletter = $("#signupSanfrNewsletter").attr("checked")?1:0;
                res.signupBostonNewsletter = $("#signupBostonNewsletter").attr("checked")?1:0;
                break;
            case "topsignup":
                res.signupEmail = $("#e-sub-text").val();
                break;
            case "submit":
                res.fName = self.holder.find("#fName").val();
                res.lName = self.holder.find("#lName").val();
                res.income = self.holder.find("[name=income]").val();
                res.gender = self.holder.find("[name=gender]").val();
                res.age = self.holder.find("[name=age]").val();
                res.iLiveIn = self.holder.find("[name=iLiveIn]").val();
                res.zip = self.holder.find("[name=zip]").val();
            case "skip":
                res.inviteid = self.holder.find("#invId").val();
                res.hiddenSignupEmail = self.holder.find("#signupEmail").val();
                res.signupLANewsletter = self.holder.find("#signupLANewsletter").attr("checked")?1:0;
                res.signupNYNewsletter = self.holder.find("#signupNYNewsletter").attr("checked")?1:0;
                res.signupHmNewsletter = self.holder.find("#signupHmNewsletter").attr("checked")?1:0;
                res.signupWSNewsletter = self.holder.find("#signupWSNewsletter").attr("checked")?1:0;
                res.signupEverywhereNewsletter = $("#signupEverywhereNewsletter").attr("checked")?1:0;
                res.signupMiamiNewsletter = $("#signupMiamiNewsletter").attr("checked")?1:0;
                res.signupChicagoNewsletter = $("#signupChicagoNewsletter").attr("checked")?1:0;
                res.signupLondonNewsletter = $("#signupLondonNewsletter").attr("checked")?1:0;
                res.signupAustinNewsletter = $("#signupAustinNewsletter").attr("checked")?1:0;
                res.signupSanfrNewsletter = $("#signupSanfrNewsletter").attr("checked")?1:0;
                res.signupBostonNewsletter = $("#signupBostonNewsletter").attr("checked")?1:0;
                res.signupPassword = self.holder.find("#signupPassword").val();
                res.username = self.holder.find("#username").val();
                break;
            case "dologin":
                res.uname = self.holder.find("#uname").val();
                res.upwd = self.holder.find("#upwd").val();
                res.remember = self.holder.find("#remember").attr("checked")?1:0;
                break;
            case "register":
                res.signupPassword = self.holder.find("#signupPassword").val();
                res.username = self.holder.find("#username").val();
                res.signupEmail = self.holder.find("#signupEmail").val();
                res.securitycode = self.holder.find("#securitycode").val();
                res.matchthis = self.holder.find("[name=matchthis]").val();
                res.termsAgree = self.holder.find("#termsAgree").val();
                res.signupLANewsletter = self.holder.find("#signupLANewsletter").attr("checked")?1:0;
                res.signupNYNewsletter = self.holder.find("#signupNYNewsletter").attr("checked")?1:0;
                res.signupHmNewsletter = self.holder.find("#signupHmNewsletter").attr("checked")?1:0;
                res.signupWSNewsletter = self.holder.find("#signupWSNewsletter").attr("checked")?1:0;
                break;
            case "sendpwd":
                res.remindTo = self.holder.find("#remindEmail").val();
                break;                    
        }
        return res;
    }
    self.actions = {login:"login",
                    signup:"signupstep2",
                    topsignup:"topsignup",
                    skipInfo:"skip",
                    submitInfo:"submit",
                    doLogin:"dologin",
                    register:"register",
                    signupsimple:"signupsimple",
                    reentermail:"reentermail",
                    forgotpassword:"forgotpwd",
                    sendpwd:"sendpwd",
                    opentip:"opentip",
                    sendtip:"sendtip"};
    return {
        unameregistered:false,
        emailregistered:false,
        lastuname:"",
        lastemail:"",
        captchacorrect:true,
        lastcaptcha:"",
        actions:self.actions,
        callPopUp:function (action, validator, actionUrl){
            if(this.unameregistered == 'checking' || this.emailregistered == "checking" || this.captchacorrect == "checking") return;
            if(!self.inited)
                self.init();
            var valid = false;
            if(validator)
                valid = validator(self.holder);
            else
                valid = true;
            if(valid){
                var data = self.collectPostData(action);
                data.popup = 1;
                self.holder.html("");
                self.holder.addClass("popup-loader");
                $.ajax({
                        url: (actionUrl ? actionUrl : city_url + '/account/' + action),
                        type: 'POST',
                        dataType: 'html',
                        data: data,
                        success:function(res){
                          self.holder.removeClass("popup-loader");
                          self.holder.html(res);
                        },
                        error:function(res){
                            self.holder.html(res);
                        },
                        complete:function(a1, a2){
                            var a = 10;
                        }});
                this.openPopUp();
            }
        },
        closePopUp:function(){
            self.contentholder.hide();
            self.background.hide();
           // self.root.hide();
        },
        openPopUp:function(){
            self.background.show();
            self.contentholder.show();
            //for scrolling if window is too small
            self.contentholder.css("position", self.contentholder.find("div:first").height() + 10 > document.body.clientHeight ? "absolute" : "");
            //self.root.show();
        },
        createUsername:function(res, uname){
            var email = res.value;
            var pos = search(email,'@');
            uname.value = pos > 0?substr(email, 0, pos - 1):email;
        }
    }   
})();
function validateForgotForm(holder){
    var email = holder.find("#remindEmail").val();
    var err_img = $("<img>").addClass("icons");
    if($.trim(email) == "") {
                holder.find("#remindEmailError").text("")
                            .append(err_img.clone())
                            .append("Please provide your email or username");
		holder.find("#remindEmail").focus();
    	return false;
    }
    return  true;
}
function skipValidator(holder)
{
     var signupPassword = holder.find("#signupPassword").val();
     var cSignupPassword = holder.find("#signupPasswordConfirm").val();
     var username = holder.find("#username").val();
     var pvalid = true, uvalid = true;
     var err_img = $("<img>").addClass("icons");
     if(signupPassword != cSignupPassword){
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Passwords do not match");
         pvalid = false;
     }
     
     if(signupPassword.length < 6){
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Password is too short");
         pvalid = false;
     }
     if(pvalid) holder.find("#passwordError").html("");
     
     if(username == '3 to 32 alphanumeric characters or "_"' || $.trim(username) == ""){
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is required");
         uvalid = false;
     }
     
     if((username.length < 3)&& username != '3 to 32 alphanumeric characters or "_"' ){
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is too short");
         uvalid = false;
     }
     if((username.length > 32)&& username != '3 to 32 alphanumeric characters or "_"' ){
        holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is too long");
         uvalid = false;
     }
     
     
      var unRegexp =  /[^a-zA-Z0-9_]/;
     if(unRegexp.test(username) && username != '3 to 32 alphanumeric characters or "_"' ){
         //$("#usernameError").text("Username should contain alphanumeric characters and \"_\" only");
        holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Letters, digits and \"_\" only");
         uvalid = false;
     }
     if(uvalid && !loginPopUp.unameregistered) holder.find("#usernameError").html("");
   
     return (pvalid && uvalid && !loginPopUp.unameregistered && !loginPopUp.emailregistered);
}
function checkUsername(object, errorHolder){
    if(loginPopUp.lastuname == object.value || object.value == "" ) return;
    $("#"+errorHolder).html('<div class="check"></div>&nbsp;Checking username...');
    loginPopUp.unameregistered = 'checking';
    loginPopUp.lastuname = object.value;
    $.ajax({
            url: city_url + '/account/checkuname',
            type: 'POST',
            dataType: 'html',
            data: {username:object.value,popup:1},
            success:function(res){

                if(res.substr(0, 2) == 'Ok'){
                    $("#"+errorHolder).html('<img class="icons iok" /><span style="color:#008000">Available</span>');
                    loginPopUp.unameregistered = false;
                }
                else{
                    $("#"+errorHolder).html('<img class="icons" />Username is already registered');
                    loginPopUp.unameregistered = true;
                }
            },
            error:function(res){
                loginPopUp.unameregistered = false;
            }});
}
function checkEmail(object, errorHolder){
    if(loginPopUp.lastemail == object.value || object.value == "" || object.value == "Enter your mail address here...") return;
    $("#"+errorHolder).html('<div class="check"></div>&nbsp;Checking email...');
    loginPopUp.emailregistered = 'checking';
    loginPopUp.lastemail = object.value;
    $.ajax({
            url: city_url + '/account/checkemail',
            type: 'POST',
            dataType: 'html',
            data: {email:object.value,popup:1},
            success:function(res){

                if(res.substr(0, 2) == 'Ok'){
                    $("#"+errorHolder).html('<img class="icons iok" /><span style="color:#008000">Ok</span>');
                    loginPopUp.emailregistered = false;
                }
                else{
                    $("#"+errorHolder).html('<img class="icons" />Email is already registered');
                    loginPopUp.emailregistered = true;
                }
            },
            error:function(res){
                loginPopUp.emailregistered = false;
            }});
}
function checkCaptcha(object, errorHolder){
    if(loginPopUp.lastcaptcha == object.value || object.value == "") return;
    $("#"+errorHolder).html('<div class="check"></div>&nbsp;Checking security code...');
    loginPopUp.captchacorrect = 'checking';
    loginPopUp.lastcaptcha = object.value;
    $.ajax({
            url: city_url + '/account/checkcaptcha',
            type: 'POST',
            dataType: 'html',
            data: {securitycode:object.value,popup:1,quicktest:1,matchthis:$("#popupMatchCode").val()},
            success:function(res){

                if(res.substr(0, 2) == 'Ok'){
                    $("#"+errorHolder).html('<img class="icons iok" /><span style="color:#008000">Ok</span>');
                    loginPopUp.captchacorrect = true;
                }
                else{
                    $("#"+errorHolder).html('<img class="icons" />Incorrect security code');
                    loginPopUp.captchacorrect = false;
                }
            },
            error:function(res){
                loginPopUp.captchacorrect = true;
            }});
}
function registerValidator(holder){
     var signupPassword = holder.find("#signupPassword").val();
     var signupPasswordConfirm = holder.find("#signupPasswordConfirm").val();
     var username = holder.find("#username").val();
     var signupEmail = holder.find("#signupEmail").val();
     var securitycode = holder.find("#securitycode").val();
     var termsAgree = holder.find("#termsAgree").attr('checked');
     var pvalid = true, uvalid = true, evalid = true, svalid = true, avalid = true;
     var err_img = $("<img>").addClass("icons");
     if($.trim(signupPassword) == ""){
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Password can not be empty");
         pvalid = false;
     }
     if(signupPassword != signupPasswordConfirm){
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Passwords do not match");
         pvalid = false;
     }
     if(signupPassword.length < 6){
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Password must be at least 6 characters long");
         pvalid = false;
     }
     if(pvalid) holder.find("#passwordError").html("");
     
     if(username == '3 to 32 alphanumeric characters or "_"' || $.trim(username) == ""){
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is required");
         uvalid = false;
     }
     if(username == "" || username == '3 to 32 alphanumeric characters or "_"'){
       holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is required");
         uvalid = false;  
     } else if(username.length < 3 && username != '3 to 32 alphanumeric characters or "_"' ){
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is too short");
         uvalid = false;
     } else if(username.length > 32 && username != '3 to 32 alphanumeric characters or "_"' ){
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username is too long");
         uvalid = false;
     }
     var unRegexp =  /[^a-zA-Z0-9_]/;
     if(unRegexp.test(username) && username != '3 to 32 alphanumeric characters or "_"' ){
         //$("#usernameError").text("Username should contain alphanumeric characters and \"_\" only");
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Letters, digits and \"_\" only");
         uvalid = false;
     }
     if(uvalid && !loginPopUp.unameregistered) holder.find("#usernameError").html("");
     
     if(signupEmail == "") {
            holder.find("#signupEmailError").text("")
                                  .append(err_img.clone())
                                  .append("Empty email address");
            evalid = false;
    }	else if(signupEmail.search("[ ]") == 0) {
             holder.find("#signupEmailError").text("")
                                   .append(err_img.clone())
                                   .append("E-mail shouldn't start with spaces.");
            evalid = false;
    } else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(signupEmail))) 	{
            holder.find("#signupEmailError").text("")
                                  .append(err_img.clone())
                                  .append("Incorrect e-mail address");
            evalid = false;
    }
    if(evalid && !loginPopUp.emailregistered) holder.find("#signupEmailError").html("");
    if($.trim(securitycode) == ""){
        holder.find("#securityError").text("")
                           .append(err_img.clone())
                           .append("Empty security code");
        svalid = false;
    }
    if(svalid && loginPopUp.captchacorrect) holder.find("#securityError").html("");
    
    if(!termsAgree)
    {
        //alert('You should agree with Terms of Service and Privacy Policy to register');
        holder.find("#termsError").text("")
                        .append(err_img.clone())
                        .append("You should agree with Terms of Service and Privacy Policy");
        avalid = false
    }    
    if(avalid) holder.find("#termsError").html("");
   
    return (avalid && svalid && evalid && uvalid && pvalid && !loginPopUp.emailregistered && !loginPopUp.unameregistered && loginPopUp.captchacorrect);
}
function checkAgreeState(sender){
    if(sender.checked){
        $('#termsError').html('');
    }
}
function loginValidator(holder){
     var username = holder.find("#uname").val();
     var password = holder.find("#upwd").val();
     var valid = true; //$.trim(username) != "" && $.trim(password);
     var err_img = $("<img>").addClass("icons");
     //check password
     if ($.trim(password) == "") {
         holder.find("#passwordError").text("")
                            .append(err_img.clone())
                            .append("Password can not be empty");
         valid = false;
     }
     //check username
     if ($.trim(username) == "") {
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Username or email can not be empty");
         valid = false;
     } else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(username)) && !(/\w+/.test(username))) {
         holder.find("#usernameError").text("")
                            .append(err_img.clone())
                            .append("Incorrect username or password");
         valid = false;
     }
     return valid;
}

function blurfunction(obj, defval) {
	if ((obj.id == "uname") || (obj.id == "email")) {
		if ((obj.value == "") || (obj.value == "Email")) {
			obj.style.color = "#a4a4a4";
			obj.value = "Email";
		}
	} else if ((obj.id == "upass") || (obj.id == "cpassword")) {
		if ((obj.value == "") || (obj.value  == "Password")) {
			obj.type = "text";
			obj.style.color = "#a4a4a4";
			obj.value = "Password";
		}
	} else if ((obj.id == "fName") || (obj.id == "First")) {
		if ((obj.value == "") || (obj.value == "First")) {
			obj.style.color = "#a4a4a4";
			obj.value = "First";
		}
	} else if ((obj.id == "lName") || (obj.id == "Last")) {
		if ((obj.value == "") || (obj.value == "Last")) {
			obj.style.color = "#a4a4a4";
			obj.value = "Last";
		}
	}
	else if ((obj.id == "signupEmail") ) {
		if ((obj.value == "") || (obj.value == "Enter Your Email")) {
			obj.style.color = "#a4a4a4";
                        obj.style.background = "#fff";
			obj.value = "Enter Your Email";
		}
	}
	else if ((obj.id == "signupPassword") ) {
		if ((obj.value == "") || (obj.value == "Enter Password")) {
			obj.style.color = "#a4a4a4";
			obj.value = "Enter Password";
			obj.type = "text";
		}
	}
        else if ((obj.id == "username") ) {
		if ((obj.value == "") || (obj.value == '3 to 32 alphanumeric characters or "_"')) {
			obj.style.color = "#a4a4a4";
			obj.value = '3 to 32 alphanumeric characters or "_"';
		}
	}else{
            if ((obj.value == "") || (obj.value == defval)) {
                obj.style.color = "#a4a4a4";
                obj.type = "text";
                obj.value = defval;
            }
        }
}

function focusfunction(obj, defval, type) {
	if (((obj.id == "uname") && (obj.value == "Email")) || ((obj.id == "fName") && (obj.value == "First")) || ((obj.id == "lName") && (obj.value == "Last")) || ((obj.id == "upass") && (obj.value == "Password")) || ((obj.id == "email") && (obj.value == "Email"))
            || ((obj.id == "cpassword") && (obj.value == "Password")) || ((obj.id == "username") && (obj.value == '3 to 32 alphanumeric characters or "_"'))) {
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}else
	if ((obj.id == "upass") || (obj.id == "cpassword")) {
		obj.setAttribute('type',"password");
	}else
	if (((obj.id == "signupPassword") && (obj.value == "Enter Password")) || ((obj.id == "signupEmail") && (obj.value == "Enter Email"))){
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}else
	if (obj.id == "signupPassword") {
		obj.setAttribute('type',"password");
	}else{
            if(defval && obj.value == defval){
                obj.style.cursor = "default";
		obj.value = "";
                obj.style.color="#000";
                if(type)
                    obj.setAttribute('type',type);
            }
        }
}

function goShare(elem) {
    var box = $(elem).parent();
    var text_box = box.children("textarea");
    if (!text_box.hasClass("opened")) {
        openTipBox(elem);
    } else {
        var str = text_box.val();
        if (str == "") {
            text_box.focus();
        } else {
            $.ajax({
                url: city_url + "/store_tip.php",
                dataType: "text",
                type: "POST",
                data: {
                    "tip": str,
                    "action":1
                },
                success: function (res) {
                    closeTipBox(elem, res);
                }
            })
        }
    }
}
function openTipBox(elem) {
    var box = $(elem).parent();
    var text_box = box.children("textarea");
    if (text_box.val() == "Have a tip? (anonymous)" || text_box.val() == "Your tip has been sent." || text_box.val() == "Thank you for your submission."  || text_box.val() == "Your tip hasn't been sent.") {
        box.children(".icancel_tip")
           .removeClass("hidden");
        text_box.addClass("opened")
                .val("")
                .focus();
    }
}
function closeTipBox(elem, value) {
    var box = $(elem).parent();
    box.children("textarea")
       .removeClass("opened")
       .val(value ? value : "Have a tip? (anonymous)");
    box.children(".icancel_tip")
       .addClass("hidden");
}
function goToGuestComment() {
    $('.comment_wizard').hide();
    $('.comment_guest').show();
}
function putIntoComment(name) {
    $('#comment').val('@' + name + ': ')
                 .focus();
}
function showcityevents(id, parent, tabs, addinf){

    $(parent + " .current").removeClass('current');
    $(parent + " .city_" + id).addClass('current');
    $(parent + " .currentPan").removeClass('currentPan');
    $(parent + " #" +tabs + id).addClass('currentPan');
    if(addinf)
        $(parent + " #"+ addinf + id).addClass('currentPan');
}
function popUpSendTip(){
    var tip = $('#tip').val();
    if($.trim(tip) == '')
    {
        $('#tipError').show();
        return false;
    }
    else $('#tipError').hide();

    var securitycode = $('#securitycode').val();
    if($.trim(securitycode) == '' || securitycode == "Type the Security Code below")
    {
        $('#captchaError').show();
        return false;
    }
    else $('#captchaError').hide();

    var popupMatchCode = $('#popupMatchCode').val();    
    var mail = $('#tip-mail').val();
    if(mail == "Type the Security Code above")
        mail = '';

    $.ajax({
        url: city_url + "/store_tip.php",
        dataType: "text",
        type: "POST",
        data: {
            "tip": tip,
            "mail": mail,
            "matchthis":popupMatchCode,
            "securitycode":securitycode,
            "action":1
        },
        success: function (res) 
        {
            $('#sendRes').html(res);
            if (res == 'Thank you for your submission.')
            {
                setTimeout("if(typeof loginPopUp != 'undefined') loginPopUp.closePopUp();else window.parent.MP.Ajax.Login.closeDialog();", 1000);
            }
        }
    })
    $('#sendRes').html("Sending...");
}

suggest = (function() {
    var self = this;
    self.type = "";
    self.func_name = "";
    self.timer = -1;
    self.callValue = null;
    self.cache = new Object();
    self.position = -1;
    self.enteredValue = null;
    self.parentBox = new Object();
    self.contentBox = new Object();
    self.scroller = new Object();
    self.isKeyUpDownPressed = true;
    self.suggestions = 0;
    self.waitingResponse = false;
    self.minVisiblePosition = 0;
    self.maxVisiblePosition = 9;

    self.deselectAll = function()
    {
      for(var i=0; i < self.suggestions; i++)
      {
        var oCrtTr = self.parentBox.find("#tr" + i);
        oCrtTr.removeClass("highlightrow");
      }
    }

    self.getDataFromServer = function(){
        $.ajax({
                url: city_url + self.func_name,
                type: 'POST',
                dataType: 'text',
                data: {
                    'id': self.callValue,
                    'task': 'suggest'
                },
                success: function (res) {
                    if(self.waitingResponse)
                    {
                        self.contentBox.html(res)
                            .parent()
                            .css({"visibility": "visible"});
			self.position = -1;
			self.minVisiblePosition = 0;
			self.maxVisiblePosition = 9;
			self.waitingResponse = false;
                    }
                    self.cache[self.callValue] = res;
                }
            })
            self.waitingResponse = true;
    }

    self.refreshResults = function(value) {
        if (value.length > 0) {
            var context = this;
            if(self.cache[value])
            {
                context.value = value;
                self.contentBox.html(self.cache[value])
                    .parent()
                    .css({"visibility": "visible"});
                self.position = -1;
                self.minVisiblePosition = 0;
                self.maxVisiblePosition = 9;
            }
            else
            {
                if(self.timer == -1)
                {
                    context = this;
                    self.callValue = value;
                    self.timer = setTimeout(self.getDataFromServer, 350)
                }
            }
        } else {
           self.scroller.css({"visibility":"hidden"});
        }

    }

    self.updateValue = function(){
        if(self.enteredValue == null)
            self.enteredValue = $("#" + self.type + "_keyword").val();
        if(self.position >= 0){
            $("#" + self.type + "_keyword").val(self.contentBox.find("#tr" + self.position).text());
        }
    }

    self.restoreValue = function(){
        if(self.enteredValue != null)
             $("#" + self.type + "_keyword").val(self.enteredValue);
         self.enteredValue = null;
    }

    return {
	initSuggest: function (type) {
            self.type = type;
            switch (type) {
                case "right":
                case "people":self.func_name = "/ajax_people_suggest.php";
                               break;
				case "single-venues":
                               self.func_name = "/venue/venues.php";
                               break;
                case "venues":self.func_name = "/venue/venues.php";
                               break;
                case "calendar":
                                self.func_name = "/calendar/ajax_suggest.php";
                                break;
            }
            self.enteredValue = null;
            self.parentBox = $("#" + self.type + "_keyword").parent();
            self.contentBox = $("#" + self.type + "_suggest");
            self.scroller = $("#" + self.type + "_scroll");
	},
        handleOnMouseOver:function(oTr){
          self.contentBox.find("#tr" + self.position).removeClass("highlightrow");
          oTr.addClass("highlightrow");
          self.position = parseInt(oTr.attr("id").substring(2, oTr.attr("id").length));
          self.updateValue();
        },
        handleOnMouseOut:function(oTr){
          oTr.removeClass("highlightrow");
          //self.position = -1;
        },
        onFocusSuggestIn:function(elem) {
            var id = $(elem).attr("id");
            suggest.initSuggest(id.substring(0, id.indexOf('_')));
            
            var value = $(elem).val();
            if((self.type == "venues" && value == 'Search By Name') || ((self.type == "people" || self.type == "right") && value == 'Find people in photos'))
                $('#' + self.type + '_keyword').val('')
                                               .css({
                                                   'color': '#000000',
                                                   'background-color': '#FFFFFF'
                                               });
            else
            {
                if (value.length > 0) {
                    $('#' + self.type + '_scroll').css({"visibility":"visible"});
                    self.restoreValue();
                }
            }
        },
        onFocusSuggestOut:function(value) {
            setTimeout(function(){self.scroller.css({"visibility":"hidden"})}, 100);
            //$('#' + self.type + '_keyword').val('');
        },
        goCurrent:function() {
            if(self.position >= 0)
            {
                location.href = self.parentBox.find("#a" + self.position).attr("href");
            }
        },
        handleSuggestKeyUp:function(e)
        {
          // get the event
          e = (!e) ? window.event : e;
          // get the event's target
          var target = (!e.target) ? e.srcElement : e.target;
          if (target.nodeType == 3)
            target = target.parentNode;
          // get the character code of the pressed button
          var code = (e.charCode) ? e.charCode :
               ((e.keyCode) ? e.keyCode :
               ((e.which) ? e.which : 0));
            // get the event
          e = (!e) ? window.event : e;
          // get the event's target
          target = (!e.target) ? e.srcElement : e.target;
          if (target.nodeType == 3)
            target = target.parentNode;
          // get the character code of the pressed button
          code = (e.charCode) ? e.charCode :
               ((e.keyCode) ? e.keyCode :
               ((e.which) ? e.which : 0));
          // check to see if the event was keyup
          if (e.type == "keyup")
          {
            isKeyUpDownPressed =false;
            // check to see we if are interested in the current character
            if ((code < 13 && code != 8) ||
                (code >=14 && code < 32) ||
                (code >= 33 && code <= 46 && code != 38 && code != 40) ||
                (code >= 112 && code <= 123))
            {
              // simply ignore non-interesting characters
            }
            else
            /* if Enter is pressed we jump to the PHP help page of the current
               function */
            if(code == 13)
            {
              // check to see if any function is currently selected
              if(self.position>=0)
              {
                this.goCurrent();
              }
            }
            else
            // if the down arrow is pressed we go to the next suggestion
              if(code == 40 && !self.scroller.is(':hidden'))
              {
                oldTR = self.parentBox.find("#tr" + (self.position));
                newTR = self.parentBox.find("#tr" + (self.position + 1));
                // deselect the old selected suggestion
                if(newTR.length == 1)
                {
                  oldTR.removeClass("highlightrow");
                  newTR.addClass("highlightrow");
                  self.position ++;
                  self.updateValue();
                }
                e.cancelBubble = true;
                e.returnValue = false;
                isKeyUpDownPressed = true;
                // scroll down if the current window is no longer valid
                if(self.position >= self.maxVisiblePosition)
                {
					self.maxVisiblePosition++;
					self.minVisiblePosition++;
                }
              }
              else
              // if the up arrow is pressed we go to the previous suggestion
              if(code == 38 && !self.scroller.is(':hidden'))
              {

                oldTR = self.parentBox.find("#tr"+(self.position));
                newTR = self.parentBox.find("#tr"+(self.position - 1));
                // deselect the old selected position

                if(newTR.length == 1)
                {
                  oldTR.removeClass("highlightrow");
                  newTR.addClass("highlightrow");
                  self.position --;
                  self.updateValue();

                }
                else
                {

					if(self.position == 0){
						self.position --;
						self.restoreValue();
						oldTR.removeClass("highlightrow");

					}
                }
                // scroll up if the current window is no longer valid
                if(self.position < self.minVisiblePosition)
                {
					self.maxVisiblePosition--;
					self.minVisiblePosition--;
                }

                e.cancelBubble = true;
                e.returnValue = false;
                isKeyUpDownPressed = true;
              } else {
                  clearTimeout(self.timer);
                  self.timer = -1;
                  self.refreshResults($('#' + self.type + '_keyword').val());
              }
          }
          else
          {
            if ((code <= 13 && code != 8) ||
                (code >=14 && code < 32) ||
                (code >= 33 && code <= 46) ||
                (code >= 112 && code <= 123))
            {
            }else
            {
                self.restoreValue();
                self.refreshResults($('#' + self.type + '_keyword').val());
            }
          }
      }
   }
})();/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* �2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

function displayArchives(link)
{
	if (link == 'Less')
	{
		var footer_margin = $('.footer').css('margin-top');
		var form_height = $('.calendarNavigation').outerHeight();

		$('div.gallery-monthes').hide();
		$('.footer').css('margin-top', (parseInt(footer_margin) - (parseInt(form_height) + 45)) + 'px');
		return 'More';
	}
	else
	{
		$('div.gallery-monthes').show();
		var footer_margin = $('.footer').css('margin-top');
		var form_height = $('.calendarNavigation').outerHeight();
		$('.footer').css('margin-top', (parseInt(footer_margin) + parseInt(form_height) + 45) + 'px');
		return 'Less';
	}
}

function addLocation()
{
	var form = document.createElement('div');
	$(form).addClass('location-popup').html('Please enter in the information of your location: <br /><b>All fields are required</b><br /><br />' +
					 '<div class="location-popup-error">You must enter all fields</div><input type="text" style="color:#7C7C7C;" name="Location" value="Name" class="calenderInput" id="Location"  onfocus="cfocusfunction(this);" onblur="cblurfunction(this);"/><br /><br />' +
					 '<input type="text" style="color:#7C7C7C;" name="Address" value="Address" class="calenderInput" id="Address"  onfocus="cfocusfunction(this);" onblur="cblurfunction(this);" /><br /><br />' +
					 '<input type="text" style="color:#7C7C7C;" name="City" value="City, State" class="calenderInput" id="City"  onfocus="cfocusfunction(this);" onblur="cblurfunction(this);" /><br /><br />' +
					 '<div align="right"><input type="button" value="" onclick="cancelLocationAdd(); return false;" class="icons icancel">&nbsp;&nbsp;' +
					 '<input type="button" value="" onclick="submitLocationAdd();return false;" class="icons isubmit"></div>');

	var div = document.createElement('div');
	$(div).addClass('login-popup-bg');
	$('body').prepend(div).prepend(form);
}

function cancelLocationAdd()
{
	$('.location-popup').remove();
	$('.login-popup-bg').remove();
}

function submitLocationAdd()
{
	var location = $('#Location').val();
	var address = $('#Address').val();
	var city = $('#City').val();

	if (location && location != 'Name' && address && address != 'Address' && city && city != 'City, State')
	{
		$('#Location_result').val(location);
		$('#Address_result').val(address);
		$('#City_result').val(city);
		$('#venueId').append('<option value="" selected>' + location + '</option>');
		cancelLocationAdd();
	}
	else
	{
		$('.location-popup').css('height', '195px');
		$('.location-popup div.location-popup-error').show();
	}
}


function showCalenderDiv (id) {
	if(document.getElementById('newCalendarDetails' + id).style.display == "inline"){
		document.getElementById('newCalendarDetails'+id).style.display = 'none';
		document.getElementById('link'+id).style.display = 'inline';
		document.getElementById('desc'+id).style.display = 'none';
	}
	else
		document.getElementById('newCalendarDetails'+id).style.display = 'inline';
}

function loadCalendarByType(eType, pType, opt, city_id, show_all) {
    //alert(eType + ' / ' + pType + ' / ' + opt + ' / ' + city_id + ' / ' + show_all);
    $.ajax({
        url: city_url + "/calendar/get-events.php",
        dataType: "text",
        type: "POST",
        data: {"type": eType, "page": pType, "opt": opt, "city_id": city_id, "show_all": show_all},
        success: function (res) {
            switch (pType) {
                case 'sidebar':
                    $('div#calendar-content').html(res);
                    break;
                case 'events':
                    $('div#CalendarBodyText').html(res);
                    break;
            }
        }
    });
}
function openDescription (id) {
	document.getElementById('link'+id).style.display = 'none';
	document.getElementById('desc'+id).style.display = 'inline';
}

   function allblurfunction() {
  	document.getElementById('Title').style.color = '#7C7C7C';
  	document.getElementById('Description').style.color = '#7C7C7C';
  	document.getElementById('Location').style.color = '#7C7C7C';
  	document.getElementById('Address').style.color = '#7C7C7C';
  	document.getElementById('City').style.color = '#7C7C7C';
  	document.getElementById('captcha').style.color = '#7C7C7C';
  }


 function cblurfunction(obj) {
	if (obj.id == "Title") {
		if ((obj.value == "") || (obj.value == "Please avoid all CAPS")) {
			obj.style.color = "#7C7C7C";
			obj.value = "Please avoid all CAPS";
		}
	}
	if (obj.id == "Description") {
		if ((obj.value == "") || (obj.value == "Please avoid all CAPS")) {
			obj.style.color = "#7C7C7C";
			obj.value = "Please avoid all CAPS";
		}
	}

	if (obj.id == "captcha") {
		if ((obj.value == "") || (obj.value == "Prove you're human!")) {
			obj.style.color = "#7C7C7C";
			obj.value = "Prove you're human!";
		}
	}

	if (obj.id == "Location") {
		if ((obj.value == "") || (obj.value == "Name")) {
			obj.style.color = "#7C7C7C";
			obj.value = "Name";
		}
	}

	if (obj.id == "Address") {
		if ((obj.value == "") || (obj.value == "Address")) {
			obj.style.color = "#7C7C7C";
			obj.value = "Address";
		}
	}

	if (obj.id == "City") {
		if ((obj.value == "") || (obj.value == "City, State")) {
			obj.style.color = "#7C7C7C";
			obj.value = "City, State";
		}
	}
}

function cfocusfunction(obj) {
	if ((obj.id == "Title") && (obj.value == "Please avoid all CAPS")) {
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}
	/*if (obj.id == "Title") {
		obj.type = "Please avoid all CAPS"; // mahesh do you know what it'll do?
			}*/

	else if ((obj.id == "Description") && (obj.value == "Please avoid all CAPS")) {
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}
	/*if (obj.id == "Description") {
		obj.type = "Please avoid all CAPS";
	}*/

	else if ((obj.id == "captcha") && (obj.value == "Prove you're human!")) {
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}
	/*if (obj.id == "captcha") {
		obj.type = "Prove you're human!";
	}*/
	else if(((obj.id == "Location") && (obj.value == "Name")) || ((obj.id == "Address") && (obj.value == "Address")) || ((obj.id == "City") && (obj.value == "City, State"))) {
		obj.style.cursor = "default";
		obj.value = "";
		obj.style.color = "#333333";
	}
}
function validateCalendarForm() {

        var start_time = new Date(document.calendarForm.FromDay.value + "/" + document.calendarForm.FromMonth.value + "/"+ document.calendarForm.FromYear.value + " " + document.calendarForm.FromHour.value + ":" + document.calendarForm.FromMin.value + " " +document.calendarForm.FromMer.value);
        var end_time = new Date(document.calendarForm.FromDay.value + "/" + document.calendarForm.FromMonth.value + "/"+ document.calendarForm.FromYear.value + " " + document.calendarForm.ToHour.value + ":" + document.calendarForm.ToMin.value + " " +document.calendarForm.ToMer.value);

        if((document.calendarForm.citysite.value == "") || (! IsNumeric(document.calendarForm.citysite.value))){
                alert("Please provide City Site");
                document.calendarForm.citysite.focus();
                return false;
        }else if((document.calendarForm.Title.value == "") || (document.calendarForm.Title.value == "Please avoid all CAPS")) {
		alert("Please provide Event Title");
		document.calendarForm.Title.focus();
		return true;
	} /*if((document.calendarForm.Description.value == "") || (document.calendarForm.Description.value == "Please avoid all CAPS")) {
		alert("Please provide Event Description");
		document.calendarForm.Description.focus();
		return true;
	}*/if((document.calendarForm.FromHour.value == "") || (! IsNumeric(document.calendarForm.FromHour.value))) {
		alert("Please provide Event Start Time");
		document.calendarForm.FromHour.focus();
		return false;
	} else if((document.calendarForm.FromMin.value == "") || (! IsNumeric(document.calendarForm.FromMin.value))) {
		alert("Please provide Event Start Time");
		document.calendarForm.FromMin.focus();
		return false;
	} else if((document.calendarForm.FromMer.value == "")) {
		alert("Please provide Event Start Time");
		document.calendarForm.FromMer.focus();
		return false;
	} else if((document.calendarForm.ToHour.value == "") || (! IsNumeric(document.calendarForm.ToHour.value))) {
		alert("Please provide Event End Time");
		document.calendarForm.ToHour.focus();
		return false;
	} else if((document.calendarForm.ToMin.value == "") || (! IsNumeric(document.calendarForm.ToMin.value))) {
		alert("Please provide Event End Time");
		document.calendarForm.ToMin.focus();
		return false;
	} else if((document.calendarForm.ToMer.value == "")) {
		alert("Please provide Event End Time");
		document.calendarForm.ToMer.focus();
		return false;
	} else if((document.calendarForm.admission.value == "")) {
		alert("Please provide Admission type");
		document.calendarForm.admission.focus();
		return false;
	} else if((document.calendarForm.type.value == "")) {
		alert("Please provide Type of event");
		document.calendarForm.type.focus();
		return false;
	} else if((document.calendarForm.venueId.value == "")) {
		if((document.calendarForm.Location.value == "") || (document.calendarForm.Location.value == "Name")) {
			alert("Please provide Event Location Name");
			document.calendarForm.Location.focus();
			return false;
		} else if((document.calendarForm.Address.value == "") || (document.calendarForm.Address.value == "Address")) {
				alert("Please provide Event Location Address");
				document.calendarForm.Address.focus();
				return false;
		} else if((document.calendarForm.City.value == "") || (document.calendarForm.City.value == "City, State")) {
				alert("Please provide Event Location City, State");
				document.calendarForm.City.focus();
				return false;
		}
	}if((document.calendarForm.FromYear.value == "") || (! IsNumeric(document.calendarForm.FromYear.value))) {
		alert("Please provide Event Date");
		document.calendarForm.FromYear.focus();
	} else if((document.calendarForm.FromMonth.value == "") || (! IsNumeric(document.calendarForm.FromMonth.value))) {
		alert("Please provide Event Date");
		document.calendarForm.FromMonth.focus();
	} else if((document.calendarForm.FromDay.value == "") || (! IsNumeric(document.calendarForm.FromDay.value))) {
		alert("Please provide Event Date");
		document.calendarForm.FromDay.focus();
	} else if(((document.calendarForm.Email.value == "") && (window.emailRequired == true))
                  || !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.calendarForm.Email.value))) {
		alert("Please provide your Email address");
		document.calendarForm.Email.focus();
	} else if((document.calendarForm.Description.value == "") || (document.calendarForm.Description.value == "Please avoid all CAPS")) {
		alert("Please provide Description");
		document.calendarForm.Description.focus();
        } else if((document.calendarForm.captcha.value == "") || (document.calendarForm.captcha.value == "Prove you're human!")) {
		alert("Prove you're human!");
		document.calendarForm.captcha.focus();
	} else if (end_time - start_time <= 0) {
		alert("Event End Time must be greater than Event Start Time!");
		document.calendarForm.ToHour.focus();
	} else {
		document.calendarForm.submit();
	}
}


function IsNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }
   return IsNumber;
}

	function submitform()
	{
		u=location.href;
		//alert(u);
		document.facebook_form.event_url.value=u;
	    document.facebook_form.submit();
	}

	function openEmailForm1(){
		//alert('1');
		document.getElementById("urname_up"). value="";
		document.getElementById("email_up"). value="";
		document.getElementById("remarks_up"). value="";
		document.getElementById("fn_email_up"). value="";
		document.getElementById("responce_up"). innerHTML="";
		document.getElementById("email_form_up").style.display="inline";
		document.getElementById("responce_up").style.display="none";
		if(document.getElementById('email_form1').style.display == 'none') {
		document.getElementById('email_form1').style.display = 'block';
		var height = document.getElementById("upperContent").offsetHeight;
		if(height  < document.getElementById("right").offsetHeight)
				height += document.getElementById("email_form2").offsetHeight;
			if(document.getElementById("right").offsetHeight < height) {
				document.getElementById("upperContent").style.height = height + "px";
				document.getElementById("right").style.height = height + "px";
			}

		}else {
			//height -= document.getElementById("email_form1").offsetHeight;
			document.getElementById('email_form1').style.display = 'none';
			//document.getElementById("upperContent").style.height = height + "px";
		var ufright = document.getElementById("right").offsetHeight;
		var ufhome = document.getElementById("upperContent").offsetHeight;

	if((ufright) < (ufhome)){
		document.getElementById("right").style.height = (ufhome) + "px";
	}
		}
                InputHelperCreate("#fn_email_up", "friend1@example.com\nfriend2@example.com\nfriend3@example.com");
		return false;
	}

	function submitEmail_up(title_up,cal_url){
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null){
		alert ("Browser does not support HTTP Request");
		return;
	}
	var urname_up = document.getElementById("urname_up"). value;
	var email_up = document.getElementById("email_up"). value;
	var remarks_up = document.getElementById("remarks_up"). value;
	var fn_email_up = document.getElementById("fn_email_up").value.replace("\n", ",");
	var em_up = document.getElementById("em_up"). value;
	var url = "/calenderEvent_mail.php?event_title="+title_up+"&urname="+urname_up+"&email="+email_up+"&remarks="+remarks_up+"&fn_email="+fn_email_up+"&em="+em_up+"&cal_url="+cal_url;;
	//alert(url);
	xmlHttp.open("GET",url,false);
	xmlHttp.send(null);
	if (xmlHttp.status==200) {
		document.getElementById("responce_up").innerHTML='<div class="gallery-notice-box">A message has been sent to the following addresses:</div>'+xmlHttp.responseText;
		document.getElementById("email_form_up").style.display="none";
		document.getElementById("responce_up").style.display="inline";
	}

}

function GetXmlHttpObject(){
	var xmlHttp=null;
	try {
		 // Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		//Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function showInterviewDiv(divId, totalDivs, year, dateString)
{
	for(var i=0; i < totalDivs; i++)
	{
		$('#year'+i).hide();
	}
	$('#year'+divId).show();
	dateArray = dateString.split(',');
	for(var i=0; i<dateArray.length; i++)
	{
		if(year == dateArray[i])
		{
			$('#' + dateArray[i]).html(dateArray[i]);
		}
		else
		{
			var outputString = "<a href='#' onclick='javascript:showInterviewDiv("+i+",";
			outputString += totalDivs+","+dateArray[i]+",\""+dateString+"\");return false;'>";
			outputString += dateArray[i]+"</a>";
			$('#' + dateArray[i]).html(outputString);
		}
	}
}

function displayInterviewContent(interviewId)
{
	$.ajax({
			url: city_url + "/getInterviewContent.php?id="+interviewId,
			type: 'GET',
			dataType: 'html',
			success:function(res)
			{
				$("#show_interview_content").html(res);
			}
		});
}

function venueListEventPage(page_number)
{
	var venue_url = $('input[name=venue_url]').val();
	$.ajax({
			url: city_url + "/venue/change_events_page_ajax.php?page=" + page_number + '&venue_url=' + venue_url,
			type: 'GET',
			dataType: 'json',
			success:function(res)
			{
				if (res)
				{
					$('.venue-events-list').html('');
					for (i in res)
					{
						var div = document.createElement('div');
						$(div).attr('class','venue-event-item clearfix');

						var a = document.createElement('a');
						$(a).attr({'href':'/galleries/album' + res[i].albumId + '/', 'class':'event-pic'});

						var img = document.createElement('img');
						$(img).attr({'alt':res[i].albumName, 'src':'http://guestofaguest.com/wp-content/uploads/wppa/thumbs/' + res[i].photoId + '.' + res[i].ext});

						$(a).append(img);

						var div_info = document.createElement('div');
						$(div_info).attr('class', 'event-info').append('<p>' + res[i].createdDate + '</p>');

						var a_info = document.createElement('a');
						$(a_info).attr({'href':'/galleries/album' + res[i].albumId + '/'}).html(res[i].albumName);

						$(div_info).append(a_info);

						$(div).append(a).append(div_info);

						$('.venue-events-list').append(div);
					}

					$('a[id^=event-page-]').removeClass();
					$('#event-page-' + page_number).addClass('sb-current-page');
				}
			}
		});
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getClientCenterY()
{
	return parseInt(getClientHeight()/2)+getBodyScrollTop();
}

function openImage(image_path, alt)
{
	var img = document.createElement('img');
	$(img).attr({'alt':alt, 'src':image_path, 'border':0});

	var close = document.createElement('div');
	$(close).attr('class', 'popupt-close-button').css({'margin':0}).click(function()
	{
		$('.login-popup-bg, .advertise-image-popup').remove();
	});

	var div = document.createElement('div');
	$(div).attr('class', 'advertise-image-popup').css({'top':getClientCenterY()-250}).append(close).append(img);
	$('body').prepend(div);

	var div = document.createElement('div');
	$(div).attr('class', 'login-popup-bg');
	$('body').prepend(div);
}

function showBlogRollDiv(divIdNumber, totalNoofDivs, obj) {
	for(var i=0; i < totalNoofDivs; i++) {
		document.getElementById("blogrolldiv"+i).style.display = "none";
		try{
			document.getElementById("black"+i+"active").id="black"+i;
		} catch (e) {
		}
	}
	document.getElementById("blogrolldiv"+divIdNumber).style.display = "inline";
	obj.id += 'active';
}

function expandCalendar()
{
    if ($('div.calendar .calendar-other-events').css('display') == 'none')
    {
        $('.calendar-bottom span.calendar-more').css('background-position', '0 -124px');
        $('div.calendar .calendar-other-events').slideToggle('quick');
    }
    else
    {
        $('.calendar-bottom span.calendar-more').css('background-position', '0 -103px');
        $('div.calendar .calendar-other-events').slideUp('quick');
    }
}

function submitEmail(id, title, suffix)
{
    var urname = $("#urname" + suffix).val();
	if (!urname)
	{
		$('#name_error').show();
		return;
	}
	$('#name_error').hide();
	
    var email = $("#email" + suffix).val();
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (!email || reg.test(email) == false)
	{
		$('#email_error').show();
		return;
	}
	$('#email_error').hide();
	
    var remarks = $("#remarks" + suffix).val();

	var fn_email = document.getElementById("fn_email" + suffix).value.replace(/\n/ig, ",");
	fn_email = fn_email.replace(/ /ig, "");
	if (!fn_email || fn_email.match("/(friend1@example\.com)|(friend2@example\.com)|(friend3@example\.com)/ig"))
	{
		$('#recipient_error').show();
		return;
	}

	var right_emails = true;
	var fn_emails = fn_email.split(/[\n,]/ig);

	for (i in fn_emails)
	{
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(fn_emails[i]) == false) right_emails = false;
	}

	if (!right_emails)
	{
		$('#recipient_error').show();
		return;
	}

	$('#recipient_error').hide();
    var em = $("#em" + suffix).val();

    var url = "/postemail_header.php?post_id=" + id +
                                    "&post_title=" + title +
                                    "&urname=" + urname +
                                    "&email=" + email +
                                    "&remarks=" + remarks +
                                    "&fn_email=" + fn_email +
                                    "&em=" + em;

    $.ajax({url: city_url + url,
		type:"GET",
		success:function(res)
		{
			$("#email_responce").html('<div class="gallery-notice-box">A message has been sent to the following addresses:</div>');
			$("#email_responce").append(res);

			var footer_margin = $('.advBottom').css('margin-top');
			var form_height = $('#email_form1').outerHeight();

			$("#email_form1").hide();
			$("#email_responce").show();
			var response_height = $("#email_responce")[0].offsetHeight;
			$('.advBottom').css('margin-top', (parseInt(footer_margin) - parseInt(form_height)) + parseInt(response_height) + 'px');
		}});
}

function openEmailForm1()
{
	$('#name_error').hide();
	$('#email_error').hide();
	$('#recipient_error').hide();

	document.getElementById("urname_up"). value="";
	document.getElementById("email_up"). value="";
	document.getElementById("remarks_up"). value="";
	document.getElementById("fn_email_up"). value="";
	document.getElementById("responce_up"). innerHTML="";
	document.getElementById("email_form_up").style.display="inline";
	document.getElementById("responce_up").style.display="none";
	if(document.getElementById('email_form1').style.display == 'none') {
		document.getElementById('email_form1').style.display = 'block';
	}
	
	InputHelperCreate("#fn_email_up", "friend1@example.com\nfriend2@example.com\nfriend3@example.com");
	return false;
}

jQuery(document).ready(function() {
    var analyticsOutboundPrefix = '/ga_outbound_prefix/';
    var analyticsDownloadsPrefix = '/ga_downloads_prefix/';
    var analyticsFileTypes = ['mp3'];
    var analyticsEventTracking = 'enabled';
    
    /* ga_downloads
    ga_outbound*/

    jQuery('a').each(function() {
        var a = jQuery(this);
        var href = a.attr('href');
		
        // Check if the a tag has a href, if not, stop for the current link
        if ( href == undefined )
            return;
		
        var url = href.replace('http://','').replace('https://','');
        var hrefArray = href.split('.').reverse();
        var extension = hrefArray[0].toLowerCase();
        var hrefArray = href.split('/').reverse();
        var domain = hrefArray[2];
        var downloadTracked = false;
	
        // If the link is a download
        if (jQuery.inArray(extension,analyticsFileTypes) != -1) {
            // Mark the link as already tracked
            downloadTracked = true;
			
            // Add the tracking code
            a.click(function() {
                if ( analyticsEventTracking == 'enabled' ) {
                    _gaq.push(['_trackEvent', 'Downloads', extension.toUpperCase(), href]);
                } else
                    _gaq.push(['_trackPageview', analyticsDownloadsPrefix + url]);
            });
        }
		
        // If the link is external
        if ( ( href.match(/^http/) ) && ( !href.match(document.domain) ) && ( downloadTracked == false ) ) {
            // Add the tracking code
            a.click(function() {
                if ( analyticsEventTracking == 'enabled' ) {
                    _gaq.push(['_trackEvent', 'Outbound Traffic', href.match(/:\/\/(.[^/]+)/)[1], href]);
                } else
                    _gaq.push(['_trackPageview', analyticsOutboundPrefix + url]);
            });
        }
    });

});

function expandAboutUsSection(category)
{
    var link_value = $('#' + category + '_link').html();
    
    if (link_value == 'Expand')
    {
        $('#' + category + '_block').css({'display':'block'});
        $('#' + category + '_link').html('Collapse');
        
        var footer_margin = $('.advBottom').css('margin-top');
        var section_height = $('#' + category + '_block').outerHeight();

        $('.advBottom').css('margin-top', (parseInt(footer_margin) + parseInt(section_height)) + 'px');
    }
    else
    {
        var section_height = $('#' + category + '_block').outerHeight();
        
        $('#' + category + '_block').css({'display':'none'});
        $('#' + category + '_link').html('Expand');

        var footer_margin = $('.advBottom').css('margin-top');        

        $('.advBottom').css('margin-top', (parseInt(footer_margin) - parseInt(section_height)) + 'px');
    }
}

function TwitterCallback(data)
{
    /*if (data.count > 0) 
    {
        $(".tweet-button").each(function(){
            if($(this).attr("url")==data.url)
            {
                $(this).css({'margin-top':'0'}).addClass("no-zero-tweet");
            }
        })
    }*/
    if (data.count > 0) 
    {
        $(".tweet-button").each(function(){
            if($(this).attr("url")==data.url)
            {
                if($(this).hasClass('mp_tweet'))
                {
                    $(this).css({'width':'auto', 'overflow':'visible','margin-right':'-30px'});
                }
                else
                {
                $(this).css({'margin-top':'0px'}).addClass("no-zero-tweet");
                $(this).parent().css('margin-top','0px');
                if($(this).parent().css("margin-right")=="10px")
                {
                    if($(this).parent().next().hasClass("no-zero-fb"))
                    {
                        
                    }
                    else
                    {
                        $(this).parent().next().css('margin-top','44px');
                        $(this).parent().next().find('.fb-like-btn').css("margin-top","-42px");
                    }
                }
            }
            }
        })
    }
}

function signupValidator()
{    
    if ($('.snemail').val() == '' || !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('.snemail').val()))) return false;

    return true;
}

function validateInviteByForm()
{
    var fn_email = document.getElementById("invite_friends").value.replace(/\n/ig, ",");
    fn_email = fn_email.replace(/ /ig, "");
    if (!fn_email || fn_email.match("/(friend1@example\.com)|(friend2@example\.com)|(friend3@example\.com)/ig"))
    {
            $('#invite-by-error').html('Please, enter valid emails.');
            return;
    }

    var right_emails = true;
    var fn_emails = fn_email.split(/[\n,]/ig);

    for (i in fn_emails)
    {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if(reg.test(fn_emails[i]) == false) right_emails = false;
    }

    if (!right_emails)
    {
            $('#invite-by-error').html('Please, enter valid emails.');
            return;
    }

    document.InviteByEmail.submit();
}

function reloadAdvertisement()
{
    topAdvHolder = $('#topAdvertisementTagWidget');
    if(topAdvHolder.length != 0){
       topAdvHolder.children().remove();
      $('<iframe src="/ads.php?tag=' + adTag + '_Top_728x90&id=topAdvertisementTagWidget" style="width:728px; height: 90px; padding:0px; margin:0px;border:0px;overflow:hidden;"></iframe>').appendTo(topAdvHolder);
    }
    rightAdvHolder = $('#topRightAdvertisementTagWidget');
    if(rightAdvHolder.length != 0){
       rightAdvHolder.children().remove();
       $('<iframe src="/ads.php?tag=' + adTag + '_Top_300x250&id=topRightAdvertisementTagWidget" style="width:300px; height: 250px; padding:0px; margin:0px;border:0px;overflow:hidden;"></iframe>').appendTo(rightAdvHolder);
    }
    bottomAdvHolder = $('#bottomAdvertisementTagWidget');
    if(bottomAdvHolder.length != 0){
       bottomAdvHolder.children().remove();
       $('<iframe onload="checkHeight()" src="/ads.php?tag=' + adTag + '_Bottom_728x90&id=bottomAdvertisementTagWidget" style="width:738px; height: 0px; padding:0px; margin:0px;border:0px;overflow:hidden;" scrolling="no" vspace="0" frameBorder="0" hspace="0"></iframe>').appendTo(bottomAdvHolder);
    }
    rightAdvHolder = $('#rightAdvertisementTagWidget');
    if(rightAdvHolder.length != 0){
       rightAdvHolder.children().remove();
       $('<iframe scrolling="no" onload="fixHeight(\'rightAd\')" id="rightAd" src="/ads.php?tag=' + adTag + '_Top_300x600&id=rightAdvertisementTagWidget" style="width:300px; height: 250px; padding:0px; margin:0px;border:0px;"></iframe>').appendTo(rightAdvHolder);
    }
    rightAdvHolder = $('#rightAdvertisementTagWidget2');
    if(rightAdvHolder.length != 0){
       rightAdvHolder.children().remove();
       $('<iframe src="/ads.php?tag=' + adTag + '_Top_300x250&id=rightAdvertisementTagWidget2" style="width:300px; height: 250px; padding:0px; margin:0px;border:0px;overflow:hidden;"></iframe>').appendTo(rightAdvHolder);
    }
}

function fixHeight(element_id, block_id)
{
    document.getElementById(element_id).style.height = document.getElementById(element_id).contentWindow.document.body.scrollHeight + 'px';
}

function reloadWPandGAStats(post_id)
{
    if(typeof st_go == 'function')
    {
        eval("local_st_go({blog:'"+blog_id+"', v:'ext', post:'"+post_id+"'});");
    }
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		$.getScript( gaJsHost + "google-analytics.com/ga.js", function () {
			try {
				var pageTracker = _gat._getTracker(gauaCode);
				pageTracker._trackPageview();
			} catch(err) {}
		});
}

function postCounter(post_type)
{
    if (typeof(id) !== 'undefined' && typeof(key) !== 'undefined')
    {
        var link_param = '';
        switch(post_type)
        {
            case 'post':
                link_param = '?post_type=post';
                break;
            case 'venue':
                link_param = '?post_type=venue';
                break;
            case 'event':
                link_param = '?post_type=event';
                break;
            case 'profile':
                link_param = '?post_type=profile';
                break;
            case 'gallery_album':
                link_param = '?post_type=gallery_album';
                break;
        }
        $.ajax({
                cache: false,
                url: '/post_counter.php'+link_param,
                dataType: "text",
                type: 'POST',
                data: {'id':id,'key':key},
                success:function(res){}
                });
    }
}
function showGoogleCounter(res)
{
    $('.google-button').css('margin-top', '0px');
}
function showGoogleCounterMobile(res)
{
    $('.google-button').css('width', '70px');
}

function checkHeight() {
//    adsIframe = $('body').find("#adsIframe");
    bottomAdvHolder = $('#bottomAdvertisementTagWidget');
    var iframe = bottomAdvHolder.find("iframe");
    if (iframe.contents().find('a').length > 0 || iframe.contents().find('object').length > 0 ||
        iframe.contents().find('iframe').length >0 || iframe.contents().find('img').length > 0) {
        iframe.css("height", "90px");
    }else {
        iframe.css("height", "0px");
    }
}

function nextSlide(post_id, slide_id, link)
{
    $('.imageLoaderBg').show();
    $('.imageLoader').show();

    reloadAdvertisement();
    reloadWPandGAStats(post_id);

    $.ajax({
            url: '/ajax_slideshow_content.php',
            dataType: "json",
            type: 'POST',
            data: {'post_id':post_id,'slide_id':slide_id},
            success:function(res)
            {
                if (res.key) key = res.key;
                postCounter('post');
                
                $('.active-slide').removeClass('active-slide');
                $('#slide-' + slide_id).addClass('active-slide');
                $('.prev-slide a').show();
                $('#slide-number').html(parseInt($('#slide-number').html()) + 1);
                if (res.next_id)
                {
                    var new_href = $(link).attr('href').replace(/slide=\d+$/, 'slide=' + res.next_id);
                    $(link).attr({'id':res.next_id, 'href':new_href});
                }
                else $(link).hide();

                if (res.prev_id)
                {
                    var new_href = $('.prev-slide a').attr('href').replace(/slide=\d+$/, 'slide=' + res.prev_id);
                    $('.prev-slide a').attr({'id':res.prev_id, 'href':new_href});
                }
                else $('.prev-slide a').hide();

                $('.slide-content').html(res.slide_content + '<div class="imageLoaderBg"></div><div class="imageLoader"></div>');

                $('.imageLoaderBg').hide();
                $('.imageLoader').hide();

                var slide_number = parseInt($('.active-slide').attr('jcarouselindex'));
                var total_slides = parseInt($('.slide-title b').html());
                
                jQuery('#mycarousel').jcarousel('next');
                var post_url = $('#post_url').html();
                var histAPI = !!(window.history && history.pushState);
                if (histAPI) history.pushState(null, null, post_url+"&slide="+slide_id);
            }
    });
}
function prevSlide(post_id, slide_id, link)
{
    $('.imageLoaderBg').show();
        $('.imageLoader').show();

        reloadAdvertisement();
        
        reloadWPandGAStats(post_id);

        $.ajax({
                url: '/ajax_slideshow_content.php',
                dataType: "json",
                type: 'POST',
                data: {'post_id':post_id,'slide_id':slide_id},
                success:function(res)
                {
                    if (res.key) key = res.key;
                    postCounter('post');
                                        
                    $('.active-slide').removeClass('active-slide');
                    $('#slide-' + slide_id).addClass('active-slide');
                    $('.next-slide a').show();
                    $('#slide-number').html(parseInt($('#slide-number').html()) - 1);
                    if (res.prev_id)
                    {
                        var new_href = $(link).attr('href').replace(/slide=\d+$/, 'slide=' + res.prev_id);
                        $(link).attr({'id':res.prev_id, 'href':new_href});
                    }
                    else $(link).hide();

                    if (res.next_id)
                    {
                        var new_href = $('.next-slide a').attr('href').replace(/slide=\d+$/, 'slide=' + res.next_id);
                        $('.next-slide a').attr({'id':res.next_id, 'href':new_href});
                    }
                    else $('.next-slide a').hide();

                    $('.slide-content').html(res.slide_content + '<div class="imageLoaderBg"></div><div class="imageLoader"></div>');

                    $('.imageLoaderBg').hide();
                    $('.imageLoader').hide();

                    var slide_number = parseInt($('.active-slide').attr('jcarouselindex'));
                    var total_slides = parseInt($('.slide-title b').html());                    
                    
                    jQuery('#mycarousel').jcarousel('prev');
                    var post_url = $('#post_url').html();
                    var histAPI = !!(window.history && history.pushState);
                    if (histAPI) history.pushState(null, null, post_url+"&slide="+slide_id);
                }
        });
}
function local_st_go(a){var i,u=document.location.protocol+'//stats.wordpress.com/g.gif?host='+escape(document.location.host)+'&rand='+Math.random();for(i in a){u=u+'&'+i+'='+escape(a[i]);}u=u+'&ref='+escape(document.referrer);pingImg = new Image();pingImg.alt="";pingImg.src=u;}
