// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

try {
	$.extend({
	  getUrlVars: function(){
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	      hash = hashes[i].split('=');
	      vars.push(hash[0]);
	      vars[hash[0]] = hash[1];
	    }
	    return vars;
	  },
	  getUrlVar: function(name){
	    return $.getUrlVars()[name];
	  }
	});
}
catch(err) {}

function trackSeen(seen) {
	pageTracker._setCustomVar(
      1,             		// This custom var is set to slot #1
      "Stories Viewed", // The name of the custom varaible
      "" + seen,      	// Sets the value of "User Type" to "Member" or "Visitor" depending on status
       2             	// Sets the scope to session-level  
   );
}

function trackClick(url) {
	pageTracker._trackPageview(url);
	com.mtvi.reporting.Controller.sendLinkEvent({ linkName:url, linkType:'o' });
}

function lightbox(action) {	
	lb = $('#lightbox');
	if(action == 'close') {
		lb.hide();
		$('#lightbox-overlay').hide();
		$('#lightbox-inner').html('');		
	} else {
		$('#lightbox-overlay').show();
		lb.show();
		w = $('#map-lightbox-content').length > 0 ? $('#map-lightbox-content').width() : $('#lightbox-content').width();
    $('#lightbox-content, #map-lightbox-content').css('position', 'absolute');
    $('#lightbox-content, #map-lightbox-content').css('top', $(window).scrollTop() + "px");
    $('#lightbox-content, #map-lightbox-content').css('left',  (($(window).width() - w) / 2) + "px");
	  if(jQuery.browser.msie) {
      if(jQuery.browser.version == '6.0') {
  	    $('#lightbox-overlay').css("top", $(window).scrollTop() + "px");
  	    $('#lightbox-overlay').css('width', $(window).width() + 'px');
  	    $('#lightbox-overlay').css('height', $(window).height() + 'px');
  	    $(window).scroll(function() {
  	      $('#lightbox-overlay').css("top", $(window).scrollTop() + "px");
  	    });
  	  }
	  }
	}
}

function load_score() {
  $.ajax({dataType:'script', url:'/quizzes/results'})
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function fluxUserVerified() {}
function fluxUserIsAnonymous() {}

var flux_user = null;
function flux_session() {
  atl_cookie = readCookie('flux_ucid');
	if(typeof Flux != 'undefined') {
	  Flux.loadContext(function(context) {
	    if(context.user) {
	      flux_user = context.user;
	      if(flux_user.communityMember) {
	        // if(flux_user.ucid != atl_cookie) {
	          // user was logged in as one community member, now logged in as another
	          // OR user has just logged in
	          $.ajax({data:'ucid='+flux_user.ucid, dataType:'script', url:'/people/flux_session', complete:fluxUserVerified});
	        //         }
	        // else  {
	        //  fluxUserVerified(); // the logged-in user matches the current one. verify them in flash;
	        // }
	      } else if(atl_cookie) {
	        // user was logged in as community member, now logged in as non-community member
	        $.ajax({dataType:'script', url:'/people/flux_session', complete:fluxUserIsAnonymous});
	        // fluxUserIsAnonymous();
	      }
	    }
			else if(atl_cookie) {
	      // user was previously logged in, not anymore
	      $.ajax({dataType:'script', url:'/people/logout', complete:fluxUserIsAnonymous});
	      // fluxUserIsAnonymous();
	    }
/*
			else {
	      $.ajax({dataType:'script', url:'/people/logout', complete:fluxUserIsAnonymous});
	    }
*/
	  });
	}
}

function dylProfileButton() {
	$('#profile-login-button').hide();
	$('#profile-refresh-button').show();
}

function dylLoginButton() {
	$('#profile-login-button').show();
	$('#profile-refresh-button').hide();
}

function dylLogin() {
	$.getJSON('/drawyourline/profile.json', function(data) {
		if(!data || !data.map_person || !data.map_person.flux_user_id || data.map_person.flux_user_id == "") {
			$('#profile-avatar').hide();
			$('#profile-login-button').show();
			$('#profile-refresh-button').hide();
		}
		else {
			var p = data.map_person;
			if(p.small_thumbnail_url && p.small_thumbnail_url != "")
				$('#avatar-box').css({ backgroundImage:"url(" + p.small_thumbnail_url + ")" });
			
			if(($('#map_action_display_name').val() == "" || $('#map_action_display_name').val() == "Anonymous") && p.display_name && p.display_name != "")
				$('#map_action_display_name').val(p.display_name);
			
			$('#profile-avatar').show();
			$('#profile-login-button').hide();
			$('#profile-refresh-button').hide();
		}
	});
	return false;
}

function drop_downs() {
  $('.drop-down').each(function() {
    var d = this;
    var p = $(this).parent();
    // hide/show drop-down
    $(p).hover(
      function () {
        $(d).show();
      },
      function () {
        $(d).hide();
      }
    );
    
    // rollover effect
    $(d).children('ul').children('li').each(function() {
      var c = this;
      $(c).hover(
        function () {
          $(c).addClass('over');
        }, 
        function () {
          $(c).removeClass('over');
        }
      );
    });
  });
}

function setup_quiz_question(number) {
  $('#response-form table tr').each(function() {
    var id = $(this).attr('id').replace(/row-/i, '');
    $(this).hover(
      function() {
        $(this).addClass('highlight');
      },
      function() {
        $(this).removeClass('highlight');
      }
    );
    $(this).click(function() {
      var r = this;
      // deselect others
      $('#quiz_response_answer_'+number+'_id').val(id);
      $('#response-form table tr').each(function() {
        var i = $(this).attr('id').replace(/row-/i, '');
        $(this).removeClass('selected');
        $('#quiz-checkbox-'+i).removeClass('on');
        $('#question_'+number+'_'+i).attr('checked', '');
      });
      $(r).addClass('selected');
      $('#quiz-checkbox-'+id).addClass('on');
      $('#question_'+number+'_'+id).attr('checked', 'checked');
    });
  });
}

var chatter_display = 'tweets';
function chatter(id) {
  if(id != chatter_display) {
    $('ul#chatter-menu').attr('class', 'flat chatter-'+id)
    $('ul.chatter-list').each(function() {
      $(this).hide();
    });
    $('ul#'+id).show();
    chatter_display = id;
  }
}



  
function clear_empty_fields() {
  $('#challenge-participants input[id$="_first_name"]').each(function(e) {
    if($(this).val() == 'First Name')
      $(this).val('');
  });
  $('#challenge-participants input[id$="_last_name"]').each(function(e) {
    if($(this).val() == 'Last Name')
      $(this).val('');
  });
  $('#challenge-participants input[id$="_email"]').each(function(e) {
    if($(this).val() == 'Email')
      $(this).val('');
  });
  
  // general info
  f = $('.general-info input[id$="_first_name"]');
  if(f.val() == 'First')
    f.val('');
  f = $('.general-info input[id$="_last_name"]');
  if(f.val() == 'Last')
    f.val('');
  $('.general-info input[id$="_address_1"]').each(function(e) {
    if($(this).val() == 'Line 1')
      $(this).val('');
  });
  $('.general-info input[id$="_address_2"]').each(function(e) {
    if($(this).val() == 'Line 2')
      $(this).val('');
  });
  $('.general-info input[id$="_city"]').each(function(e) {
    if($(this).val() == 'City')
      $(this).val('');
  });
  $('.general-info input[id$="_zip"]').each(function(e) {
    if($(this).val() == 'Zip')
      $(this).val('');
  });
  f = $('.general-info input[id$="_email"]');
  if(f.val() == 'Email')
    f.val('');
  f = $('.general-info input[id$="_telephone"]');
  if(f.val() == 'XXX-XXX-XXXX')
    f.val('');
  return true;
}

function highlightInput(input) {
  var parent = $(input).parent('dd').parent('dl');
  if(!parent.hasClass('active')) {
    $('dl').removeClass('active');
    parent.addClass('active');
  }
}

function defaultValue(obj, val) {
  $(obj).bind("focus", function(e) {
    if($(this).val() == val) {
      $(this).val('');
      $(this).addClass('focus');
    } 
  });
  $(obj).bind("blur", function(e) {
    if($(this).val() == '') {
      $(this).val(val);
      $(this).removeClass('focus');
    } else if(!$(this).hasClass('focus')) {
      $(this).addClass('focus');
    }
  });
  $(obj).trigger('blur');
}

function copyTemporaryAddress(obj) {
  if($(obj).attr('checked')) {
    $('.general-info input[id*="temporary_address"]').each(function(e) {
      id = $(this).attr('id').replace(/(.*)temporary_/i, '');
      $('.general-info input[id$="permanent_'+id+'"]').val($(this).val());
    });
  }
}


// SLIDING CONTENT PANES
var sliderHeight = "150px";

function initialize_sliders() {
	
	var hash = "";
	if(location.href.indexOf("#") > 0) {
		var parts = location.href.split('#');
		hash = parts[parts.length-1];
	}
	
  $(".slider-menu").html('<a href="#" class="button slider-down">Read More</a>');

  $('.slider').each(function () {
    var current = $(this);
    current.attr("box_h", current.height());
    current.children('.slider-menu').children('a').click(function() {
      openSlider(current); return false; 
    });

		if(hash != "" && current.find("a[name="+hash+"]").length > 0)
			current.addClass("open");
  });

	$(".slider").not(".open").css("height", sliderHeight);
	
	if(hash != "")
		location.href = location.href;
}

function openSlider(s) {
  var open_height = $(s).attr("box_h") + "px";
  $(s).animate({"height": open_height}, { duration: "slow" });
  $(s).children('.slider-menu').html('<a href="#" class="button slider-up">Close</a>');
  $(s).children('.slider-menu').children('a').unbind();
  $(s).children('.slider-menu').children('a').click(function() { closeSlider(s); return false; });
}
function closeSlider(s) {
  $(s).animate({"height": sliderHeight}, {duration: "slow" });
  $(s).children('.slider-menu').html('<a href="#" class="button slider-down">Read More</a>');
  $(s).children('.slider-menu').children('a').unbind();
  $(s).children('.slider-menu').children('a').click(function() { openSlider(s); return false; });
}



var quizResults = null;
function getQuizResults() {
	return quizResults;
}
function refreshQuizResults() {
	if(quizResults != null)
		$('#carousel')[0].loadQuizResults(quizResults);
}
function learnMoreLightbox() {
	$.ajax({complete:function(request){lightbox()}, success:function(request){$('#lightbox').html(request);}, url:'/quizzes/explanation'}); return false;
}
function shareScoreLightbox() {
	$.ajax({complete:function(request){lightbox();}, success:function(request){$('#lightbox').html(request);}, url:'/quizzes/share' }); return false;
}

// Page Load
$(function() {
  drop_downs();
  initialize_sliders();
  flux_session();
});

