var timer;
var iGrid 				= 100;
var iGridOffset 		= 100;	
var iLegacyWidth		= 800;
var iTweenTime			= 275;
var bFirstTime			= true;

jQuery(document).ready(function()
{
	setupPollLinks();
	setupLoginLink();
	setupRegLinks(); 
	setupFooterLink();
	setupMPTabs();
	initOverLabels();
	msgTimeOut();
	document.answers = 0;
	document.threshold = 3;
	document.highThreshold = 5;
});

jQuery(window).load(function()
{
	gridCheck();
});

jQuery(window).resize(function() {
	jQuery('html').queue("fx",[]);
	jQuery('html').stop();
	jQuery('html').delay(300).queue(function() { gridCheck(); });	
});

function setupPollLinks()
{
	jQuery('.block > a[title$=" this poll"]').unbind('click');
	jQuery('.block > a[title$=" this poll"]').click(function() {
		if(!jQuery(this).parent().hasClass('active'))
		{
			jQuery('#noThanksQR').click();
			jQuery('.block > a.question[title="Close this poll"]').click();
			
			//Handle register prompts
			if(document.answers >= document.threshold)
			{
				document.threshold = document.highThreshold;
				document.answers = 0;
				
				document.activePoll = this;
				jQuery.get('/wp-content/themes/votetub/quickRegister.php/', function (data) {
					jQuery(document.activePoll).parent().addClass('signup height-to-grid');
					jQuery(document.activePoll).parent().prepend(data);
					setupQRLinks();
				});
			}
			else
			{
			jQuery(this).parent().addClass('active height-to-grid');
			jQuery(this).attr('title','Close this poll');
			}
		}
		else
		{
			checkPollRemoval(this);
			jQuery('#quickSignup').remove();
			jQuery('.signup').removeClass('signup');
			jQuery(this).parent().removeClass('active height-to-grid');
			jQuery(this).parent().css('height','');
			jQuery(this).attr('title','View this poll');
		}
		ajaxifyPolls();
		gridHeightCheck();
		return false;
	});
}

function setupQRLinks()
{
	jQuery('#quickSignup > a.btn').click(function() { getLoginPanel(); restorePoll(this); return false;});
	jQuery('#quickSignup > #noThanksQR').click(function() { restorePoll(this); return false;});
}

function restorePoll(link)
{
	jQuery(link).parent().remove();
	jQuery('.signup').addClass('active');
	jQuery('.signup a.question').attr('title','Close this poll');
	jQuery('.signup').removeClass('signup');
}

function setupLoginLink()
{
	jQuery('li.login > a').click(function() { jQuery(this).parent().addClass('active'); return false;});
	jQuery('#login-close').click(function () { jQuery(this).parents('li.login').removeClass('active'); return false;});
}

function setupRegLinks()
{
	jQuery('a[href$=/register/]').click(function() { return getLoginPanel();});
	
	jQuery('#quickRegister').submit(function () { return getLoginPanel(); });
}

function getLoginPanel() 
{
	jQuery.get('/ajax-handler/?login-panel=1&goTo='+window.location.pathname,function(result) { jQuery('body').append(result); setupLoginPanel();});
	return false;
}

function setupLoginPanel()
{
	jQuery('.closeLoginPanel').click(function() { jQuery('#login-panel-hover').remove(); return false;});
	var uName = jQuery('#qr_user_name');
	if(jQuery('#new-user').val() != "")
	{
		jQuery(uName).val(jQuery('#new-user').val());
		checkUserName(jQuery('#qr_user_name'));
	}
	jQuery('#login-panel-hover .fbLogin').click(function () { return fbLogin(); });
	jQuery('#qr_user_name').keyup(jQuery.debounce(300,function() { jQuery(this).removeClass('OK NOWAY'); jQuery(this).addClass('WAIT'); checkUserName(this); }));
}

function setupMPTabs()
{
	jQuery('#mp_menu a').click(function() {
		jQuery('#mp_menu li').removeClass('active');
		jQuery('.mpPanel').removeClass('active');
		var targetPanel = jQuery(this).attr('href').replace('?panel=','');
		jQuery('.mpPanel.'+targetPanel).addClass('active');
		jQuery(this).parent().addClass('active');
		gridHeightCheck();
		return false;
	});
}

function setupFooterLink() {
	jQuery('#close-footer-panel').click(function() {
		if(jQuery('#panel-footer').hasClass('active'))
			jQuery('#panel-footer').removeClass('active');
		else
			jQuery('#panel-footer').addClass('active');
	});
}

function checkUserName(element)
{
	var val = jQuery(element).val();
	jQuery(element).val(jQuery.trim(val));
	jQuery.get('/ajax-handler/?check_uname='+val,function(data) { 
		jQuery('#qr_user_name').removeClass('WAIT');
		jQuery('#qr_user_name').addClass(data=='1'?'OK':'NOWAY');
	});
}

function gridHeightCheck()
{		
	var myFunction 					= function(index,item) 
	{
		jQuery(item).css('height', '');
		var iBorderWidth			= parseInt(jQuery(item).css('border-top-width').replace('px',''))+parseInt(jQuery(item).css('border-bottom-width').replace('px',''));
		var iMargin					= parseInt(jQuery(item).css('margin-bottom').replace('px',''))+parseInt(jQuery(item).css('margin-top').replace('px',''));
		var iPadding				= parseInt(jQuery(item).css('padding-bottom').replace('px',''))+parseInt(jQuery(item).css('padding-top').replace('px',''));
		var extras 					= iPadding+iBorderWidth+iMargin;
		var iCurrentCombinedHeight 	= parseInt(jQuery(item).innerHeight()) - iPadding + extras;
		var iColumnHeight			= (Math.floor(iCurrentCombinedHeight/iGrid)*iGrid)- extras;
		if((iColumnHeight+iPadding) < iCurrentCombinedHeight)
			iColumnHeight			= (Math.ceil(iCurrentCombinedHeight/iGrid)*iGrid)- extras;
		if(iCurrentCombinedHeight % iGrid != 0)	
		{
			jQuery(item).css('height', iColumnHeight);		
		}
	};	
	jQuery('.height-to-grid').each(myFunction);
}

function gridCheck()
{
	var objGridTarget	= jQuery('#site');
	if(objGridTarget)
	{	
		
		var iMinWidth		= parseInt(jQuery(objGridTarget).css('min-width').replace('px','') | 0);
	
		var innerWidth = jQuery(window).width();
		var iWindowWidth 	= (Math.ceil(innerWidth/iGrid)*iGrid)-iGridOffset;
		var iBrowserCentre	= (innerWidth/2)-(iWindowWidth/2);
		
		if (iWindowWidth < iMinWidth + 70)
		{
			jQuery(objGridTarget).css('margin', '0 auto');
			jQuery(objGridTarget).css('position', 'static');
			jQuery(objGridTarget).css('padding', '0 35px 35px');
			iWindowWidth	= iMinWidth;
		}
			
		if(iLegacyWidth != iWindowWidth)
		{			
			jQuery(objGridTarget).css('width', iWindowWidth);
			jQuery(objGridTarget).css('margin', 0);
			jQuery(objGridTarget).css('position', 'absolute');
			jQuery(objGridTarget).css('padding', '0 0 35px 0');
		
			/* Setup the tween 
			var tweenObject = new Fx.Tween(objGridTarget, 
			{
			    duration: 	iTweenTime,
			    transition: 'back:out'
			});
			// First time through we want to snap to the correct width
			if (bFirstTime)
			tweenObject.set('left', iBrowserCentre);
			else
			tweenObject.start('left', iBrowserCentre);*/

			// reset the LegacyWidth to equal our new value
			iLegacyWidth 	= iWindowWidth;

			jQuery(objGridTarget).animate({ left : iBrowserCentre } , 100);
		}	
		gridHeightCheck();
	}
}

function ajaxifyPolls()
{
	jQuery('.voteLink').unbind('click.votetub');
	jQuery('.voteLink').bind('click.votetub',function() {		
		var href = jQuery(this).attr('href').replace(/^[^?]+/,'/ajax-handler/');
		jQuery(this).parents('.block').addClass('answered');
		
		//Only increment nag counter if user is not signed in
		if(document.unregistered)
			document.answers++;
		
		jQuery(this).parents('.block').load(href,function() { gridHeightCheck(); setupPollLinks(); ajaxifyPolls();});
		FB.Event.fire('xfbml.render');
		return false;
	});
	
	jQuery('.skipPoll').unbind('click');
	jQuery('.skipPoll').bind('click',function() {
		jQuery(this).parents('.block').addClass('answered');
		checkPollRemoval(this);
		return false;
	});
	
}

function checkPollRemoval(link)
{
	if(jQuery(link).parents('.block').hasClass('answered') || jQuery(link).parents('.block').hasClass('skip'))
	{
		jQuery(link).parents('.block').remove();
		
		if(!jQuery('.endtub').length)
		{
			jQuery.ajax({ url: '/ajax-handler/?get_poll=true', success: function(data) {
				if(!data.match('endtub') || !jQuery('#wall .block.real').length)
				{
					if(data.match('endtub'))
						jQuery('.block').remove();
					jQuery('#wall').append(data);
					setupPollLinks();
					gridHeightCheck();
				}
			}});
		}
	}
}

function initOverLabels () {
  if (!document.getElementById) return;  	

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
	
    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-6000px' : '0px';
	  labels[i].style.visibility = (hide) ? 'hidden' : 'visible';
      return true;
    }
  }
}

function msgTimeOut()
{
	
	 $clear(timer);
	  timer 			= (function()
	  {
		  	var alert = $('alert');
		  	if(alert)
		  		alert.fade('out');	  
	  }).delay(5*1000);
}
