BB = {};
BB.unimplemented = function() {
	alert('This has not been implemented yet.');
};
BB.isDef = function(value) {
	return (typeof value !== 'undefined');
};
BB.bodyID = function(id, fn) {
	$(function() {
		if (!BB.isDef(BB.bodyID.value)) {
			BB.bodyID.value = $.findCache('body').attr('id');
		}
		if (BB.bodyID.value == id) {
			fn();
		}
	});
};
BB.bodyClass = function(klass, fn) {
	$(function() {
		if ($.findCache('body').is('.' + klass)) {
			fn();
		}
	});
};

function UserDataCookie() {
	this.COOKIE_NAME = 'imt_user_data';
	this.cookieHash = {};
	this.readCookie();
}
UserDataCookie.prototype.isLoggedIn = function() { 
	return this.cookieHash && !!this.cookieHash.user_id;
};
UserDataCookie.prototype.readCookie = function() {
	try {
		var cookieValue = $.cookie(this.COOKIE_NAME);
		if (!!cookieValue) {
			this.cookieHash = $.toJSON(cookieValue);
		}
	} catch (err) {
	}
	return this.cookieHash;
};
UserDataCookie.prototype.writeCookie = function(hash) {
	try {
		this.cookieHash = hash;
		$.cookie(this.COOKIE_NAME, $.jSONToString(hash));
	} catch (err) {
	}
};
$(function() {
	var udc = new UserDataCookie(), cookieHash = udc.cookieHash;
	if (!cookieHash) {
		return;
	}
	var isLoggedIn = udc.isLoggedIn();
	(function() {
		if (!isLoggedIn) {
			return;
		}
		var $userNav = $.findCache('#site-header .user-nav.signed-in'), $currentUser = $userNav
				.children('ul.current-user'), $currentUserLI = $currentUser
				.children('.current-user'), $nav = $userNav.children('ul.nav'), $navCommentsVotesLI = $nav
				.children('.comments-votes');
		$userNav.show().siblings('.signed-out').hide();
		$currentUserLI.html( [ '<a href="', cookieHash.edit_user_path, '">',
				cookieHash.username, '</a>' ].join(''));
		if (typeof userID !== 'undefined' && userID == cookieHash.user_id
				&& !!$('#users-show, #users-edit, #users-votes')[0]) {
			$currentUserLI.addClass('selected');
		}
		if (!!cookieHash.is_facebook_user) {
			$currentUser.children('.signout').addClass('fb-signout');
		}
		$nav.find('li.settings a').attr('href', cookieHash.settings_user_path);
		if (!!cookieHash.entered_competition) {
			$nav.find('li.entry a').attr('href', cookieHash.user_path);
		} else {
			$nav.children('.entry').hide();
		}
		if (cookieHash.unread_notifications_count > 0) {
			$navCommentsVotesLI.addClass('new');
			$navCommentsVotesLI.children('em').html(
					[ '(', cookieHash.unread_notifications_count, ')' ]
							.join('')).show();
		}
		$navCommentsVotesLI.children('a').attr('href',
				cookieHash.user_votes_path);
		if (cookieHash.voter_or_not_entered) {
			var $siteBody = $('#site-body'), $voterError = $('<div class="voter error"></div>');
			$voterError
					.append($('<p>Now the competition is over we\'d like to invite you to convert your voting profile to a full profile. All you need to do is upload your picture or video to the site, put in your birthday, where you live, and tell us something about yourself. It\'s that easy. Voting only profiles will be deleted on <strong>May 7th</strong>, so don\'t forget to convert your profile before this time.</p>'));
			if (cookieHash.user_voter) {
				$voterError
						.append($('<p>You can <a href="' + cookieHash.settings_user_path + '">update your settings here</a>.</p>'));
			} else {
				$voterError
						.append($('<p>You can <a href="' + cookieHash.edit_user_path + '">upload a photo or video here</a>.</p>'));
			}
			$siteBody.prepend($voterError);
		}
	})();
	if (!!$('#main-index')[0] && isLoggedIn) {
		$.findCache('a.signup').hide();
	}
});

$.ajaxSetup( {
	beforeSend : function(xhr) {
		xhr.setRequestHeader('Accept', 'text/javascript');
	}
});
function sendAjaxRequest(ev) {
	var $form = $(ev.target);
	$.ajax( {
		url : $form.attr("action"),
		type : $form.attr("method"),
		data : $form.serialize(),
		dataType : 'json',
		success : function(resp) {
			$().trigger(resp.trigger, resp.data);
		},
		error : function() {
			alert('Sorry, there was a problem with this request.');
		}
	});
	ev.preventDefault();
}
function getFacebookPermissions(redirect) {
	$.getJSON('/users/is_user_already.js', function(json) {
		if (json.success) {
			window.location = redirect;
		} else {
			FB.Connect.showPermissionDialog(
					'email, publish_stream, offline_access', function(perms) {
						window.location = redirect;
					});
		}
	});
}
$(function() {
	$('a[rel=external]').click(function(ev) {
		window.open(this.href);
		ev.preventDefault();
	});
	$('.datetime[title]')
			.each(
					function() {
						var $this = $(this), date = new Date($this
								.attr('title')), humanTime = $.trim($this
								.html());
						$this.relativeTimestamp(date);
						$this.attr('title', humanTime);
					});
	(function() {
		var $nav = $('#site-header div.user-nav.signed-in');
		if (!$nav[0]) {
			return;
		}
		var $searchForm = $nav.children('div.search-form');
		$nav.children('div.search').click(function(ev) {
			if ($searchForm.is(':visible')) {
				$searchForm.fadeOut('fast');
			} else {
				$searchForm.show();
				$searchForm.find('input[type=text]').focus();
			}
			ev.preventDefault();
		});
	})();
	$('.youtube').each(
			function() {
				var $this = $(this), flashID = $this.attr('id'), uuid = $this
						.attr('class').replace(/youtube /, '');
				new YouTube(uuid, 300, 243, flashID);
			});
	 $('.youtube_big').each(
              function() {
                                var $this = $(this), flashID = $this.attr('id'), uuid = $this
                                                .attr('class').replace(/youtube_big /, '');
                                new YouTube(uuid, 960, 564, flashID);
                        });
      (function() {
		var qtip_options = {
			style : {
				tip : {
					corner : 'topMiddle',
					size : {
						x : 9,
						y : 6
					}
				},
				border : {
					width : 0,
					radius : 0,
					color : '#000'
				},
				background : '#000',
				name : 'dark',
				textAlign : 'center'
			},
			position : {
				corner : {
					target : 'bottomMiddle',
					tooltip : 'topMiddle'
				},
				adjust : {
					screen : true
				}
			}
		};
		$('ul.nav a[title], ol.entries li form.delete').qtip(qtip_options);
		qtip_options.position.adjust = {
			y : 5
		};
		$('ul.networks a').qtip(qtip_options);
		(function($el) {
			if (!$el[0]) {
				return;
			}
			qtip_options.content = {
				text : $el
			};
			$el.qtip(qtip_options);
		})($.findCache('#users-edit div.basics div.image span.edit'));
		qtip_options.show = {
			when : {
				event : 'click'
			}
		};
		qtip_options.hide = {
			when : {
				event : 'click'
			}
		};
		(function($tooltipText) {
			if (!$tooltipText[0]) {
				return;
			}
			qtip_options.content = {
				text : $tooltipText
			};
			qtip_options.style.width = 400;
			$.findCache('#why-participate').click(function(ev) {
				ev.preventDefault();
			}).qtip(qtip_options);
		})($.findCache('#why-participate-text'));
		(function() {
			$.findCache('ul.questions li span.control')
					.each(
							function() {
								var $control = $(this);
								if (!$control[0]) {
									return;
								}
								var tooltipTextID = $control.parent().attr(
										'class') + '-text', $tooltipText = $
										.findCache('#' + tooltipTextID);
								if (!$tooltipText[0]) {
									return;
								}
								qtip_options.content = {
									text : $tooltipText
								};
								qtip_options.position.corner = {
									target : 'topMiddle',
									tooltip : 'bottomMiddle'
								};
								qtip_options.position.adjust = {
									y : -5
								};
								qtip_options.style.width = 350;
								qtip_options.style.tip.corner = 'bottomMiddle';
								$control.qtip(qtip_options);
							});
		})();
	})();
	(function() {
		if ($('fieldset.bio-fields').length > 0) {
			$('li.voter-entrant input').change(function() {
				if ($("li.voter-entrant input:checked").val() == 'entrant') {
					$('fieldset.bio-fields').fadeIn('fast');
				} else {
					$('fieldset.bio-fields').fadeOut('fast');
				}
			}).click(function() {
				$(this).change();
			});
		}
	})();
});
BB
		.bodyID(
				'main-index',
				function() {
					(function() {
						var showText, hideText, $content = $
								.findCache('.primary-content'), $cta = $
								.findCache('.cta'), $toggle;
						showText = 'Show people';
						hideText = 'Hide people';
						$toggle = $( [
								'<p class="toggle-primary-content" title="',
								hideText, '">', hideText, '</p>' ].join(''));
						$toggle.prependTo('.column-wrapper').toggle(
								function(ev) {
									$content.addClass('hidden');
									$cta.hide();
									$toggle.addClass('show').html(showText)
											.removeAttr('title');
								},
								function(ev) {
									$content.removeClass('hidden');
									$cta.show();
									$toggle.removeClass('show').html(hideText)
											.attr('title', hideText);
								});
					})();
					(function() {
						$('form.countries select').change(
								function() {
									var $menu = $(this), val = $menu.val();
                                                                        window.location.href = (val == '' ? '/'
											: ('/' + $menu.val()));
								});
					})();
					if (ieMajorVersion && ieMajorVersion <= 6) {
						(function() {
							var $grid = $.findCache('ul.country-users');
							if (!$grid[0]) {
								return;
							}
							$grid.find('li').hover(function() {
								$(this).addClass('hover');
							}, function() {
								$(this).removeClass('hover');
							});
						})();
					}

			function refreshUserGrid(link) {
						var $link = $(link);
						$loadingImg = $link.parent().find('img.loading');
						$link.hide();
						$loadingImg.show();
						$link.parent().append($loadingImg);
						/* var href = (window.location.href + '/refresh.js?' + Math
								.floor(Math.random() * 99999)).replace(
								/\/\/refresh/, '/refresh'); */
                                                var country = window.location.href.substr(28)+'/';
                                                var href= 'http://casting.benetton.com/'+country + 'home/refresh/' + Math.floor(Math.random()*99999);

						$.get(href, function(data) {
							$('ul.country-users').replaceWith($(data));
							$loadingImg.hide();
							$link.show();
						});



}
					(function() {
						var container = $('dl.users-count dd'), link = $('<a href="#" class="refresh-button"><img width="22" height="18" title="refresh" src="images/button-refresh.gif?1272362754" alt="refresh"></a>'), loadingImg = $('<img src="' + assetHost() + 'images/ajax-loader.gif" alt="loading" class="loading" style="display:none" />');
						container.append(link).append(loadingImg);
						link.click(function(ev) {
							refreshUserGrid(this);
							ev.preventDefault();
						});
					})();
				});
/* gigi */

/*
  BB.bodyID('entries-index', function() {
	$('input#entries_search').defaultText();
});
*/
BB.bodyID(
  'entries-index', 
  function() { 
    $('input#entries_search').defaultText();
    
    (function() {
						$('form.countries select').change(
								function() {
								var form_url = $("#locale").attr("action");
									var $menu = $(this), val = $menu.val();
									//alert(form_url);
                  //window.location.href = (val == '' ? form_url	: ( $menu.val()+form_url));
                  //window.location.href= form_url+"/"+val;
                  // alert($('#host').val());
                  if (val == '' ){
                    window.location.href= $('#host').val()+form_url;
                  } else{
                    window.location.href= $('#host').val() +val+"/"+form_url;
                  }
                  
								});
					})();
  }
  
);
/* gigi */				

