$(document).ready(function() {

	$("#form-login input").labelify({ text: "label" });


	jQuery.each(jQuery.browser, function(i) {
		if($.browser.msie){
			
			if ($("body.home #content #messages li.success:contains(Congratulations, your profile has been created.)").length > 0 ) { 

				$(".scrollable").hide();

			}
			
		}
	});
	

	

	$("body.home #content #messages li.success:contains(Congratulations, your profile has been created.)").addClass("profilecreated").click(function() {
		$(this).hide();
		$(".scrollable").show();
	});

});







/**
 * Define firebug's console object as a plug
 */
if (typeof console == typeof some_undefined_variable) {
	var console = new (function() {
		this.info = this.log = function(msg) {
			//alert(msg);
		};
	});
}

/**
 * Global AJAX setup
 */
$.ajaxSetup({
	type: "POST",
	dataType: 'json',

	beforeSend: function (XMLHttpRequest) {
	  //this; // the options for this ajax request
	  console.info('ajax has started');
	  /* Ajax indicator */
	  //msgSystem.startLoading('Loading');
	},

	error: function (XMLHttpRequest, textStatus, errorThrown) {
	  // typically only one of textStatus or errorThrown
	  // will have info
	  //this; // the options for this ajax request
	  console.info('ajax error: ' + textStatus);
	  msgSystem.message('Request error. Please try again. If the problem repeats, please contact site administrator: admin@profvote.com.');
	},

	complete: function (XMLHttpRequest, textStatus) {
	  //this; // the options for this ajax request
	  console.info('ajax has finished, status: ' + textStatus);
	  //msgSystem.finishLoading();
	}

});




/**
 * Message System
 * Shows dynamic messages on top
 */
var msgSystem = new (function() {
	this.config = {
		id : 'message-system',
		hideIn : 1, // sec
		hideOut : 1, // sec
		opacity : 1,
		imageLoading: filesPath + 'css/images/ajax-loader.gif'

	};

	this.object = false;
	this.loading = false;
	this.visible = false;

	// Start system
	this.start = function() {
		// build html
		html = '<div id="' + this.config.id + '"></div>';
		$('body').append(html);

		this.object = $('#' + this.config.id)
			.css('opacity', this.config.opacity)
			.hide();
	};

	// Set a simple message
	this.message = function(text) {
		if ( ! this.object) {
			return false;
		}

		this.object.empty().append(text);
		this.show();
		this.loading = false;
	};

	// Show
	this.show = function() {
		this.object.stop();
		//if ( ! this.visible) {
			this.visible = true;
			this.object.fadeIn('fast', function() {
				msgSystem.hide(true);
			});

		//}
	};

	// Wait and Hide
	this.hide = function(wait) {
		if (wait) {
			this.object.animate({'opacity' : this.config.opacity}, this.config.hideIn * 1000, false, function() {
				msgSystem.object.fadeOut('slow', function() {
					msgSystem.visible = false;
				});
			});
		} else {
			this.object.fadeOut('fast', function() {
				msgSystem.visible = false;
			});
		}
	};

	// Start a loading message
	this.startLoading = function(text) {
		this.loading = true;

		text = text || '';

		this.object.empty()
			.append('<img src="' + this.config.imageLoading + '" alt="!" /> ')
			.append(text)
			.fadeIn('fast');
	};

	// Finish a loading message
	this.finishLoading = function() {
		if (this.loading) {
			this.hide();
		}
	};

});

/**
 * Tooltips setup
 */
var toolTips = function($el) {
	var config = {
		delay: 333,
		showBody: ': ',
    	showURL: false
	};

	if ( ! $el) {
		// default anchors tooltips
		$('a, label em, .posted span').tooltip(config);

		/*// icons tooltips
		config.bodyHandler = function() {
			return $(this).text();
		};
		$('i').tooltip(config);*/
	} else {
		$el.tooltip(config);
	}
};






var votesJob = function() {
	$('a.vote-job').click(function(e) {
		e.preventDefault();

		//if this button is disabled, don't do ajax
		if($(this).hasClass('disabled')){
			return false;
		}
		var current_vote = $(this);

		this.clicked = true;

		$.ajax({
			anchor: this,
			//type: "get",
			data: 'foo=bar',
			url: this.href,
			success: function(answer) {
				if (answer.messages.length) {
					//uncomment to show user a message,when voted
					//msgSystem.message(answer.messages[0].text);

					if (answer.messages[0].level == 'success') {

						//add 'disabled' class
						$(this.anchor).addClass('disabled picked');

						//if user clicked in, enable out
						if(current_vote.hasClass('in')){
							$('#vote_in').addClass('picked');
							$('#vote_out').addClass('disabled');
						}else if(current_vote.hasClass('out')){
							$('#vote_out').addClass('picked');
							$('#vote_in').addClass('disabled');
						}

						// Hide skip link, show next link
						$("#vote-skip").hide();
						$("#vote-success").show();
						$("#vote-done").show();

						// Show confirmation
						var vote_message = $(".profile-vote #vote-message");

						if(vote_message.hasClass('shown')) {

						} else {
							
							var COOKIE_NAME = 'signup_message';
			                var options = { path: '/', expires: 60000 };
			
							if ($.cookie(COOKIE_NAME) != "set") {

								$(".profile-vote #vote-message").show().click(function() {
									$(this).hide();
									$(this).addClass('shown');
									$.cookie(COOKIE_NAME, 'set', options);
								});
							
							} else {
								
								$.cookie(COOKIE_NAME, 'set', options);
								
							}

						}

					}
				}

				this.anchor.clicked = false;
			}
		});

	});
};

//------------------------------------------------------------------------------
/**
 * Let's load user's CPU on DOM ready
 */
$(function(){
	msgSystem.start(); // start messages
	toolTips(); // make more visible tooltips

	if (currentMod.primary == 'profile' && currentMod.secondary == 'view' || currentMod.primary == 'vote' && currentMod.secondary == 'all') {

	}

	votesJob();
});


var check_username = function(field_id, check_username_url) {
	$('#' + field_id).blur(function ()  {
		var username = $('#' + field_id).val();
			if (username != "") {
				$.ajax({
					//anchor: this,
					//type: "get",
					dataType: 'json',
					data: 'username=' + username,
					url: check_username_url,
					success: function(answer) {
					console.log(answer);
						if (answer.messages.length) {
							if (answer.messages[0].level == 'error') {
								if ( $('#' + field_id).is('.error') ) {
								} else {
									$('#' + field_id).addClass('error');
								}
								if ( $('#' + field_id+'_error_span').length ) {
									$('#' + field_id+'_error_span').val(answer.messages[0].text);
									if ( $('#' + field_id+'_error_span').is('.error') ) {
									} else {
										$('#' + field_id+'_error_span').addClass('error');
									}
								} else {
									$('#formfield_' + field_id).append('<span id="'+field_id+'_error_span" class="error">'+ answer.messages[0].text + '</span>');
								}
							} else if (answer.messages[0].level == 'success') {
								if ( $('#' + field_id).is('.error') ) {
									$('#' + field_id).removeClass('error');
								}
		 						if ( $('#' + field_id+'_error_span').length ) {
									$('#' + field_id+'_error_span').remove();
								}
							}
						}
					}
				});
			}
	});
};
//initializing jcrop, if we got uploaded file
//Our simple event handler, called from onChange and onSelect
//event handlers, as per the Jcrop invocation above
function showPreview(coords)
{
	if (parseInt(coords.w) > 0)
	{
		var rx = 92 / coords.w;
		var ry = 92 / coords.h;
		var img = new Image();
		img.src = $('#cropbox').attr('src');

		$('#preview').css({
			width: Math.round(rx * img.width) + 'px',
			height: Math.round(ry * img.height) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
	}
}

function updateCoords(c)
{

	$('#photo-x').val(c.x);
	$('#photo-y').val(c.y);
	$('#photo-width').val(c.w);
	$('#photo-height').val(c.h);
};



function initializeResize(photo_url) {
	window.photo = new Image();
	photo.src = photo_url;
	//resize photo
	photo.onload = function(){resize();};
}


/*
 * Zoom & Drag tool
 */
function editPlacement() {
	$("#choose-info").slideUp();
	$("#swfu_placeholder_photo").hide();

	$("#photo-step2").slideDown();
	
	//enable zoom&drag
	$('#draggable_img').draggable({
		drag:function(){
			$('#draggable_img').css({cursor:"move"});
          },
          containment: 'parent'
	});

}

// A handler to kill the action //for Jcrop
function nothing(e){
    e.stopPropagation();
    e.preventDefault();
    return false;
};


function confirmPlacement() {
	//disable zoom&drag
	$("#draggable").removeAttr('style');
	$("#grid_slider").css({'display':'none'});
	$('#draggable').css({'cursor':'default'});
	
	//save img corrdinates
	$('#draggable_img').css({'display':'block'});
	
	//unbind mouse events
	$('#draggable_img').draggable('disable').removeClass('ui-state-disabled');

	$("#zoomcrop-group").slideUp();
	$("#zoomcrop-done").show();
	$("#photo-step3").slideDown();

	//enable jcrop
	var boundary_left = $('#boundary').css('left').replace(/px/,''); boundary_left = boundary_left*(-1);
	var boundary_top = $('#boundary').css('top').replace(/px/,'');boundary_top = boundary_top*(-1);
	var img_left = $('#draggable_img').css('left').replace(/px/,'');
	var img_top = $('#draggable_img').css('top').replace(/px/,'');
	var x_axis = boundary_left - img_left;
	var y_axis = boundary_top - img_top;

	var drag = $("#draggable");
	var offset = drag.offset();
	$("#crop_holder").css({
		'position' : 'absolute',
		'top' : offset.top + 'px',
		'left' : offset.left + 'px',
		'z-index' : '10000'
	});

	$.ajax({
		async:false,
		url:'/profile/crop_photo',
		data: 'width='+$('#draggable_img').width()+'&height='+$('#draggable_img').height()+'&photo='+photo_url+'&x_axis='+x_axis+'&y_axis='+y_axis,
		success: function(data) {
			var cropped_img = new Image();
			cropped_img.src = data.data.cropped_image;

			cropped_img.onload = function(){
				$('#cropbox').attr({'src':cropped_img.src});
				$('#cropbox').Jcrop({
					minSize : [92,92],
					setSelect: [ 0, 0, 0, 10000],
					onChange: showPreview,
					onSelect: updateCoords,
					aspectRatio: 1,
					displayHolder:true,
					allowSelect:false
				});
				$('#preview').attr({'src':cropped_img.src});
				
			}
			showJcrop();
			$('#thumbnail-confirm').show();
		},error: function() {
			msgSystem.message('Request error. Please try again. If the problem repeats, please contact site administrator: admin@profvote.com.');
		}
	});

}

function showJcrop(){
	if($('td.profile-thumb img').attr('src')){
		$('td.profile-thumb img').remove();
		$('#preview_holder').appendTo($('td.profile-thumb'))
	}
}

function confirmThumbnail() {
	$("#thumbnail-tool").slideUp();
	$('.jcrop-holder').hide();
	$('.jcrop-holder img').hide();
	$('#draggable').show();
	$("#thumbnail-done").show();
	$("#photo-step4").show();
}



 function resize(){
    var w = 400; var h = 600;
    var res_width = w; var res_height = h;

	if(photo.width > photo.height){
		res_height = h;
		res_width = parseInt((photo.width*h)/photo.height);
	}else{
		res_width = w;
		res_height = parseInt((photo.height*w)/photo.width);
	}

	$.ajax({
		beforeSend: function (XMLHttpRequest) {
		 //$('#draggable').css({'display':'none'});
		},
		url:'/profile/resize_photo',
		data: 'width='+res_width+'&height='+res_height+'&photo='+photo_filename,
		success: function(data) {
			resized_image = data.data.resized_image;
			window.resized = new Image();
			resized.src = resized_image;
			$('#draggable_img').attr({'src':resized_image});

			//replace image container to the right of the page
			$('#full-photo img').hide();
			$('#draggable').appendTo($('#full-photo'));
			$('#draggable').css({'display':'block'});
			
			$("#grid_slider").show();
			$("#zoomcrop-tool").show();


			//
			resized.onload = function(){
				initSlider();
				wb = 2*resized.width - 400;
				hb = 2*resized.height - 600;
				$('#boundary').width(wb);
				$('#boundary').height(hb);
				$('#boundary').css({'top':-((hb/2)-300)+'px', 'left':-((wb/2)-200)+'px', 'position':'absolute'});
			};
		},error: function() {
			msgSystem.message('Request error. Please try again. If the problem repeats, please contact site administrator: admin@profvote.com.');
		}
	});

}

function initSlider(){
	if(resized.width == 400){
		var min_img = 400;
		var max_img = photo.width;
	}else{
		var min_img = 600;
		var max_img = photo.height;
	}
	$("#grid_slider").slider({
		value: min_img,
		max: max_img,
		min: min_img,
		//step:12,
		step:5,
		slide: function(event, ui) {

			//do smth to hide draggable and show draggable img and then revert these modifications

			if(resized.width == 400){
				$('#draggable_img').height((ui.value*photo.height)/photo.width);
				$('#draggable_img').width(ui.value);
			}else{
				$('#draggable_img').height(ui.value);
				$('#draggable_img').width((ui.value*photo.width)/photo.height);
			}

			wb = 2*$('#draggable_img').width() - 400;
			hb = 2*$('#draggable_img').height() - 600;
			$('#boundary').width(wb);
			$('#boundary').height(hb);
			$('#boundary').css({'top':-((hb/2)-300)+'px', 'left':-((wb/2)-200)+'px', 'position':'absolute'});
			$('#draggable_img').css({'top':'0px', 'left':'0px'});


		}
	});

}

function initPreview(photo_url){
	var photo_preview = "<img id='photo_preview' src="+photo_url+"></img>";
	$(photo_preview).appendTo('ul#grid li.grid');

	//resizing photo
	initializeResize(photo_url);
}


function initJCrop(){
	$('#cropbox').css({'display':'none'});
}