$.ajaxSetup({
    cache: false
});

$(document).ready(function() {
	// ----- For signing up
	$('#subscriptions a').click(function() {
		
		// AJAX call to subscribe
		var elemID = $(this).attr('id');
		var split = elemID.split('_');
		
		// We can skip the first element of the split array (that's just there to make the ID valid in the element)
		var device = split[1];
		
		$.get('/subscriptions/addSubscription/' + device, function (data) {
			
//			alert(data);
			
			var json = data.parseJSON();
			
			if (json.Error)
			{
				alert(json.Error);
			}
			else
			{
				alert(json.Success);
				window.location.reload(); // So that the widget now shows the user is subscribed
			}
		});
	});
	
	// ----- For subscribing to all file updates
	if ($('#SubscriberSubscribeAllFileUpdates').attr('checked') == true)
	{
		$('.individualDevices').addClass('alt');
	}
	else
	{
		$('.individualDevices').removeClass('alt');
	}
	
	$('#SubscriberSubscribeAllFileUpdates').change(function() {
		if ($(this).attr('checked') == true)
		{
			$('.individualDevices').addClass('alt');
		}
		else
		{
			$('.individualDevices').removeClass('alt');
		}
	});
	
	// ----- For Unsubscribing
	$('#unsubscribeAll').click(function() {
		if ($(this).attr('checked') == true)
		{
			if (confirm('Are you sure you would like to permanently unsubscribe from all PLX Alerts?'))
			{
				$("input[id^='cb_']").removeAttr('checked');
			}
			else
			{
				$(this).removeAttr('checked');
			}
		}
	});
	
	// ----- For signing up for Press Release subscriptions
	$('#prsubscription.not_subscribed a').click(function() {
		
		$.get('/subscriptions/addPRSubscription', function (data) {
			
//			alert(data);
			
			var json = data.parseJSON();
			
			if (json.Error)
			{
				alert(json.Error);
			}
			else
			{
				alert(json.Success);
				window.location.reload(); // So that the widget now shows the user is subscribed
			}
		});
	});	
	
	// ----- File updates checkbox
	$('#cb_2').click(function() {
		if ($(this).attr('checked') == true)
		{
			$('#fileupdate_dyk').slideDown();
		}
		else
		{
			$('#fileupdate_dyk').slideUp();
		}
	});
});


/**
 * Change the email preference for File Updates
 * @param int uid - Subscriber ID
 * @param int current - what it is currently (0 or 1)
 * @return void
 */
function changeEmailPref(uid, current)
{
	var changeTo = 1;
	
	if (current == 1)
		changeTo = 0;
	
	$.get('/subscriptions/changeFileUpdateEmailPreference/' + uid + '/' + changeTo, function(data) {
		
		var json = data.parseJSON();
		
		if (json.Error)
		{
			alert(json.Error);
		}
		else
		{
			alert(json.Success);
			window.location.reload();
		}
	});
	
}


/**
 * Unsubscribe from a particular device
 * @param int id - Device ID
 * @param string li - Element ID to fade out
 * @return void
 */
function unsubscribeDevice(id, li)
{
	$(document).ready(function() {
		
		if (confirm('Are you sure you would like to unsubscribe from updates to this device?\nTo re-subscribe, you can go back to this device\'s page and click on the File Update Alerts box.'))
		{
			$.get('/subscriptions/removeSubscription/' + id, function(data) {
				
				var json = data.parseJSON();
				
				if (json.Error)
				{
					$('#jsMsg').html('<p class="error">' + json.Error + '</p>');
					$('#jsMsg').fadeIn();
				}
				else
				{
					$('#' + li).fadeOut();
					
					$('#jsMsg').html('<p class="note">' + json.Success + '</p>');
					$('#jsMsg').fadeIn();
				}
			});
		}
	});
}


//The following block implements the string.parseJSON method
(function (s) {
  // This prototype has been released into the Public Domain, 2007-03-20
  // Original Authorship: Douglas Crockford
  // Originating Website: http://www.JSON.org
  // Originating URL    : http://www.JSON.org/JSON.js

  // Augment String.prototype. We do this in an immediate anonymous function to
  // avoid defining global variables.

  // m is a table of character substitutions.

  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  s.parseJSON = function (filter) {

    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {

          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.

          if (typeof filter === 'function') {

            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }

            j = walk('', j);
          }
          return j;
        }
      } catch (e) {

      // Fall through if the regexp test fails.

      }
      throw new SyntaxError("parseJSON");
    };
  }
) (String.prototype);
// End public domain parseJSON block
