var DEBUG = false;
var TIMEOUT_LIMIT = 10000;
var STALE_CHECK_TIME = 30000
var FADE_AND_SLIDE = {height : "0", opacity : "0", paddingTop : "0px", paddingBottom : "0px", marginTop : "0px", marginBottom : "0px"};
var alertCounter = 0;
var dimCounter = 0;
var overlayIDs = new Array();
var overlaySuccessCallbacks = new Array();
var overlayCancelCallbacks = new Array();

var keyRing = {
	ring		: [],
	initKeys	: function(keys) {
		for (var i = 0; i < this.initKeys.arguments.length; i++)
			this.ring[this.initKeys.arguments[i]] = 0;
	},
	acquireKey	: function(key) {
		return this.ring[key]++ < 1;
	},
	checkKey	: function(key) {
		return this.ring[key] < 1;
	},
	releaseKey	: function(key) {
		this.ring[key] = 0;
	}
}

$(document).ready(function() {
 	keyRing.initKeys("editFollowing");
	$("#header .head_search .input_txt, #content .event_search .input_txt").focus(function() {
		if (($(this).val() == null || $(this).val() == "") || ($(this).val() == "Search Events")) $(this).val("");
	});
	$("#header .head_search .input_txt, #content .event_search .input_txt").blur(function() {
		if ($(this).val() == null || $(this).val() == "") $(this).val("Search Events");
	});
	$("#header .input_email, #header .input_password").focus(function() {
		if ($(this).val() == null || $(this).val() == "") $(this).addClass("input_active");
	});
	$("#header .input_email, #header .input_password").blur(function() {
		if ($(this).val() == null || $(this).val() == "") $(this).removeClass("input_active");
	});
	$("#header .head_search .input_txt, #content .event_search .input_txt").focus(function() {
		var div = this;
        setTimeout(function(){
          if ($(div).val() != null && $(div).val() != "") {
            $(div).addClass("input_active")
          };
        }, 300); 
	    setTimeout(function(){
          if ($(div).val() != null && $(div).val() != "") {
            $(div).addClass("input_active")
          };
        }, 1000); 
	});
	$("#header .head_search .input_txt, #content .event_search .input_txt").focus(function() {
		var div = this;
        setTimeout(function(){
          if ($(div).val() != null && $(div).val() != "") {
            $(div).addClass("input_active")
          };
        }, 300); 
	    setTimeout(function(){
          if ($(div).val() != null && $(div).val() != "") {
            $(div).addClass("input_active")
          };
        }, 1000); 
	});
	$("#input_email, #input_password").each(function() {
       var div  = this;	
	   setTimeout(function() {
          if ($(div).val() != null && $(div).val() != "") {
             $(div).addClass("input_active")
          };
       }, 300); 	
       setTimeout(function() {
          if ($(div).val() != null && $(div).val() != "") {
             $(div).addClass("input_active")
          };
       }, 1000); 
	});
	$("#content .sidebox .hide_show").click(function () {
		$(this).next().children(":first").toggle();
		if ($(this).html()=="Hide") $(this).html("Show");
		else $(this).html("Hide");
	});
	/*$("#content .sidebox .hide_show_h3").click(function () {
		$(this).next().next().toggle();
		if ($(this).next().html()=="Hide") $(this).next().html("Show");
		else $(this).next().html("Hide");
	});*/
});



 function loadSidebarBox(id,type,tagParameters){
 	$.ajax({
        url			: "/shared/ajax_sidebarBox/",
		data		: {"id" : id,
						"type" : type,
						"tagParameters":tagParameters	},
        cache		: false,
        timeout		: TIMEOUT_LIMIT,
		dataType	: "json",
		beforeSend	: function() {
		},
        success	 	: function(data) {
			$('#'+id).html(data[0]);
		},
        error	 	: function(xhr, type, error) {
			if (DEBUG) showMessage("error",xhr.status+" "+ xhr.responseText+" "+ type+" "+ error,false,"fetch-photos");
			
        }
    });
 }
 function editFollowing(eventid,flag,refresh,userid) {
 	if (!keyRing.acquireKey("editFollowing")) return;
	$.ajax({
		url			: "/event/ajax_edit_following/" + eventid,
		data		: {"flag"				: flag,
					   "authenticity_token" : $("#authenticity_token").val()},
		cache		: false,
		timeout		: TIMEOUT_LIMIT,
		dataType 	: "json",
		type		: "POST",
		beforeSend	: function() {
			startLoading(((flag == "start") ? "Adding you to" : "Removing you from") + " this event...");
		},
		success		: function(data) {
			$("#startFollow"+eventid).toggle();
			$("#stopFollow"+eventid).toggle();
			if (refresh){
				location.reload();
			}else{
				if (data[0]){
					$('#follower_pics').html(data[1]+$('#follower_pics').html());
				}else{
					$('#event_follower_'+data[1]).html("");
				}
			}
		},
		error		: function(xhr, type, error) {
			if (xhr.status == 401) forceSignin("message=auth", function() { editFollowing(eventid,flag,true); });
			else {
				showMessage("error","The server encountered an error.  Please try again later.",false,"editFollowing",xhr.responseText);
				if (DEBUG) {showMessage("error",xhr.status+ " "+xhr.responseText+" "+type+" "+error,false,"editFollowing")}
			}
		},
		complete	: function() {
			doneLoading();
			keyRing.releaseKey("editFollowing");
		}
	});
 }
function setFormFocus(id){
		var focusSet = false;
		$(id + " input").each(function(){
			if (!focusSet && ($(this).val() == "" || $(this).val() == null)) {
				$(this).focus();
				focusSet = true;
			}
		});
}
mergeAnchorAttributes()
function mergeAnchorAttributes(){
	try {
		var anchorStr = location.hash
		if (anchorStr && anchorStr.length > 1) {
			var newStr = location.search
			if (newStr == null || newStr == "") {
				newStr = "?"
			}
			var str = anchorStr.substring(1);
			var anchorArray = str.split("&");
			for (var i = 0; i < anchorArray.length; i++) {
				var entry = anchorArray[i].split("=")
				if (entry.length == 2) {
					newStr = replaceParameter(entry[0], entry[1], newStr)
				}
			}
			location = (location + "").split("?")[0].split("#")[0] + newStr
		}
	}catch(e){
		
	}
}
var delayedInterval;
function setDelayedInterval(func,interval,delay){
	setTimeout(function(){
		delayedInterval = setInterval(func,interval);
	},delay);
}


function replaceParameter(attributeName,attributeValue,oldStr){
	var i=0;
	var notFound = true;
	var newStr = "?";
	if (oldStr && oldStr.length>1){
		var str = oldStr.substring(1);
		var paramsArray = str.split("&");
		for (i=0;i<paramsArray.length;i++){
			if (i>0){
				newStr += "&"
			}
			var entry = paramsArray[i].split("=")
			if (entry.length==2 && entry[0] == attributeName){
				newStr += entry[0] + "=" + attributeValue
				notFound = false;
			}else{
				newStr += entry[0] + "=" + entry[1]
			}
		}
	}
	//we dedin t find it in the original string
	if(notFound){
		if (i>0){
			newStr += "&"
		}
		newStr += attributeName + "=" + attributeValue
	}
	return newStr;
}
function getAttribute(attributeName,paramString){
	if (paramString && paramString.length>0){
		var str = paramString.substring(1);
		var paramsArray = str.split("&");
		for (var i=0;i<paramsArray.length;i++){
			var entry = paramsArray[i].split("=")
			if (entry.length==2 ||entry[0] == attributeName){
				return entry[1]
			}
		}
	}
	return null;
}

function showMessage(type, text){
	showMessage(type,text,false,"") 
}

function showMessage(type,text,isPopup,from,trackingDetails) {
	$("#alertMessages"+(isPopup?"-popup":"")).removeClass("message_error");
	$("#alertMessages"+(isPopup?"-popup":"")).removeClass("message_warning");
	$("#alertMessages"+(isPopup?"-popup":"")).removeClass("error_info");
	$("#alertMessages"+(isPopup?"-popup":"")).addClass("message_"+type);
	$("#alertMessages"+(isPopup?"-popup":"")).html(""+text+"<br/>");
	$("#alertMessages"+(isPopup?"-popup":"")).show();
	track(type,'messageBox-'+from,text+" | "+trackingDetails);
}
function resetMessages(){
	$("#alertMessages").hide();
	$("#alertMessages").html("");
}

function closePromo() {
	document.cookie = "promo=closed; path=/;";
	$("#promo").animate(FADE_AND_SLIDE, 500, function(){ $(this).hide();	});
	$("#showPromo").show();
}
function openPromo() {
	document.cookie = "promo=open; path=/;";
	$("#promo").height(230).css({
		opacity: 1
	});
	$('#promo').show();
	$("#showPromo").hide();
}


function seeDescription(eventID, show, hide) {
	$("#description" + eventID + show).show(0);
	$("#description" + eventID + hide).hide(0);
}

function scrollToTop(duration) {
	var scrollingInterval = setInterval(function(){
		window.scrollBy(0, -25);
		if (window.pageYOffset == 0) clearInterval(scrollingInterval);
	}, 25 * duration / window.pageYOffset);
}

function startLoading(message) {
	if ($("#loading_box").css("display") == "none")
		$("#loading_box").html("<p>" + ((typeof message == "undefined") ? "Loading..." : message) + "</p>").slideToggle("fast");
}

function doneLoading() {
	if ($("#loading_box").css("display") != "none")
		$("#loading_box").slideToggle("slow");
}

function pushOverlay(id, overlay, successCallback, cancelCallback, onLoad) {
	dim();
	$("body").append('<div id="' + id + '" class="layer"></div>');
	$("#" + id).load(overlay, null, function() { 
		$(this).fadeIn('fast');
		if (typeof onLoad == "function") onLoad();
	});
	overlaySuccessCallbacks.push((typeof successCallback == "undefined") ? function() {} : ((typeof successCallback == "string") ? function() { window.location = successCallback; } : successCallback));
	overlayCancelCallbacks.push((typeof cancelCallback == "undefined") ? function() {} : ((typeof cancelCallback == "string") ? function() { window.location = cancelCallback; } : cancelCallback));
	overlayIDs.push(id);
}

function popOverlay(action) {
	var successCallback = overlaySuccessCallbacks.pop();
	var cancelCallback = overlayCancelCallbacks.pop();
	$("#" + overlayIDs.pop()).remove();
	undim();
	if ((typeof action == "undefined") || (action == "success")) successCallback();
	else if (action == "cancel") cancelCallback();
}

function dim() {
	$("body").append('<div id="dimmer' + dimCounter + '" class="dimmer"></div>');
	$("#dimmer" + (dimCounter++)).fadeIn('fast');
}

function undim(){
	$("#dimmer" + (--dimCounter)).remove();
}

function tag(jquery_object) {
	return $("<div>").append(jquery_object.clone()).html();
}

function filterUpdates(filter) {
	if (filter == 'comments') {
		$('.txt_comment_wrapper, .txt_comment_single_update').show();
		$('.photo_comment, .photo_comment_single_update').hide();
		$('#control_viewtype_comments').addClass("on");
		$('#control_viewtype_all, #control_viewtype_photos').removeClass("on");
	} else if (filter == 'photos') {
		$('.photo_comment, .photo_comment_single_update').show();
		$('.txt_comment_wrapper, .txt_comment_single_update').hide();
		$('#control_viewtype_photos').addClass("on");
		$('#control_viewtype_all, #control_viewtype_comments').removeClass("on");
	} else if (filter == 'all') {
		$('.txt_comment_wrapper, .photo_comment, .txt_comment_single_update, .photo_comment_single_update').show();
		$('#control_viewtype_all').addClass("on");
		$('#control_viewtype_comments, #control_viewtype_photos').removeClass("on");
	}
}

function clearCookies() {
	document.cookie = "authKey=;  path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
	document.cookie = "userName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
	document.cookie = "userID=;   path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
	document.cookie = "email=;	  path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
function clearFacebookCookies(){
	document.cookie = "facebook_session_key=;	path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
	document.cookie = "facebook_id=;	  		path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
	
}

function track(category,action,label,value){
	try {
		pageTracker._trackEvent(category, action, label, value);
	}catch(e){
		try {
			pageTracker._trackEvent("error", "tracking", err.description);
		}catch (e2) {
			//do nothing
		}
	}
}


/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {

  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
  	//alert ('init');
    callback();
  } else {
    FB_RequireFeatures(["XFBML", "CanvasUtil","Api","Connect"], function() {
        FB.FBDebug.logLevel = 4;
        FB.FBDebug.isEnabled = true;
        // xd_receiver.php is a relative path here, because The Run Around
        // could be installed in a subdirectory
        // you should prefer an absolute URL (like "/xd_receiver.php") for more accuracy
		FB.Facebook.init(window.api_key, window.xd_receiver_location);
  
        window.is_initialized = true;
        callback();
      });
  }
  
}

function facebook_button_onclick(next) {
	if (next == null){
		next='';
	}
  ensure_init(function() {

	FB.Facebook.get_sessionState().waitUntilReady(function() {
			
		  var session = FB.Facebook.apiClient.get_session();
		  var user = FB.Facebook.apiClient.get_session() ?
            FB.Facebook.apiClient.get_session().uid :
            null;

          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }

          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          //refresh_page();
		  
		  FB.Connect.showPermissionDialog("publish_stream,offline_access,email",function(){
				post(window.facebook_authenticate_location, {
					next:next,
					facebook_session_key:FB.Facebook.apiClient.get_session().session_key,
					facebook_session_secret:FB.Facebook.apiClient.get_session().secret,
					facebook_id:FB.Facebook.apiClient.get_session().uid
				})
				
				return false;
			});	
        });
    });
}

function facebook_button_connect_onclick() {
  ensure_init(function() {
	 FB.Connect.requireSession(function() {
 
		  var user = FB.Facebook.apiClient.get_session() ?
            FB.Facebook.apiClient.get_session().uid :
            null;

          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }

          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          //refresh_page();
		  FB.Connect.showPermissionDialog("publish_stream,offline_access,email",function(){
          		connectFacebook();
			});	
        });
    });
}

 function connectFacebook() {
	if (keyRing.acquireKey("post")) {
		 
		$.ajax({
			url: "/settings/ajax_facebook_connect/",
			data: {
			},
			cache: false,
			timeout: TIMEOUT_LIMIT,
			type: "POST",
			beforeSend: function(){
			},
			success: function(data){
				location.reload()
			},
			error: function(xhr, type, error){
				
				showMessage("error", "The server encountered an error.  Please try again later.", false, "postTwitterSettings", xhr.responseText);
				if (DEBUG) 
					showMessage("error", xhr.status + " " + xhr.responseText + " " + type + " " + error, false, "postTwitterSettings");
				
			},
			complete: function(){
				
				keyRing.releaseKey("post");
			}
		});
	}
	return false;
 }
 
 function post(URL, PARAMS) {
	var temp=document.createElement("form");
	temp.action=URL;
	temp.method="POST";
	temp.style.display="none";
	for(var x in PARAMS) {
		var opt=document.createElement("textarea");
		opt.name=x;
		opt.value=PARAMS[x];
		temp.appendChild(opt);
	}
	var opt=document.createElement("textarea");
	opt.name="authenticity_token";
	opt.value=$("#authenticity_token").val();
	temp.appendChild(opt);
	document.body.appendChild(temp);
	temp.submit();
	return temp;
}
