function albumPaginate(selectedDate) {
	window.location = "/galleries/date/" + selectedDate;
}

var Gallery = function(photoId, album, citysite, page, requestDir){
    var self = this;
    self.currentPhotoUrl = window.location.href;
    self.currentPhotoId = photoId;
    self.currentAlbum = album;    
    self.tmpCurrentPhotoUrl = false;
    self.currentPhotoCitySite = citysite;
    self.currentTPage = page;
    return {
        addTips: function(){
          var tipContent = '<strong>Did You Know?</strong><span>You can now move back-and-forth between images using the arrow keys<br/>on your keyboard. Give it a try!</span>';
          var l_tip = '<div class="arrTips" id="lTip">'+tipContent+'</div>';
          var r_tip = '<div class="arrTips" id="rTip">'+tipContent+'</div>';
          $("#prevNavLinkH").after(l_tip);
          $("#nextNavLinkH").after(r_tip);
          $(".galleryPhotoC").hover(function(){
              $(this).next(".arrTips").fadeIn(100);
          }, function(){
              $(this).next(".arrTips").fadeOut(100);
          })
        },
        ajax_change_page : function(sender, ref, loading){
            if(!ref) {
                self.tmpCurrentPhotoUrl = sender.href;
                $('.imageLoaderBg').show();
                $('.imageLoader').show();
            } else {
                self.tmpCurrentPhotoUrl = ref;
                if (loading) {
                        $('.imageLoaderBg').show();
                        $('.imageLoader').show();
                }
            }
            //$('.largeImage').hide();
            caller = this;
            $.ajax({url: city_url + requestDir + 'change_page_ajax.php',
                type:"POST",
                data:"ajax=1&oldTPage="+self.currentTPage+"&imgurl="+self.tmpCurrentPhotoUrl,
                dataType:"json",
                success:function (res){
                    /*var objStr = '';
                    for (var k in res) {
                        objStr+=k+':'+res[k]+'\r\n';
                    }*/
                    //alert(objStr);
                    if (res.key) key = res.key;
                    if(res.currentProfileId)
                    {
                        id = res.currentProfileId;
                        postCounter('profile');
                    }
                    if(res.album_id)
                    {
                        id = res.album_id;
                        postCounter('gallery_album');
                    }
                    if(res.img){
                        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);
                        }
                        if(res.neighbours.prev){
                            $('#prevNavLinkHolder').show();
                            $('#prevNavLinkHolder a').attr("href",res.neighbours.prev);
                            $('#prevNavLinkH').show();
                            $('#prevNavLinkH a').attr("href",res.neighbours.prev);
                        }
                        else
                        {
                            $('#prevNavLinkHolder').hide();
                            $('#prevNavLinkH').hide();
                        }
                        var img = $('.largeImage');
                        if(res.neighbours.next){
                            $('#nextNavLinkHolder').show();
                            $('#nextNavLinkH').show();
                            //                            $('#largeImageCopy').remove();
                            $('#nextNavLinkHolder a').attr("href",res.neighbours.next);
                            $('#nextNavLinkH a').attr("href",res.neighbours.next);
                            if ($(img).parent()[0].tagName == 'DIV' /*$(img).parent().attr('nodeName') == 'DIV'*/) {
                                var hrf = $('<A>');//document.createElement('a');
                                hrf.attr("href", res.neighbours.next);
                                $(img).before(hrf);
                                hrf.append(img);
                                hrf.bind('click', function() {
                                    gl.ajax_change_page(this);
                                    return false;
                                });
                            } else {
                                $(img).parent().attr("href", res.neighbours.next);
                            }
                        }
                        else
                        {
                            $('#nextNavLinkHolder').hide();
                            $('#nextNavLinkH').hide();
                            if ($(img).parent()[0].tagName == 'A' /*$(img).parent().attr('nodeName') != 'DIV'*/)
                            {
                                var a = img.parent();
                                var p = img.parent().parent();
                                a.remove();
                                p.append(img);
                            }
                        }
                        
                        // hide/show "get hi-res photo"
                        if (res.img.have_hires == 0) {
                            $('.buy-link').remove();
                        } else {
                            var hl = $('<a class="buy-link" href="#" onclick="openBuyHireForm(\'buy\'); return false;">GET HI-RES VERSION</a>');
                            hl.insertBefore($('.hire-link'));
                        }
                        
                        $('#galleryTopNav').html(res.nav_top);

                        var nImg = new Image();
                        $(nImg).load(function () {
                            $('.imageLoaderBg').hide();
                            $('.imageLoader').hide();
                            
                            $('img.largeImage').attr({'width':res.img.w, 'height':res.img.h, 'src':res.img.src, 'title':res.img.tag_title, 'alt':res.img.tag_title});
                            $('.large_photo-block').css({'height':res.img.h, 'width':res.img.w});
                            
                            if (res.img.h) { 
                                $('div.seoContent').height(res.img.h + 253); 
                            };
                            
                            if ($.browser.msie && $.browser.version.substr(0,1)<7) {
                                $('.imageLoaderBg').css('height',$('.large_photo a img').outerHeight()+"px");
                                $('.imageLoader').css('height',$('.large_photo a img').outerHeight()+"px");
                            }
                        }).attr('src', res.img.src);

                        /* new social buttons reloader*/
                        var tumblr_description = '<img src="' + document.domain + res.img.src + '" alt="' + (res.img.tag_title || '') + '" /><br />'+ (res.img.tag_title || '');
                        $($('.big-margin').eq(3)).html('<a href="http://www.tumblr.com/share/link?url=' + encodeURIComponent(res.img.url) +
                                                  '&name=' + encodeURIComponent(res.title) +'&description=' + encodeURIComponent(tumblr_description) + ' title="Share on Tumblr" style="display:inline-block; text-indent:-9999px; overflow:hidden; width:62px; height:20px; background:url(\'http://platform.tumblr.com/v1/share_2.png\') top left no-repeat transparent;">Share on Tumblr</a>');
                        $($(".big-margin").eq(4)).find("iframe").attr("src","http://www.stumbleupon.com/badge/embed/5/?url="+res.img.url);
                        /*$.getScript('http://www.stumbleupon.com/hostedbadge.php?s=5&r='+res.img.url, function(data, textStatus){
                            alert(data);
                        });*/
                        $(".google-button").html('<g:plusone size="tall" callback="showGoogleCounter" href="'+res.img.url+'"></g:plusone>');
                        gapi.plusone.go();
                        $('.fb-like-btn').each(function() {
                            $(this).html('');
                            $(this).append('<div class="connect_widget_text" url="'+res.img.url+'" style="display: none;"></div>');
                            $(this).append('<fb:like locale="en_US" height="21" colorscheme="light" font="arial" action="like" width="46px" show_faces="false" layout="box_count" href="'+res.img.url+'" class="fb_edge_widget_with_comment fb_iframe_widget"></fb:like>');
                            FB.init({appId: 'f8cd762f0462f0df07b2e6a9411e5149', status: true, cookie: true, xfbml: true});
                            FB.Event.subscribe('edge.create', function(href, widget) 
                             {
                                $("div.connect_widget_text").each(function(){
                                    if($(this).attr("url")==href)
                                    {
                                        /*var obj = 'div.connect_widget_text[url=' + href + ']';*/
                                        var obj = $(this);
                                        $(obj).parent().css({'margin-top':'2px', 'position':'absolute', 'overflow':'visible'});
                                        $(obj).parent().parent().css({'margin-top':'auto'});
                                        $(obj).parent().parent().css({'height':'60px', 'width':'46px'});
                                    }
                                })
                             });
                             var fb_urls = '';
                            $('.connect_widget_text').each(function ()
                            {
                                fb_urls += '"' + $(this).attr('url') + '",';
                            });

                            fb_urls = fb_urls.slice(0, -1);
                            FB.api(
                              {
                                method: 'fql.query',
                                query: 'SELECT total_count FROM link_stat WHERE url IN (' + fb_urls +')'
                              },
                              function(response)
                              {
                                $('.connect_widget_text').each(function (i)
                                {
                                   if (response[i].total_count > 0)
                                   {
                                        $(this).parent().css({'margin-top': '2px', 'overflow':'visible'});
                                   }
                                   else
                                   {
                                       $(this).parent().css({'margin-top': '-42px', 'overflow':'hidden'});
                                   }
                                });
                              }
                            );
                        });
                        
                        var tweeter_via = 'guestofaguest';
                        if (res.city == 2) tweeter_via = 'gofgLA';
                        if (res.city == 1) tweeter_via = 'gofgHamptons';
                        if (res.city == 4) tweeter_via = 'gofgDC';
                        
                        $(".tweet-button").attr("url",res.img.url);
                        $(".tweet-button").html('<a href="http://twitter.com/share" class="twitter-share-button" data-url="' + res.img.url + '" data-via="' + tweeter_via + '" data-text="' + res.title + '" data-count="vertical">Tweet</a>');
                        
                        if($('.twitter-share-button').length > 0)
                        {
                            $.getScript('http://platform.twitter.com/widgets.js');
                            //$.getScript('http://urls.api.twitter.com/1/urls/count.json?url='+encodeURIComponent(res.img.url)+'&callback=TwitterCallback');
                        }
                        
                        try
                        {
                            activate_share_on_tumblr_buttons();
                        } catch(e) {}

                        document.title = res.title;
                        buildcomments(res.comments);
                        if(res.img.o_tag){
                            if (res.img.tag) $(".tag-text-tags").html('L-R: ' + res.img.tag).show();
                            else $(".tag-text-tags").html('');
                            $(".tags_photo_overlay").remove();
                            $(".tag-text-controls").show();
                            $(".large_photo-block").html($(".large_photo-block").html() + res.img.o_tag);
                            $('#controlsWithTag').html(res.tagged_details).show();
                            $('#controlsWithNoTag').hide();
                            $('#album_tag').html(res.img.tag_text);
                            $('#pink_tag').hide();
                        }else{
                            $('#o_tag').remove();
                            $(".tag-text-tags").hide();
                            $(".tag-text-controls").hide();
                            $('#controlsWithTag').hide();
                            $('#controlsWithNoTag').show();
                            $('#pink_tag').show();
                        }
                        $('#tag_text').show();

                        $("#comments_div").hide();
                        $("#tag_div").hide();
                        $("#album_tag").text(res.tag_title);
                        $("#tagControls").show();
                        $("#tagMessage").hide();
                        $("#commentControls").show();
                        $("#commentMessage").hide();
                        var fb_meta = $("meta[property]");
                        fb_meta[0]['content'] = res.title;
                        fb_meta[1]['content'] = res.img.tag;
                        fb_meta[2]['content'] = res.img.src;
                        
                        if(res.img.id)
                            self.currentPhotoId = res.img.id;
                        if(res.img.post_id) {
                            self.currentPostId = res.img.post_id;
                        } else {
                            self.currentPostId = 0;
                        }
                        if (self.currentPostId > 0) {
                            if(res.img.profile_photo_id)
                                self.currentProfilePhotoId = res.img.profile_photo_id;
                        } else {
                            self.currentProfilePhotoId = self.currentPhotoId;
                        }
                        self.currentPhotoUrl = res.img.url;
                        //--- ping GA, quantcast and WP statistic
                        (function (url) {
                            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(url);
                            } catch(err) {}
                            });
                        })(self.currentPhotoUrl);
                        if(res.statsArray)
                            if(typeof st_go == 'function' && res.statsArray){
                                eval("local_st_go({"+res.statsArray+"});");
                            }
                        if(typeof _qoptions !== 'undefined'){
                           _qpixelsent = undefined;
                           local_quantserve(self.currentPhotoUrl);
                        }
                        //--- ping GA, quantcast and WP statistic
                        if(res.currentSiteId) self.currentSiteId = res.currentSiteId;
                        if(res.currentProfileName) self.currentProfileName = res.currentProfileName;
                        if(res.currentProfileId) self.currentProfileId = res.currentProfileId;
                        if(res.currentAlbumId) self.currentAlbum = res.currentAlbumId;
                        $('#email_gallery_photo_responce').hide();
                        $('#email_gallery_photo_form').hide();
                        $('#commentTextArea').val('').blur();
						var per_row = 46;
						var currentPhotoUrl = res.img.url;
						rows = Math.floor(currentPhotoUrl.length/per_row);
						var link = '';
						for (var c = 0; c < rows; c++)
						{
							link += currentPhotoUrl.substr(c * per_row, per_row) + "<br/>";
						}
						link += currentPhotoUrl.substr(c * per_row, per_row);
                        $('.sb-white a').attr('href', res.img.url).html(link);
                        self.currentPhotoCitySite = res.img.city;
                        self.currentTPage = res.page;
                        caller.preloadImg(res.neighbours);
                        
                    }
                    if(res.thumbsPager) {
                        $('#sb-pager-holder').html(res.thumbsPager);
                    } else {
                        var classname = $('img.sb-curr').attr('class');
                        $('img.sb-curr').removeClass();
                        $('#thumb-'+self.currentProfilePhotoId + '-' + self.currentPostId).addClass(classname);
                    }

					$('a[name=fb_share]').attr('href', 'http://www.facebook.com/sharer.php?u=' + res.img.url + '&t=' + res.title);
                },
                error:function (a, b){
                    var c = 1;
                }
            });
        },
        submitTag : function(){                    
                    var tag = document.getElementById("album_tag").value;
                    var url = "/addAltTag.php?album="+self.currentAlbum+"&photo="+self.currentPhotoId+"&tag="+tag;
                    $.ajax({url: city_url + url,
                            type:"GET",
                        success:function(res){
                            $("#tagControls").css('display', 'none');
                            $("#tagMessage").html(res).css('display', 'block');
                        }});
       },
       submitPeopleComments : function(){
	var tag = document.getElementById("commentTextArea").value;
	if(tag == "Anonymous...please be nice (or it won't be accepted!)") {
		return false;
	}
	var url = "/addImageComments.php?photo="+self.currentPhotoId+"&tag="+tag+"&citysite=" + self.currentPhotoCitySite;
	 $.ajax({url: city_url + url,
                type:"GET",
                success:function(res){
                    document.getElementById("commentControls").style.display = 'none';
                    ta = document.getElementById("commentTextArea");
                    document.getElementById("commentMessage").style.display = 'block';
                    document.getElementById("commentMessage").innerHTML = res;
                }});	
        },
        submitComments : function(){
            var tag = document.getElementById("commentTextArea"). value;
            if(tag == "Anonymous...please be nice(or it won't be accepted!)") {
                    return false;
            }
            var url = "/addImageComments.php?photo="+self.currentPhotoId+"&tag="+tag + "&citysite=" + self.currentPhotoCitySite;
            $.ajax({url: city_url + url,
                    type:"GET",
                    success:function(res){
                        $("#commentControls").hide();                        
                        $("#commentMessage").html(res).show();

                    }});
        },
        submitPhotoComment : function(id) {	
            var tag = document.getElementById("commentTextArea"+id). value;
            if(tag == "Anonymous...please be nice(or it won't be accepted!)") {
                    return false;
            }
            var url = "/addImageComments.php?photo="+self.currentPhotoId+"&tag="+tag+"&citysite="+self.currentPhotoCitySite;
            $.ajax({url: city_url + url,
                    type:"GET",
                    success:function(res){
                        document.getElementById("commentsFormDiv"+id).innerHTML=res;
                    }});
        },
	submitGalleryPhotoEmail : function()
	{
		var urname = document.getElementById("email_gallery_photo_form_urname").value;
		if (!urname)
		{
			$('#name_error').show();
			return;
		}
		$('#name_error').hide();
		var email = document.getElementById("email_gallery_photo_form_email").value;
		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 = document.getElementById("email_gallery_photo_form_remarks").value;
		
		var fn_email = document.getElementById("email_gallery_photo_form_fn_email").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 = document.getElementById("email_gallery_photo_form_em").value;

		var url = "/emailFormAjax.php?album="+self.currentAlbum+"&photo="+self.currentPhotoId+"&urname="+urname+"&email="+email+"&remarks="+remarks+"&fn_email="+fn_email+"&em="+em;
                if (self.currentProfileId)
                    url += "&profile_id="+self.currentProfileId;
                if (self.currentProfileName)
                    url += "&profile_name="+self.currentProfileName;
		$.ajax({url: city_url + url,
                    type:"GET",
                    success:function(res)
					{
                        $("#email_gallery_photo_responce").html('<div class="gallery-notice-box">A message has been sent to the following addresses:</div>');
						$("#email_gallery_photo_responce").append(res);

						var footer_margin = $('.advBottom').css('margin-top');
						var form_height = $('#email_gallery_photo_form').outerHeight();

						$("#email_gallery_photo_form").hide();
						$("#email_gallery_photo_responce").show();
						var response_height = $("#email_gallery_photo_responce")[0].offsetHeight;
						$('.advBottom').css('margin-top', (parseInt(footer_margin) - parseInt(form_height)) + parseInt(response_height) + 'px');
                    }});		
	},
        setProfileId : function(profile_id, profile_name) {
            self.currentProfileId = profile_id;
            self.currentProfileName = profile_name;
            return true;
        },
        submitPeopleGalleryPhotoEmail : function()
        {

            photo = self.currentPhotoId;
            site_id = self.currentSiteId;
            profile_name = self.currentProfileName;
            profile_id = self.currentProfileId;
            album = self.currentAlbum;

            
            var urname = document.getElementById("email_gallery_photo_form_urname").value;
			if (!urname)
			{
				$('#name_error').show();
				return;
			}
			$('#name_error').hide();
			
            var email = document.getElementById("email_gallery_photo_form_email").value;
			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 = document.getElementById("email_gallery_photo_form_remarks").value;
            var fn_email = document.getElementById("email_gallery_photo_form_fn_email").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 = document.getElementById("email_gallery_photo_form_em").value;

            var url = '/emailFormAjax.php?photo='+photo+'&album='+album+'&site_id=0&profile_id='+profile_id+'&profile_name='+profile_name+"&urname="+urname+"&email="+email+"&remarks="+remarks+"&fn_email="+fn_email+"&em="+em;
            //alert(url);
            $.ajax({url: city_url + url,
                    type:"GET",
                    success:function(res){
                        document.getElementById("email_gallery_photo_responce").innerHTML=res;
                        document.getElementById("email_gallery_photo_form_content").style.display="none";
                        document.getElementById("email_gallery_photo_responce").style.display="inline";
                    }});            
        },
	submitGalleryEmail : function()
	{
		$('#flavor_pill_caption_bottom').show();
		var urname = document.getElementById("email_gallery_form_urname").value;
		if (!urname)
		{
			$('#name_error').show();
			return;
		}
		$('#name_error').hide();
		
		var email = document.getElementById("email_gallery_form_email").value;
		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 = document.getElementById("email_gallery_form_remarks").value;
		var fn_email = document.getElementById("email_gallery_form_fn_email").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 = document.getElementById("email_gallery_form_em").value;
		var url = "/emailFormAjax.php?album="+self.currentAlbum+"&urname="+urname+"&email="+email+"&remarks="+remarks+"&fn_email="+fn_email+"&em="+em;
		
		 $.ajax({url: city_url + url,
                    type:"GET",
                    success:function(res)
					{
						if (res.indexOf('error') < 0)
						{
							$("#email_gallery_form_responce").html('<div class="gallery-notice-box">A message has been sent to the following addresses:</div>');
							$("#email_gallery_form_responce").append(res);
							$("#email_gallery_form_content").hide();
						}
						else
						{
							$("#email_gallery_form_responce").html(res);
						}
						$("#email_gallery_form_responce").show();
                    }});
	},
        sendBuyHireRequest : function(){
            var data = {};
            var error = false;
            var hireName = $('#hireName').val();
            var hireEmail = $('#hireEmail').val();
            var hireDay = $("#hireDay option")[$("#hireDay")[0].selectedIndex].value;
            var hireMonth = $("#hireMonth option")[$("#hireMonth")[0].selectedIndex].value;
            var hireYear = $("#hireYear option")[$("#hireYear")[0].selectedIndex].value;

            data['type'] = $('#buy-hire-type').val();

            if($.trim(hireName) == '') error = true;
            if($.trim(hireEmail) == '') error = true;
            if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(hireEmail))) error = true;
            if(data['type'] != 'buy')
            {
                if($.trim(hireDay) == '' ) error = true;
                if($.trim(hireMonth) == '') error = true;
                if($.trim(hireYear) == '') error = true;
                data['year'] = hireYear;
                data['month'] = hireMonth;
                data['day'] = hireDay;
            }

            if (error)
            {
                $('div.signerrormsg').show();
                return;
            }
            else $('div.signerrormsg').hide();

            data['name'] = hireName;
            data['email'] = hireEmail;
            data['url'] = self.currentPhotoUrl?self.currentPhotoUrl:document.location.href;
            $.ajax({
                 url: city_url + "/send_hire_request.php",
                 dataType: "text",
                 type: "POST",
                 data: data,
                 success: function (res)
                 {
                    if(res == 'OK')
                    {
                        $('#buy-hire-form').hide();
                        $('#buy-hire-confirm').show();
                    }
                    else $('div.signerrormsg').show();
                }
            });
        },        
        preloadImg : function(imgs){
           var html = '';
           if(imgs.prevImg) html += '<img src="'+imgs.prevImg+'" />';
           if(imgs.prevImg1) html += '<img src="'+imgs.prevImg1 +'" />';
           if(imgs.nextImg) html += '<img src="'+imgs.nextImg+'" />';
           if(imgs.nextImg1) html += '<img src="'+imgs.nextImg1 +'" />';            
           $('#imagesToPreload').html(html);
        },

        downloadHiRes: function() {
            data = {};
            data['photo_id'] = self.currentPhotoId;
            data['get_hires'] = 1;
            data['ajax'] = 1;
            $.ajax({
                url: self.currentPhotoUrl ? city_url + self.currentPhotoUrl : document.location.href,
                type:"POST",
                data: data,
                dataType:"json",
                success:function (res){
                    window.open(res.url);
                },
                error:function (res) {
                    alert(res.message);
                }
            });
            return false;
        },
        deletePhoto: function()  {
            if (!confirm('Are you sure to delete this photo?\nThis operation can not be undone!')) {
                return;
            }
            data = {};
            data['photo_id'] = self.currentPhotoId;
            data['photo_del'] = 1;
            data['ajax'] = 1;
            $.ajax({
                url: self.currentPhotoUrl ? city_url + self.currentPhotoUrl : document.location.href,
                type:"POST",
                data: data,
                dataType:"json",
                success:function (res){
                    zx = $('div.large_photo');
                    zx.append(res.message);
                    $('div#message').height($('div.large_photo').height()+135);
                },
                error:function (res) {
                    alert(res.message);
                }
            });
            return;
        },

        deleteProfile: function() {
            if (!confirm('Are you sure to delete this profile?\nThis operation can no be undone!')) {
                return;
            }
            var data = {};
            data['ajax'] = 1;
            data['profile_del'] = 1;
            $.ajax({
                url: self.currentPhotoUrl ? city_url + self.currentPhotoUrl : document.location.href,
                type: "POST",
                data: data,
                dataType: "json",
                success: function (res) {
                    zx = $('div.large_photo');
                    zx.append(res.message);
                    $('div#message').height($('div.large_photo').height()+135);
                    setTimeout('window.location = "/directory/"', 2000);
                },
                error: function (res) {
                    alert(res.message);
                }
            });
        }
    }
}
function openGalleryPhotoEmailForm()
{
        if($('#email_gallery_photo_form').css('display') == 'none')
		{
			$('#name_error').hide();
			$('#email_error').hide();
			$('#recipient_error').hide();
            //window.open('/emailForm.php?photo='+photo+'&album='+album,'EmailACopyOfThisAlbumPhotoToAFriend','width=500,height=500');
             $('#email_gallery_photo_form').find(':input').each(function() {
             $(this).val('');
            });
            //$('#flavor_pill_caption').hide();
            $('#email_gallery_photo_responce').hide();
            $('#email_gallery_photo_form_content').show();
            $('#email_gallery_photo_form').show();
            if($('#email_gallery_photo_form_fn_email')[0].nodeName == 'TEXTAREA')
			{
                InputHelperCreate("#email_gallery_photo_form_fn_email", "friend1@example.com\nfriend2@example.com\nfriend3@example.com");
			}
			//var footer_margin = $('.footer').css('margin-top');
			var form_height = $('#email_gallery_photo_form').outerHeight();
			
			//var new_margin = parseInt(footer_margin) + parseInt(form_height) + 'px';
			//$('.footer').css({'margin-top':new_margin});
            $(".advBottom").css('margin-top', 30 + parseInt(form_height) + 'px');
        }
		else
		{
            var footer_margin = $('.advBottom').css('margin-top');
			var form_height = $('#email_gallery_photo_form').outerHeight();
			$('#email_gallery_photo_form').hide();
            $(".advBottom").css('margin-top', (parseInt(footer_margin) - parseInt(form_height)) + 'px');
			//$('.footer').css('margin-top', (parseInt(footer_margin) - parseInt(form_height)) + 'px');
        }
}

function openGalleryAlbumEmailForm()
{
    if($('#email_gallery_form').css('display') == 'none')
	{	
		$('#name_error').hide();
		$('#email_error').hide();
		$('#recipient_error').hide();
		//window.open('/emailForm.php?album='+album,'EmailACopyOfThisAlbumToAFriend','width=500,height=500');
		$('#email_gallery_form').find(':input').each(function() {
			 $(this).val('');
		});
		//$('#flavor_pill_caption_bottom').hide();
		$('#email_gallery_responce').hide();
		$('#email_gallery_form_content').show();
		$('#email_gallery_form').show();        
        InputHelperCreate("#email_gallery_form_fn_email", "friend1@example.com\nfriend2@example.com\nfriend3@example.com");
    }
    else $('#email_gallery_form').hide();
}
function openTagDiv()
{
	if ($('#tag_div').css('display') == 'none')
	{
		$('#tag_div').show();
		if ($('#pink_tag').html()) $('#pink_tag').hide();
		else $('#tag_text').hide();

		//var footer_margin = $('.footer').css('margin-top');
		var tag_height = ($('#tag_div').next().attr('class') == 'pink-box') ? '120' : '35';
        $(".advBottom").css('margin-top', 30 + parseInt(tag_height) + 'px');
		//$('.footer').css('margin-top', parseInt(footer_margin) + parseInt(tag_height) + 'px');

		return false;
	}
	else closeTagDiv();
}

function closeTagDiv()
{
	$('#tag_div').hide();
	if ($('#pink_tag').html())
        {
            if ($('.tag-text-controls').css('display') == 'none') $('#pink_tag').show();
        }
	else $('#tag_text').show();

	var footer_margin = $('.advBottom').css('margin-top');
	var tag_height = ($('#tag_div').next().attr('class') == 'pink-box') ? '120' : '35';
    $(".advBottom").css('margin-top', (parseInt(footer_margin) - parseInt(tag_height))  + 'px');
	//$('.footer').css('margin-top', (parseInt(footer_margin) - parseInt(tag_height)) + 'px');
}

function buildcomments(data){
    if(data && data != ''){
        var html = '';
        $("#comments").show();
        html = '<table width="100%" cellspacing="0" id="commentstable">';
        var i = 0;
        comment = data[i];
        while(comment) {
            html += '<tr><td width="190" valign="top">';
            html += comment.date+ "<br /><span class='blue'>"+ comment.time +"</span>";
            html += '</td><td valign="top">';
            html += comment.comment;
            html += '</td></tr>';
            comment = data[++i];
        }
        html += "</table>";
        $("#comments").html(html);
    }
    else
        $("#comments").hide();
}
function closeCommentDiv() {
	document.getElementById('comments_div').style.display = 'none';
	document.getElementById('tag_text').style.display = 'block';
	return false;
}



function openCommentsDiv(){
	document.getElementById('comments_div').style.display = 'block';
	document.getElementById('tag_text').style.display = 'none';
	return false;
}
function displayExtraCommentsDiv(id) {
	if(document.getElementById("plusImage"+id).src == 'http://guestofaguest.com/wp-content/themes/2009GofG/images/plus_icon.jpg') {
		document.getElementById("extraCommentsDiv"+id).style.display = "inline";
		document.getElementById("plusImage"+id).src = "http://guestofaguest.com/wp-content/themes/2009GofG/images/gofg_8.jpg";
		
	} else {
		document.getElementById("extraCommentsDiv"+id).style.display = "none";
		document.getElementById("plusImage"+id).src = "http://guestofaguest.com/wp-content/themes/2009GofG/images/plus_icon.jpg";
	}
}
function displayCommentsForm(id) {
	if(document.getElementById("commentsFormDiv"+id).innerHTML  == "") {
		var txtArea="<p><textarea style='width:493px; height: 50px;' id='commentTextArea"+id+"' onfocus='if(this.value==\"Anonymous...please be nice (or it wont be accepted!)\") this.value = \"\";'>Anonymous...please be nice (or it wont be accepted!)</textarea></p>";
		var btn="<p style='padding-right: 10px; text-align: right;'><input class='icons icancel' type='button' onclick='displayCommentsForm(\""+id+"\");' return false;' value=''/>&nbsp;<input class='icons isubmit' type='button' onclick='submitPhotoComment(\""+id+"\");' value='' /></p>";
		document.getElementById("commentsFormDiv"+id).innerHTML = txtArea + btn;
		document.getElementById("commentsFormDiv"+id).style.display="block";
	} else {
		document.getElementById("commentsFormDiv"+id).innerHTML = "";
	}
}

function my_strip_anchor(my_url) {
    //alert(my_url);
    var getindex = my_url.indexOf('?');
    var hashindex = my_url.indexOf('#');
    var image_code = '';
    if (getindex > 0) {
        if (hashindex > 0 && hashindex > getindex) {image_code = my_url.substring(hashindex+1, my_url.length); /*alert('found image code! hashindex > getindex!' + image_code);*/}
        else if (hashindex > 0 && hashindex < getindex) {image_code = my_url.substring(hashindex+1, getindex);}
        else {image_code = my_url.substring(getindex+1, my_url.length);}
        my_url = my_url.substring(0,getindex) + '?' + image_code;
        /* alert('getindex processed: ' + my_url); */
    } else if (hashindex > 0) {
        image_code = my_url.substring(hashindex+1, my_url.length);
        my_url = my_url.substring(0,hashindex) + '?' + image_code;
        /* alert('hashindex processed:' + my_url); */
    }
    return my_url;
}

function openBuyHireForm(type)
{
    $('div.signerrormsg').hide();
    if($('#buy-hire-form').css('display') == 'none' && type)
	{
        $('#buy-hire-form').show();
        $('#buy-hire-confirm').hide();
		var footer_margin = $('.advBottom').css('margin-top');
		var form_height = $('#buy-hire-form')[0].offsetHeight;
		$('.advBottom').css('margin-top', parseInt(footer_margin) + parseInt(form_height) + 'px');
    }
	else
	{
        if($('#buy-hire-type').val() == type || !type)
		{
            var footer_margin = $('.advBottom').css('margin-top');
			var form_height = $('#buy-hire-form')[0].offsetHeight;
			$('.advBottom').css('margin-top', (parseInt(footer_margin) - parseInt(form_height)) + 'px');
			$('#buy-hire-form').hide();
            $('#buy-hire-confirm').hide();
        }
    }
    $('#buy-hire-type').val(type);
    $('.buy-link').removeClass('hire-link-opened');
    $('.hire-link').removeClass('hire-link-opened');
    if($('#buy-hire-form').css('display') == 'block')
        if(type == 'buy'){
            $('#timeframeholder').hide();
            $('.buy-link').addClass('hire-link-opened');
            $('.buy-hire-form-invite').show();
        }else if(type == 'hire'){
            $('#timeframeholder').show();
            $('.hire-link').addClass('hire-link-opened');
            $('.buy-hire-form-invite').hide();
        }     
}
var DaysInAMonth;
function checkDaysVisible(){
    if(!DaysInAMonth){
        DaysInAMonth = {'1':31, '2':28, '3':31, '4':30, '5':31, '6':30, '7':31, '8':31, '9':30, '10':31,'11':30, '12':31};
    }
    $('#hireDay option').show();
    selectedItem = $("#hireMonth")[0].selectedIndex;
    selectedYear = $("#hireYear option")[$("#hireYear")[0].selectedIndex].value;
    currentMonth = $("#hireMonth option")[selectedItem].value;
    if(currentMonth == '') 
        i = 31;
    else
        var i = DaysInAMonth[currentMonth];
    if(currentMonth == '2' && (selectedYear - 2008)%4 == 0)
        i++;
    i++;
    while(i <= 31){
        $('#hireDay' + i).hide();
        i++;
    }
}
function local_quantserve(ajax_url){
 var sr='',qo='',qm='',url='',ref='',je='u',ns='1',media='webpage',event='load';
 if(typeof _qoptions !="undefined" && _qoptions!=null){
 for(var k in _qoptions){
 if(typeof(_qoptions[k])!='string'){continue;}
 if(k=='qacct'){_qacct=_qoptions[k];}
 else{qo+=';'+k+'='+_qceuc(_qoptions[k]);}
 if(k=='media'){media=_qoptions[k];}
 if(k=='event'){event=_qoptions[k];}
 }
 _qoptions=null;
 }
 if((typeof _qacct =="undefined")||(_qacct.length==0))return;
 if(media=='webpage' && event=='load'){
 if((typeof _qpixelsent !="undefined")&&(_qpixelsent==_qacct))return;
 _qpixelsent=_qacct;}
 var ce=(navigator.cookieEnabled)?"1":"0";
 if(typeof navigator.javaEnabled !='undefined')je=(navigator.javaEnabled())?"1":"0";
 if(typeof _qmeta !="undefined" && _qmeta!=null){qm=';m='+_qceuc(_qmeta);_qmeta=null;}
 if(self.screen){sr=screen.width+"x"+screen.height+"x"+screen.colorDepth;}
 var d=new Date();
 var dst=_qcdst();






 var dg="E9546-W-MO-5";
 var qs="http://pixel.quantserve.com";
 var fp=_qcsc(media);
 if(ajax_url)url=_qceuc(ajax_url);
 if(window.document && window.document.referrer)ref=_qceuc(window.document.referrer);
 if(self==top)ns='0';
 _qimg=new Image();
 _qimg.alt="";
 _qimg.src=qs+'/pixel'+';r='+r+fp+';ns='+ns+';url='+url+';ref='+ref+';ce='+ce+';je='+je+';sr='+sr+';dg='+dg+';dst='+dst+';et='+d.getTime()+';tzo='+d.getTimezoneOffset()+';a='+_qacct+qo+qm;
 _qimg.onload=function() {_qpxload();}
}

function deletePhoto() {
    if (!confirm('Are you sure to delete this photo?\nThis operation can not be undone!')) {
        return;
    }
    var data = {};
    data['photo_id'] = currentPhotoId;
    data['photo_del'] = 1;
    data['ajax'] = 1;
    $.ajax({
        url: currentPhotoUrl ? city_url + currentPhotoUrl : document.location.href,
        type:"POST",
        data:data,
        dataType:"json",
        success:function (res){
            $('div.large_photo').html(res.message);
        },
        error:function (res) {
            alert(res.message);
        }
    });
}

function deleteProfile() {
    if (!confirm('Are you sure to delete this profile?\nThis operation can no be undone!')) {
        return;
    }
    var data = {};
    data['ajax'] = 1;
    data['profile_del'] = 1;
    $.ajax({
        url: currentPhotoUrl ? city_url + currentPhotoUrl : document.location.href,
        type: "POST",
        data: data,
        dataType: "json",
        success: function (res) {
            window.location = '/directory/';
        },
        error: function (res) {
            alert(res.message);
        }
    });
}

