// base64 code

(function($){
	
	var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
	var uTF8Encode = function(string) {
		string = string.replace(/\x0d\x0a/g, "\x0a");
		var output = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				output += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				output += String.fromCharCode((c >> 6) | 192);
				output += String.fromCharCode((c & 63) | 128);
			} else {
				output += String.fromCharCode((c >> 12) | 224);
				output += String.fromCharCode(((c >> 6) & 63) | 128);
				output += String.fromCharCode((c & 63) | 128);
			}
		}
		return output;
	};
	
	var uTF8Decode = function(input) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < input.length ) {
			c = input.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = input.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = input.charCodeAt(i+1);
				c3 = input.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
	
	$.extend({
		base64Encode: function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = uTF8Encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
			}
			return output;
		},
		base64Decode: function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = keyString.indexOf(input.charAt(i++));
				enc2 = keyString.indexOf(input.charAt(i++));
				enc3 = keyString.indexOf(input.charAt(i++));
				enc4 = keyString.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = uTF8Decode(output);
			return output;
		}
	});
})(jQuery);

// Common JavaScript code across your application goes here.

function nearest(sel) {
  var scrollTop = $(window).scrollTop();
  var minD  = 1000000;
  var minEl = null;
  $(sel).each(function(i, el) {
    var posy = $(el).offset().top;
    var dist = Math.abs(posy - scrollTop);
    if (posy != scrollTop && dist < minD) {
      minD = dist;
      minEl = $(el);
    }
  });
  return(minEl);
}

function info(message, secs) {
  secs = typeof(secs) != 'undefined' ? secs : 3000;
  container = nearest('.flash-container');
  container.find('.fi-message:first').html(message);
  var el = container.find('.flash-info:first');
  el.fadeIn(500, function() { el.fadeOut(secs); });
}

function error(message, secs) {
  secs = typeof(secs) != 'undefined' ? secs : 10000;
  var container = nearest('.flash-container');
  container.find('.fa-message:first').html(message);
  var el = container.find('.flash-alert:first');
  el.fadeIn(500, function() { el.fadeOut(secs); });
}

jQuery.ajaxSetup({
  'beforeSend': function(req) {req.setRequestHeader("Accept", "application/json")}
})

function vote(solution_id, symptom_id, n, callback) {
  if (symptom_id) {
    target_prefix = "#sym";
    target_id = symptom_id;
    url = "/solutions/" + solution_id + "/symptoms/" + symptom_id + "/vote";
    btn_prefix = "#v";
    btn_id = symptom_id;
  }
  else {
    target_prefix = "#sol";
    target_id = solution_id;
    url = "/solutions/" + solution_id + "/vote";
    btn_prefix = "#sv";
    btn_id = solution_id;
  }

  data = { "ballot[votes]": n };

  $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: function(data) {
      if(!data || !data.id) {
        error("There was an error in registering your preference");
        disable_buttons(btn_prefix, btn_id, false);
      }
      else {
        info("Thanks for your input.");
        $('#srate').html(data.success + '%');
      }
      if (callback) {
        callback();
      }
    },
    error: function(data) {
      error("There was an error in registering your preference");
      disable_buttons(btn_prefix, btn_id, false);
      if (callback) {
        callback();
      }
    }
  });
}

function disable_buttons(prefix, id, yn) {
  if (yn) {
    $(prefix + "u_" + id).attr("disabled","disabled");
    $(prefix + "d_" + id).attr("disabled","disabled");
  }
  else {
    $(prefix + "u_" + id).removeAttr("disabled");
    $(prefix + "d_" + id).removeAttr("disabled");
  }
}

function voteup(solution_id, symptom_id, callback) {
  if (symptom_id) {
    disable_buttons("#v", symptom_id, true);
  }
  else if (solution_id) {
    disable_buttons("#sv", solution_id, true);
  }
  vote(solution_id, symptom_id, "1", callback);
}

function votedown(solution_id, symptom_id, callback) {
  if (symptom_id) {
    disable_buttons("#v", symptom_id, true);
  }
  else if (solution_id) {
    disable_buttons("#sv", solution_id, true);
  }
  vote(solution_id, symptom_id, "-1", callback);
}

function exists(resource, summary, description, callback_found, callback_notfound) {
  $.ajax({
    /* this should be a POST with larger payloads */
    type: "GET",
    url: "/" + resource + "/exists",
    data: { pretty: true, "entry[summary]": summary, "entry[description]": description },
    dataType: "json",
    success: function(data) {
      if (data && data.choices) {
        $('#overlay').show();
        $('#suggestion').show();
        $('#suggestion_slider').show();
        $('#suggestion_slider').html($.base64Decode(data.choices));
        $('.choose_suggestion').click(function(e) {
          var parentdiv = $(this).parents('.box800w:first');
          var data = {
            summary: parentdiv.find('.summary:first').text(),
            description: parentdiv.find('.description:first').text(),
            token: parentdiv.find('.token:first').text(),
            id: parentdiv.find('.id:first').text()
          };
          $('#overlay').hide();
          $('#suggestion').hide();
          callback_found(data);
        });
        $('.close_suggestion').click(function(e) {
          $('#overlay').hide();
          $('#suggestion').hide();
          callback_notfound();
        });
        $('#suggestion_chosen').val(0);
        $('#suggestion_slider').cycle({
          fx: 'scrollHorz',
          prev: 'button.less',
          next: 'button.more',
          timeout: 0,
          speed: 300,
          width: 900,
          height: 600,
          prevNextClick: function(isNext, index, e) { $('#suggestion_chosen').val(e) },
        });
      }
      else {
        callback_notfound();
      }
    },
    error: function (xhr, ajaxOptions, thrownError) {
      callback_notfound();
    }
  });
}

function add_problem(obj) {
  var form        = $(obj);
  var summary     = $('input[name="symptom[summary]"]');
  var description = $('textarea[name="symptom[description]"]');
  var tags        = $('input[name="symptom[tags]"]');
  var post_data   = form.serialize();
  if (typeof(summary.val()) == 'undefined' || summary.val().match('^[\s\r\n]*$') ) {
    alert('You need to provide a problem summary');
    return false;
  }
  else if (typeof(description.val()) == 'undefined' || description.val().match('^[\s\r\n]*$') ) {
    alert('You need to provide a problem description');
    return false;
  }

  $.ajax({
    type: "POST",
    url: form.attr('action'),
    data: post_data,
    dataType: "json",
    success: function(data) {
      if(!data || !data.id) {
        error(data.error || "There was an error in adding the problem");
      }
      else {
        $(location).attr('href', '/symptoms/' + data.id + '/edit/' + data.editkey);
      }
    },
    error: function(data) {
      error("There was an error in adding the problem");
    }
  });
  return false;
}

function scroll_to(el, duration){
  duration = typeof(duration) != 'undefined' ? duration : 1000;
  $('html, body').animate({
    scrollTop: $(el).offset().top
  }, duration);
}

$(document).ready(function() {
  user = $.grep(document.cookie.split(';'), function(n) {
    return n.match('^ *user=1');
  });
  if(user.length > 0) {
    $('#loggedin').show();
  }
  else {
    $('#loggedout').show();
  }
});

