//function for the accordion action on filter
function initMenus() {
    jQuery.each(jQuery('#filter .section .dropdown'), function(e) {
        jQuery('#filter .expandfirst').show();
        jQuery('#filter .expandfirst').siblings().addClass('collapse');
    });
    //Simple click and open click and close finctionality
    jQuery('#filter .section .header').click(function(e) {
		 jQuery(this).toggleClass('collapse');
		 jQuery(this).siblings().slideToggle('slow');
		});
	  return false;
}

function initAccordion_parties() {
  var params = parseQueryParams();
  var expand = params['expand']? params['expand'].split(','): [];
  var logged_in = $('body').hasClass('logged-in');

  if(!logged_in) expand = [0];
  else if(expand.length == 0) expand = [0, 1]; // default to first two accordions expanded
  else $.each(expand, function(k, v) {expand[k] = parseInt(v);} );
  
  $('.accordion_block').each(function(i) {
    var accrdn = $(this);
    
    if(i < 1 || logged_in) {
      accrdn.find('.header').click(function() {
        if(accrdn.hasClass('collapsed')) { // expand
          accrdn.find('.dropdown').slideDown();
          accrdn.removeClass('collapsed');
        } else { // collapse it
          accrdn.find('.dropdown').slideUp();
          accrdn.addClass('collapsed');
        }
      });
      
      if($.inArray(i, expand) == -1) accrdn.find('.header').click();
    } else {
      accrdn.addClass('not-logged-in');
      accrdn.find('.header').click(function() {
        if(aetn.user) {
          var options = $(this).offset();
          options.left += 220;
          // for some reason the pop up causes the page to scroll, so let's make sure to go back where we were
          var scroll_top = $().scrollTop();
          options.destination = '/total-beauty-makeover/makeover-party?expand=' + i;
          aetn.user.login.show(options);
          $().scrollTop(scroll_top);
        } else {
          window.location.href = "/total-beauty-makeover/user/login";
        }
        
        return false;
      });
    }
  });
  
  if(window.location.pathname == '/total-beauty-makeover/makeover-party') $('.sub_nav a span.last').click(function() { window.location.reload(); return false; });
}

function parseQueryParams(url) {
  var params = {};
  if(!url) url = window.location.href;
  
  if(url.indexOf('?') != -1) {
    var query = url.substr(url.indexOf('?') + 1);
    if(query.indexOf('&') != -1) var queries = query.split('&');
    else var queries = [query];
    for(i in queries) {
      if(queries[i].indexOf('=') != -1) params[queries[i].substr(0, queries[i].indexOf('='))] = queries[i].substr(queries[i].indexOf('=') + 1);
      else params[queries[i]] = '';
    }
  }
  
  return params;
}
  
function getEventCoordinates(e) {
     var xCoordinate = 0;
     var yCoordinate = 0;
     var objTX = 0;
     var objTY = 0;
     if (document.all) {
         xCoordinate = event.clientX + document.body.scrollLeft;
         yCoordinate = event.clientY + document.body.scrollTop;
         objTX = xCoordinate - document.body.scrollLeft;
         objTY = yCoordinate - document.body.scrollTop;
     } else if (document.layers) {
         xCoordinate = e.x;
         yCoordinate = e.y;
         objTX = xCoordinate - window.pageXOffset;
         objTY = yCoordinate - window.pageYOffset;
     } else if (document.getElementById) {
         xCoordinate = e.clientX;
         yCoordinate = e.clientY;
         objTX = xCoordinate - document.body.scrollLeft;
         objTY = yCoordinate - document.body.scrollTop;
     } else {
         xCoordinate = e.pageX;
         yCoordinate = e.pageY;
         objTX = xCoordinate - document.body.scrollLeft;
         objTY = yCoordinate - document.body.scrollTop;
     }
     if (xCoordinate < 0) {xCoordinate = 0}
     if (yCoordinate < 0) {yCoordinate = 0}
     if (objTX < 0) {objTX = 0}
     if (objTY < 0) {objTY = 0}
     return new objectCoordinates(xCoordinate, yCoordinate, objTX, objTY);
 }

 function objectCoordinates(objCoordX, objCoordY, objTrueX, objTrueY) {
     this.objCoordX = objCoordX;
     this.objCoordY = objCoordY;
     this.objTrueX = objTrueX;
     this.objTrueY = objTrueY;
 }

 //popup bubble for the more_link 
function bubble_popup() {
   jQuery('.more_link').mouseover(function(e) {
         var objCoord = getEventCoordinates(e);
         var mPosY = objCoord.objTrueY;
         var mPosX = objCoord.objTrueX;
         var posTop = jQuery('.more_link').offset().top - jQuery('.popup').height()+5;
         var posLeft = mPosX - ((jQuery('.popup').width()) / 4);
         jQuery(".popup").css({top: (posTop + 'px'), left: (posLeft + 'px')});
         jQuery(".popup").show();
         return false;
   });

   jQuery('.whatsthis_link').mouseover(function(e) {
         var objCoord = getEventCoordinates(e);
         var mPosY = objCoord.objTrueY;
         var mPosX = objCoord.objTrueX;
         var posTop = jQuery('.whatsthis_link').offset().top - jQuery('.whatsthis-popup').height()+5;
         var posLeft = mPosX - ((jQuery('.whatsthis-popup').width()) / 4);
		 jQuery(".whatsthis-popup").css({top: (posTop + 'px'), left: (posLeft + 'px')});
         jQuery(".whatsthis-popup").show();
         return false;
   });

  jQuery('.preview').click(function() {
      jQuery(".preview_popup").css({bottom: ('49px'), left: ('5px')});
      jQuery(".preview_popup").show();
      jQuery('#page #left_column .right_block .img_blocks .radio').show();
      return false;
  });
	 jQuery('.invite_friends_btn').click(function() {
	    jQuery('#edit-invites').val("");
      jQuery('.popup').css({bottom: ('60px'), right: ('0')});
      jQuery('.popup').show();
      return false;
	 });

	jQuery('#whatsthisid').hover(function() {
		//alert(jQuery('.whatsthis-popup').css('display'));
		//jQuery('.whatsthis-popup').css('display') = 'block';
		jQuery('.whatsthis-popup').show();
		return false;
	},function() {
		jQuery('.whatsthis-popup').hide();
		return false;
	});

	jQuery('.invite_link, .invite_count_link').click(function() {
    jQuery('.invite-popup')
      .removeClass('invited-friends')
      .removeClass('invite-friend')
      .addClass( $(this).hasClass('invite_link')? 'invite-friend': 'invited-friends' )
      .show();
		return false;
	});
}

function invite_submit_callback() {
  var postdata = $(this).parents('form').find('input, textarea').serialize();
  var ajaxURL =  '/total-beauty-makeover/invite';

  $.ajax({
     type: "POST",
     url: ajaxURL,
     data: postdata,
     dataType: 'json',
     success: function(data){
       if(data.status) {
         $('.invite-popup').replaceWith(data.data)
         $('#invite_button').click(invite_submit_callback);
         // update the .invite_count_link
         var invite_count = $('#invited-friends-tab').text().match(new RegExp('\\((\\d+)\\)'))[1];
         $('.invite_count_link').text(invite_count + $('.invite_count_link').text().substr($('.invite_count_link').text().indexOf(' ')));
       } else { // error
         console.error(data.messages.join('<br />'));
       }
       return false;
     }
   });
}

function maxlength() {
  var callback = function(e) {
    var key = e.which;
    //all keys including return.
    if (key > 50 || key == 32 || key == 0 || key == 13) {
      var el = jQuery(this);
      var maxLength = parseInt(el.attr("maxlength"));
      var text = el.val();
      var length = text.length;
      if (length >= maxLength) {
        text = text.substr(0, maxLength);
        el.val(text);
        return false;
      }
    }
  };

  jQuery("textarea[maxlength]").keyup(callback);
  jQuery("textarea[maxlength]").blur(callback);  
}  

// MAKEOVER
function delete_makeover(nid){
	if(nid > 0 && confirm("Are you sure you want to delete this makeover?")) {
	  jQuery("#mo_to_delete").val(nid);
	  return true;
	}
	return false;
}

// clear description
function clear_description(){
	$("input.reset").click(function(){
		$("#edit_quote #edit-new-body").html('');
	});
}

// WHAT'S MY BEST LOOK
function limitChars(textid, limit, infodiv){
	var text = $('#'+textid).val(); 
 	var textlength = text.length;
	if(textlength > limit){
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}else{
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}


function best_look_onload(nid, path, title){
	// set the first mo
	jQuery("#img_blocks_1 img").attr("src", path);
	jQuery("#img_blocks_1 img").attr("alt", title);
	jQuery("#img_blocks_1 img").attr("title", title);
	jQuery("#img_blocks_1a img").attr("src", path);
	jQuery("#img_blocks_1a img").attr("alt", title);
	jQuery("#img_blocks_1a img").attr("title", title);
	jQuery("#edit-field-first-makeover-0-nid-nid").val(nid? title + ' [nid: ' + nid + ']': '');
	jQuery("#bestlook_preview_name_1").html(title);
}

function best_look(nid, path, title){
	jQuery(function(){
		var firstval = jQuery("#edit-field-first-makeover-0-nid-nid").val();
		var secondval = jQuery("#edit-field-second-makeover-0-nid-nid").val();		
		if(firstval === ''){
			// set the first mo
			jQuery("#img_blocks_1 img").attr("src", path);
			jQuery("#img_blocks_1 img").attr("alt", title);
			jQuery("#img_blocks_1 img").attr("title", title);
			jQuery("#img_blocks_1a img").attr("src", path);
			jQuery("#img_blocks_1a img").attr("alt", title);
			jQuery("#img_blocks_1a img").attr("title", title);
			jQuery("#edit-field-first-makeover-0-nid-nid").val(nid? title + ' [nid: ' + nid + ']': '');
			jQuery("#bestlook_preview_name_1").html(title);
		}else if(secondval === ''){
			// set the second mo
			jQuery("#img_blocks_2 img").attr("src", path);
			jQuery("#img_blocks_2 img").attr("alt", title);
			jQuery("#img_blocks_2 img").attr("title", title);
			jQuery("#img_blocks_2a img").attr("src", path);
			jQuery("#img_blocks_2a img").attr("alt", title);
			jQuery("#img_blocks_2a img").attr("title", title);
			jQuery("#edit-field-second-makeover-0-nid-nid").val(nid? title + ' [nid: ' + nid + ']': '');
			jQuery("#bestlook_preview_name_2").html(title);
		}
		return false;
	});
}
function set_preview_body(){
	jQuery(function(){
		var bodyval = jQuery("#edit-body").val();
		if(bodyval!='') {bodyval = "&quot;"+bodyval+"&quot;";}
		jQuery("#bestlook_preview_body").html(bodyval);
	})
}
function clear_best_look_1(){
	jQuery(function(){
    	//This is to fix an un-set src.
		jQuery("#img_blocks_1 img").attr("src", '/total-beauty-makeover/sites/mylifetime.com.total-beauty-makeover/themes/ltvtbm/images/default_photo175X215.jpg');
		jQuery("#img_blocks_1 img").attr("alt", '');
		jQuery("#img_blocks_1 img").attr("title", '');
		jQuery("#edit-field-first-makeover-0-nid-nid").val('');
	});
}
function clear_best_look_2(){
	jQuery(function(){
		//This is to fix an un-set src.
		jQuery("#img_blocks_2 img").attr("src", '/total-beauty-makeover/sites/mylifetime.com.total-beauty-makeover/themes/ltvtbm/images/default_photo175X215.jpg');
		jQuery("#img_blocks_2 img").attr("alt", '');
		jQuery("#img_blocks_2 img").attr("title", '');
		jQuery("#edit-field-second-makeover-0-nid-nid").val('');
	});
}

// PARTIES
function select_party_photo(nid, path){
	$(function(){
    $("#edit-field-party-photo-node").val(nid);
		$(".thepartyphoto").attr("src", path);
		$('#mycarousel2 li a.selected').removeClass('selected');
		$('#link-' + nid).addClass('selected');
		$('.accordion_1 .form-lower:not(.expanded)').slideDown(function() {$(this).addClass('expanded')});
	});	
}
function select_party_winner(node_id, choice){
	var flag = confirm("This selection is final.  Are you sure you want to proceed?")
	var dataString = 'choice=' + choice + '&party=' + node_id;
	if(!flag) { 
	  return false;
	} 
	jQuery.ajax({
		type: "POST",
		url: "/total-beauty-makeover/select_party_winner",
		data: dataString,
		success: function(data){
			location.reload(true);
		}
	});
	return false;
}

// MAKEOVER CHALLENGE
function pass_main_nid(){
	jQuery(function(){
		var blnid = jQuery("#nid").html();
		jQuery("#blnid").val(blnid);
	});	
}

function pass_nids(){
	jQuery(function(){
		var nid1 = jQuery("#nid1").html();
		var nid2 = jQuery("#nid2").html();
		jQuery("#getnid1").val(nid1);
		jQuery("#getnid2").val(nid2);
	});	
}

function pass_nids_bl(){
	jQuery(function(){
		var blnid1 = jQuery("#blnid1").html();
		var blnid2 = jQuery("#blnid2").html();
		jQuery("#getblnid1").val(blnid1);
		jQuery("#getblnid2").val(blnid2);
	});	
}

// makeover challenge voting
var mo_challenge_block_num_votes = null;
$(document).ready(function() { 
  mo_challenge_block_num_votes = $('.block-makeover-challenge-voting').hasClass('block-type')? 3: null;
});

function mo_challenge_vote_handler() {
  var winning_nid = $(this).parents('.img_wrap').addClass('winner').get(0).id.substr(11);
  var losing_nid = $(this).parents('.img_wrap').siblings('.img_wrap').get(0).id.substr(11);
  
  mo_challenge_submit(winning_nid, losing_nid);
}

// this model still does not allow for more than one voting block per page
// as all the references are global
function mo_challenge_submit(winning_nid, losing_nid){
	jQuery.ajax({
		type: "POST",
		url: "/total-beauty-makeover/mo-c_front_submit",
		data: {"winning_nid": winning_nid, "losing_nid": losing_nid},
		dataType: "json",
		success: function(response){
      if(response.status) {
        // display results
        if(response.data.winning_makeover) {
          var w_mo = response.data.winning_makeover;
          $('#c-makeover-' + w_mo.nid + ' .vote_mo').hide();
          $('#c-makeover-' + w_mo.nid).append('<div class="percent mo_percent"><div class="percent_num percent_winner">' + w_mo.vote_count + '</div>Total Votes</div>');
        }
        if(response.data.losing_makeover) {
          var l_mo = response.data.losing_makeover;
          $('#c-makeover-' + l_mo.nid + ' .vote_mo').hide();
          $('#c-makeover-' + l_mo.nid).append('<div class="percent mo_percent"><div class="percent_num">' + l_mo.vote_count + '</div>Total Votes</div>');
        }
        if(response.data.next_makeover) {
          var n_mo = response.data.next_makeover;
          
          $('.block-makeover-challenge-voting #challenge-description').hide();
          $('.block-makeover-challenge-voting p.next_pair').show();
          
          // wire up next
          $('.block-makeover-challenge-voting p.next_pair a').one('click', function() {
            if(mo_challenge_block_num_votes != null && --mo_challenge_block_num_votes == 0) {
              return true;
            }
            
            // fire next, load new makeover and wire up vote            
            $('.block-makeover-challenge-voting #challenge-description').show();
            $('.block-makeover-challenge-voting p.next_pair').hide();

            $('#c-makeover-' + w_mo.nid).removeClass('winner');
            $('#c-makeover-' + w_mo.nid + ' .vote_mo').removeAttr('checked').show();
            $('#c-makeover-' + w_mo.nid + ' .mo_percent').remove();

            $('#c-makeover-' + l_mo.nid + ' .vote_mo').show();
            $('#c-makeover-' + l_mo.nid + ' .mo_percent').remove();
            
            $('#c-makeover-' + l_mo.nid + ' a:first').attr('href', n_mo.url).attr('title', n_mo.title);
            $('#c-makeover-' + l_mo.nid + ' img.mo-challenge-image').attr('src', n_mo.image).attr('title', n_mo.title).attr('alt', n_mo.title);
            $('#c-makeover-' + l_mo.nid + ' a:last').attr('href', n_mo.user_url).attr('title', n_mo.title).html(n_mo.username);
            
            $('#c-makeover-' + l_mo.nid).attr('id', 'c-makeover-' + n_mo.nid);

            return false;
          });
          
          
        }
  		  
      } else {
        ;// error has occured.  response.messages has details
      }
		}
	});
	return false;
}

// what's my best look homepage stuffs	
function do_new_pair(pairnum_js){
	var	this_pair = pairnum_js + 1;
	if(this_pair > 1) {
		var	this_suffix_num = this_pair - 1;
		var	this_suffix = '-' + this_suffix_num;
	}else{
		var	this_suffix = '';
	}
	jQuery(".bestlookhome").hide();
	jQuery(".bestlookhome" + this_pair).show();
	// submit front page wmbl vote
	var choice;
	jQuery(".bestlookhome" + this_pair + " #bestlook-front-vote-form" + this_suffix + " #edit-mo-0" + this_suffix).click(function(){
		choice = 'a';
		submit_wmbl_front(choice, this_pair);
	});
	jQuery(".bestlookhome" + this_pair + " #bestlook-front-vote-form" + this_suffix + " #edit-mo-1" + this_suffix).click(function(){
		choice = 'b';
		submit_wmbl_front(choice, this_pair);
	});
}
function submit_wmbl_front(choice, pairnum_js){
	var nid = jQuery(".bestlookhome"+pairnum_js+" .right_block .data p#nid").html();
	var dataString = 'choice=' + choice + '&nid=' + nid;
	jQuery.ajax({
		type: "GET",
		url: "wmbl_front_submit",
		data: dataString,
		dataType: 'json',
		success: function(data){
	    jQuery(".bestlookhome" + pairnum_js + " .wmbl_front_on").hide();
	    
	    var el = jQuery(".bestlookhome" + pairnum_js + " .wmbl_front_off .percent_front:first");
	    el.html(data.choiceAPercent + '%');
	    if(data.choiceAPercent > data.choiceBPercent) el.addClass('high');
	    else el.removeClass('high');
	    
      el = jQuery(".bestlookhome" + pairnum_js + " .wmbl_front_off .percent_front:last");
      el.html(data.choiceBPercent + '%');
      if(data.choiceBPercent > data.choiceAPercent) el.addClass('high');
      else el.removeClass('high');
	    
	    jQuery(".bestlookhome" + pairnum_js + " .wmbl_front_off").show();
			jQuery(".bestlookhome" + pairnum_js + " .wmbl_front_off .percent_front").show();
		}
	});
	return false;
}
function change_wmbl_pair(pairnum_js){
	old_pair = pairnum_js;
	new_pair = pairnum_js + 1;
	jQuery(".bestlookhome" + new_pair + ".wmbl_front_off").hide();
	jQuery(".bestlookhome" + new_pair + ".wmbl_front_on").show();
	do_new_pair(old_pair);
	return false;
}

// clear text from search box
function clearText(thefield){
	if (thefield.defaultValue==thefield.value)
	thefield.value = ""
}

// function setupRolloversForMakeovers(){
// 	jQuery(function(){
// 		jQuery(".gallery_filter_block .block").hover(function(){
// 			jQuery(this).css('background', 'transparent url("/total-beauty-makeover/sites/mylifetime.com.total-beauty-makeover/themes/ltvtbm/images/box_over.gif") no-repeat 0 0');
// 	// 	transparent url("images/box_over.gif") no-repeat 0 0
// 		}, function(){
// 			jQuery(this).css('background', 'transparent url("images/box.gif") no-repeat 0 0');
// 		});
// 	});	
// }

// celeb galleries
function filter(selector, query){
	jQuery(selector).each(function(){
		(jQuery(this).text().search(new RegExp(query, "i")) < 0) ? jQuery(this).hide().removeClass('visible') : jQuery(this).show().addClass('visible');
	});
}

jQuery(document).ready(function() {
	jQuery('#mycarousel').jcarousel({scroll: 6});	
	jQuery('#mycarousel2').jcarousel({
    scroll:4,
		animation:'slow',
		buttonNextEvent: 'click',
		buttonPrevEvent: 'click'
  });
	clear_description();
	bubble_popup();
	maxlength(); 
	initAccordion_parties();
	initMenus();
	clear_best_look_2();
	clear_best_look_1();
	set_preview_body();
	pass_nids();
	pass_nids_bl();
	pass_main_nid()
	delete_makeover();
	best_look_onload();
	best_look();
	do_new_pair(0);
	jQuery('#select_mult a').addClass('visible');
	jQuery('#select_mult span').addClass('visible');
	jQuery('#sort_celeb').keyup(function(event) {
		if (event.keyCode != 13){
			if (event.keyCode == 27 || jQuery(this).val() == ''){
				jQuery(this).val('');
				jQuery('#select_mult a').removeClass('visible').show().addClass('visible');
				jQuery('#select_mult span').removeClass('visible').show().addClass('visible');
			} else {
				filter('#select_mult a', jQuery(this).val());
				filter('#select_mult span', jQuery(this).val());
			}
		}
	});

	$("#sort_celeb").bind("keypress", function(event) {
		if (event.keyCode == 13) {
			var url= 'celebrity-makeover?opt=yes&celebrity_key='+$("#sort_celeb").val()+'#filter';
			window.location.href = url;
		} 
	});
	

	jQuery('#invite_button').click(invite_submit_callback);

	
	// a click will register a vote for that nid
	jQuery(".block-makeover-challenge-voting .vote_mo").click(mo_challenge_vote_handler);
	

  $('#edit-body').keyup(function(){limitChars('edit-body', 130, 'charlimitinfo');});
  $('#edit-body').blur(function(){limitChars('edit-body', 130, 'charlimitinfo');});

  // for Five star issue
  $('.block .starbump1 .star span').each(function(){
    if(this.className=='on') {
      if($(this).width() == 9) {
        $(this).width(17);
        $(this).css({backgroundPosition: "center -30px"});
      }
    }
  });

  $('#comment-controls #edit-comments-per-page').change(function() {$('#comment-controls').submit();});

  $(".messages_tbl td.delete img").hover(function() {
	$(this).attr("src","/total-beauty-makeover/sites/mylifetime.com.total-beauty-makeover/themes/ltvtbm/images/icons/orange.gif");
  }, function() {
	$(this).attr("src","/total-beauty-makeover/sites/mylifetime.com.total-beauty-makeover/themes/ltvtbm/images/icons/delete.gif");
  });

  $('.choose-winner-link').click(function() {
    $('.gallery_filter_block .makeover_actions_container').hide();
    $('.gallery_filter_block .choose_winner_container').show();
  });  

  $('#page.makeover_galleries #content-region-outer #content-region .left_block .edit_quote .reset').click (function() {   
	$('#page.makeover_galleries #content-region-outer #content-region .left_block .edit_quote textarea').val('');
  });  

 $('#page.makeover_galleries.bestlook #content-region-outer #content-region .left_block .btn').click(function() {
    var clicked =$(this).attr('class');
	if(clicked == 'form-submit submit btn'){
		$(this).hide();
	}
  });

  var wrap = $('.error').parents('div#edit-title-wrapper');
  $('label', wrap).addClass('lable-error');
  
});


