WebFont.load({
	google: {
  	families: [ 'Cantarell' ]
  }
});

overlayCreate = false;
overlayVis = false;
stopRotate = false;

sa1 = '<div class="blog-post-actions"><iframe id="blog_fb_like" src="http://www.facebook.com/plugins/like.php?href=';
sa2 = '&amp;send=false&amp;layout=button_count&amp;width=90&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe><a href="http://twitter.com/share" class="twitter-share-button" data-url="';
sa3 = '" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>';

$(document).ready(function() {

	cityId = $('#city_id_holder').text();
	cityName = $('#city_name_holder').text();
	cityUrl = $('#city_url_holder').text();
	
	currUrl = $.url.attr('source');
	if (currUrl.indexOf('/user') == -1) {
		$.cookie('ct-signin-url', null, { path: '/', domain: $.url.attr('host') });
		$.cookie('ct-signin-url', currUrl, { path: '/', domain: $.url.attr('host') });
	}
	
	//Check for at cookie, show appropriate nav user msg
	checkAtCookie();
	
	//Rotator
		//init
	$('.rotator-item:first').addClass('active');
	$('.rotator-item').each(function(i) {
		i++;
		bgImg = $(this).attr('rotator-img');
		$(this).attr('style', 'background:url('+bgImg+')');
		$(this).addClass('r'+i);
		$('.rotator-num').append('<li class="r'+i+'">'+i+'</li>');
	});
	$('.rotator-num li:first').addClass('active');
	rNum = $('.rotator').children().size() - 1;
	rCount = 1;
	setInterval("rotateRotator()", 8000);
		//arrows
	$('.rotator-arw').click(function() {
		stopRotate = true;
		if ($(this).hasClass('rotator-prev')) {
			rotateRotator(true, true);
		} else {
			rotateRotator(true);
		}
	});
		//numbers
	$('.rotator-num li').click(function() {
		stopRotate = true;
		rotateRotator(true, false, $(this).text());
	});
	
	//Breadcrumbs
	$('.bread-page').text($('h1').text());
		
  //Blogs
	$('.Blog_AddToWatchlist a').addClass("plk-btn");
	$('.PersonaBlog_TableLeft').addClass('blog-col');
	$('.Comments_Table').before('<a name="comments"></a><h2 class="comments-head">Comments</h2>');
	
	$('td.BlogMain_MabAuthTableLeft').each(function() {
		userSrc = $('img.PluckUserAvatar', this).attr('src');
		if ((userSrc.indexOf('no-user-image.gif')) != -1 ) {
			$(this).addClass('no-user-img');
		}
	});
	
	$('.blog-home .teaser-container').each(function() {
		postUrl = $('.teaser-title a', this).attr('href');
		$('.teaser img', this).wrap('<a href='+postUrl+' />');
		$('.teaser', this).append(' <a href="'+postUrl+'">read more &raquo;</a>')
	});
	
	$('.blog-recent table.BlogMain_EntryPost').each(function() {
		$(this).wrap('<div class="teaser-img-pos" />');
		postUrl = $('div.BlogMain_EntryTitle a', this).attr('href');
		$('.teaser img', this).wrap('<a href='+postUrl+' />');
	});
	$('.blog-recent div.BlogMain_EntryContent').each(function() {
		readMore = $('a:last', this);
		$('.teaser', this).append(readMore);
	});
	
	$('#blog div.Blog_RightSideSectionHead:contains("Most Recent Tags")').text('Posts by City').parent().prependTo('td.PersonaBlog_TableRight');
	
		//move blog tag msg
	$('#blog_tag_msg').insertAfter('.BlogNav');
	
	
		//fb like + tweet buttons
	$('.blog-home .post-container').each(function() {
		saUrl = $('h2 a', this).attr('href');
		$('.teaser-by', this).after(sa1+saUrl+sa2+saUrl+sa3);
	});
	$('.blog-post-page table.BlogMain_MabAuthTable').after(sa1+currUrl+sa2+currUrl+sa3);
	
	//Forums
  $('#forumTitle').text('').show();
  $('.ForumList_ForumSpecificTitleTD h1').appendTo('#forumTitle');
	$('.DiscussionList_Admin').prepend('<span class="admin-label">ADMIN: </span>');
	$('.DiscussionList_Moderator').prepend('<span class="admin-label">MODERATE: </span>');
	
	$('a.Forums_StartDiscussion').text('Start a New Discussion');
	$('a.Forums_AddPost').text('Add a New Post');
	$('a.Forums_MarkAllRead').text('Mark All Posts as Read');
	$('a.Forums_RegisterToJoinForums').text('Register to Join Forums');
	
	$('#horz_nav .city-list').addClass('city-chooser-item');
	$('.city-chooser').click(function() {
		$('.city-chooser-item').toggleClass("choosing");
	});
		
	
	//Photos Pages
		//add url params to links
	if (cityId != '') {
		$('div.PublicGallery_PhotosContainer a').each(function() {
			appendUrl(this);
		});
		$('div.PublicGallery_Details a').each(function() {
			appendUrl(this);
		});
		$('table.GalleryPhoto_GalleryPreview a').each(function() {
			appendUrl(this);
		});
		appendUrl($('div.GalleryPhoto_Heading a'));
	}
	
	//Overlay
	$('.show-overlay').click(function() {
		o_id = $(this).attr('overlayid');
		showOverlay(o_id);
	});
	$('.close-overlay').click(function() {
		closeOverlay();
		if ($(this).hasClass('close-refresh')) {
			location.href = $.cookie('ct-signin-url');
		}
	});
	
	//Jump Menus
	$('.sel-jump-check').change(function(){
		jumpTo = $(this).val();
		if ((jumpTo != "0") && ($.cookie('at') != null)) {
			location.href = $(this).val();
		} 
		else if ($.cookie('at') == null) {
			$.cookie('ct-signin-url', jumpTo, { path: '/', domain: $.url.attr('host') });
			$('#user_sign_in').click();
		}
		
	})
	
	//Search
	$('form#frm_search').submit(function() {
		sQuery = $('#nav_search_input').val();
		location.href = 'http://1.camp.citypass.com:9001/citytraveler/search?searchQuery='+sQuery+'&searchPage=1';
		return false;
	});
	
	  //clear/replace pluck login links
	$('.Forums_LoginStatus a').each(function() {
		fText = $(this).text();
		if (fText == 'Log in') {
			$(this).attr('onclick', '$("#user_sign_in").click()');
		} else if (fText == 'Register') {
			$(this).attr('onclick', 'showOverlay("#login_overlay"); $("#login_create_link").click()');
		}
	});

    //user profile page
	$('.pluck-login-persona-submit-button').attr('onclick', '$("#user_sign_in").click()');
	
	//Sign out - remove 'at' cookie
	$('a.sign-out').click(function() {
		$.cookie('at', null, { path: '/', domain: '.citypass.com' });
		$.cookie('atUser', null, { path: '/', domain: '.citypass.com' });
		location.reload(true);
	});
	
	//Login
	$('.login-switch').click(function() {
		$('.login-section').addClass('login-hide');
		switchto = $(this).attr('switchto');
		$(switchto).removeClass('login-hide');
	});
	
	$('#ct_login').submit(function() {
		$.ajax({
			type: "GET",
			url: "/citytraveler/auth_citypass/login",
			data: $('#ct_login').serialize(),
			dataType: "json",
			success: function() {
				location.href = $.cookie('ct-signin-url');
			},
			error: function(response) {
				eTxt = jQuery.parseJSON(response.responseText).error;
				$('#ct_login_response').addClass('login-error').show();
				$('#ct_login_response').html(eTxt);
			}
		});
		return false;
	});
	
	$('#btn_create_account').click(function() {
		em = isValidEmailAddress($('#create_email').val());
		p1 = $('#create_password').val();
		p2 = $('#create_password_confirm').val();
		if (em == false) {
			alert("You must enter a valid email address.");
		} else if ( p1 != p2 ) {
			alert("Passwords do not match.  Please re-enter.");
			$('#create_password').val('');
			$('#create_password_confirm').val('');
		} else {
			$('#ct_create').submit();
		}
	});
	
	$('#ct_create').submit(function() {
	
			$.ajax({
				type: "POST",
				url: "/citytraveler/auth_citypass/create",
				data: $('#ct_create').serialize(),
				dataType: "json",
				success: function() {
					checkAtCookie();
					newUser = $.cookie('atUser');
					$('.close-overlay').addClass("close-refresh");
					$('.login-create').html('<h2>Welcome</h2><p>Your account is created.</p><p>You are logged in as: <b>'+userNameDisp(newUser)+'</b></p>');
				},
				error: function(response) {
					eTxt = jQuery.parseJSON(response.responseText).error;
					$('#ct_create_response').addClass('login-error').show();
					$('#ct_create_response').html(eTxt);
				}
			});

		return false;
	});
	
	$('#btn_reset_password').click(function() {
		em = isValidEmailAddress($('#reset_email').val());
		p1 = $('#reset_password').val();
		p2 = $('#reset_password_confirm').val();
		if (em == false) {
			alert("You must enter a valid email address.");
		}
        else if ( p1 != p2 ) {
			alert("Passwords do not match.  Please re-enter.");
			$('#reset_password').val('');
			$('#reset_password_confirm').val('');
		}
        else {
			$('#ct_reset').submit();
		}
	});
	
	$('#ct_reset').submit(function() {
	
			$.ajax({
				type: "POST",
				url: "/citytraveler/auth_citypass/reset",
				data: $('#ct_reset').serialize(),
				dataType: "json",
                success: function(data, textStatus, response) {
                    eTxt = jQuery.parseJSON(response.responseText).msg;
					$('#ct_reset_response').addClass('login-error').show().html(eTxt);
				},
				error: function(response) {
					eTxt = jQuery.parseJSON(response.responseText).error;
					$('#ct_reset_response').addClass('login-error').show().html(eTxt);
				}
			});

		return false;
	});

    if ($.cookie('at')) {
        $('input#reset_email').val(userEmail($.cookie('at')));
        $('#reset_email_display').html(userEmail($.cookie('at')));
    }
	
    $('#ct_forgot').submit(function(){

        var email = $('input#forgot_email').val();
        //console.log('here in click handler with ' + email);
        if (!isValidEmailAddress(email)) {
			alert("You must enter a valid email address.");
        }
        else {
            $.ajax({
                type: "GET",
                url: "/citytraveler/auth_citypass/remind",
                data: $('form#ct_forgot').serialize(),
                dataType: "json",
                success: function(data, textStatus, response) {
                    eTxt = jQuery.parseJSON(response.responseText).msg;
                    $('#ct_forgot_response').addClass('login-error').show().html(eTxt);
                },
                error: function(response){
                    eTxt = jQuery.parseJSON(response.responseText).error;
                    //console.log('response error: ' + eTxt);
                    $('#ct_forgot_response').addClass('login-error').show().html(eTxt);
                }
            });
        }

        return false;
    });

//Click Tracking
$('a[target=_blank]').each(function() {
	$(this).attr('track', $(this).attr('href'));
});
$('[track]').click(function() {
	trackLabel = $(this).attr('track');
	_gaq.push(['_trackEvent', "Community", trackLabel ]);
});

//End of document.ready
});

function checkAtCookie() {
	if ($.cookie('at') == null) {
		$('#msg_not_logged').show();
		$('#login_forgot_link').show();
		_gaq.push(['_setCustomVar', 3, 'CTLoggedIn', 'No', 2]);
	} else {
		$('a#user_logged').text(userNameDisp($.cookie('atUser'), '25'));		
		$('#msg_not_logged').hide();
		$('#msg_logged').show();
		$('#login_reset_link').show();
		$('#login_profile_reset').show();
		_gaq.push(['_setCustomVar', 3, 'CTLoggedIn', 'Yes', 2]);
	}
}

function userNameDisp(u, max) {
	matchIndex = u.indexOf('+');
	while (matchIndex != -1) { 
		u = u.replace('+', ' ');
		matchIndex = u.indexOf('+');
	}
	if (u.length <= 25) {
		return u;
	} else {
		return u.substring(0,24)+'...';
	}
}

function userEmail(u) {
    u = u.replace(/.*\&e=/, '');
    u = u.replace(/\&.*/, '');
    return u;
}

function rotateRotator(cl, back, navNum) {
	if((!stopRotate)||(cl)) {
		$('.rotator-item.r'+rCount).removeClass('active');
		$('.rotator-num li.r'+rCount).removeClass('active');
		if ((rCount == rNum)&&(!back)&&(!navNum)) { 
			rCount = 1; 
		} else if (back) {
			if(rCount != 1) { rCount = rCount-1; } else { rCount=rNum; }
		} else if (navNum) {
			rCount=navNum;
		}
		else { 
			rCount++ 
		}
		$('.rotator-item.r'+rCount).addClass('active');
		$('.rotator-num li.r'+rCount).addClass('active');
	}
	else { return false; }
}

function showOverlay(id) {
	$(id).show().appendTo('#overlay_content');
	ovrTop = ($('html').scrollTop() + 100);
	$('#overlay_box').css({ 'top' : ovrTop+'px' });
	$('.overlay-vis').show();
	overlayVis=true;
}
function closeOverlay() {
	$('.overlay-vis').hide();
	$('.overlay-content').hide().appendTo('body');
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

//add city variables to various links to keep navigation oriented to current city
function appendUrl(sel) {
	$(sel).attr('href', $(sel).attr('href')+'&city_id='+cityId+'&city_url='+cityUrl+'&city_name='+cityName);
}




