var xmlhttp = new XMLHttpRequest();
var cqResponses = []; 

// JQuery
$(document).ready(function() {
    /*
    var snippet_new_opts = { 
        target:        '#flash',
        beforeSubmit:  showRequest,
        success:       showResponse,
        dataType:      'json',
        url:           '/api/j.php'
    }; 
    */
    $(".edit_fname").editable("/api/core.php", {
         indicator : "Saving...",
         tooltip   : 'Click to edit...'
     });

    $(".edit_email").editable("/api/core.php", {
         indicator : "Saving...",
         tooltip   : 'Click to edit...',
         callback  : function(value, settings) {
            alert(value);
         }
     });

    $(".edit_bio").editable("/api/core.php", { 
        type      : "autogrow",
        submit    : 'OK',
        tooltip   : "Click to edit...",
        onblur    : "ignore",
        autogrow : {
            lineHeight : 16,
            maxHeight  : 512, 
            width      : 200
        }
    });
    // $('#new_snippet').ajaxSubmit(snippet_new_opts); 


    var dates = {};
    $('#flight_date option').slice(1).each(function() {
        var date  = $(this).val();
        var year  = date.substring(0, 4);
        var month = date.substring(5, 7) - 1;
        var day   = date.substring(8, 10);
        dates[new Date(year, month, day)] = true;
    });

    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        // buttonImage: '/i/site/icons/calendar.png',
        // buttonImageOnly: true,
        // showOn: 'button',

        onSelect: function(flight_date) {
            $('#flight_date').val(flight_date);
        },
        beforeShowDay: function(flight_date) {
            return [dates[flight_date], ''];
        },
        beforeShow: function() {
            $(this).val($('#flight_date').val());
            return {};
        }
    });


}); // Close jQuery




// Cookie Monster
function Set_Cookie( name, value, expires, path, domain, secure ) 
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}


// Ajax-ish   

function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function pop_width(w) {
	sw = f_clientWidth(); // screen width
	bw = w; // box width
	offset = (sw/2) - (bw/2);	
	var p = document.getElementById("pop");
	p.style.width = bw+"px";
  p.style.left = offset+"px";
}

function pop(w) {
	sc = f_scrollTop();
	sh = f_clientHeight();
	sw = f_clientWidth(); // screen width
	bw = w; // box width
	offset = (sw/2) - (bw/2);

  var ip = document.getElementById("pop_in");
	ip.style.display = 'none';
	
	var p = document.getElementById("pop");
	p.style.width = bw+"px";
	p.style.display = 'block';
	p.style.zIndex = 100;
  p.style.left = offset+"px";
  p.style.top = ((sc/2+sh/2)-(p.style.height+100))+"px";
	var l = document.getElementById("loader");
	l.style.display = 'block';
		
}

function loader() {
	var ip = document.getElementById("pop_in");
	ip.style.display = 'none';
	var l = document.getElementById("loader");
	l.style.display = 'block';
}

function drop() {
	var ip = document.getElementById("pop_in");
	ip.style.innerHTML = '';
	ip.style.display = 'none';
	var p = document.getElementById("pop");
	p.style.display = 'none';
}

/* Global API request entry point */
function r(action, data) {
		xmlhttp.open('POST', '/api/xml.php', true);
		xmlhttp.onreadystatechange = eval("resp_"+action);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send('action='+action+'&'+data);
}

/* 
	New (better?) version of the API req function that already 
	has the action var in the data string. Still need to pass in
	action for the response handler.
*/
function r2(action, data) {
		xmlhttp.open('POST', '/api/xml.php', true);
		xmlhttp.onreadystatechange = eval("resp_"+action);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(data);
}

/* 
	New (better?) version of the API req function that already 
	has the action var in the data string. Still need to pass in
	action for the response handler.
*/
function jmanual(action, data) {
		xmlhttp.open('POST', '/api/xml.php', true);
		xmlhttp.onreadystatechange = eval("resp_"+action);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(data);
}


/*
	Form to querystring data assembler.
	Needs to be updated to suppport checkboxes & radio buttons.
*/
function assemble_data(myform) {
	f = "";
	for(i=0; i<myform.elements.length; i++) {
		f = f + myform.elements[i].name + "=" + escape(myform.elements[i].value) + "&";
	}	
	return f;
}


function add_tags(id) {
	pop(250);
	data = "id="+id;
	action = "add_tag";
	r(action, data);	
}

function tag_this(f) {
	loader();
	id = document.getElementById("api-id")
	once = document.getElementById("api-once")
	tags = document.getElementById("api-tags")
	data = "id="+id.value+"&once="+ once.value +"&tags="+tags.value;
	action = "add_tag";
	r(action, data);
	return false;		
}

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function

function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function

function assemble_download_data(myform) {
	f = "";
	for(i=0; i<myform.elements.length; i++) {
	    if (myform.elements[i].type == 'checkbox') {
            if (myform.elements[i].checked == true) {
                f = f + myform.elements[i].name + "=" + escape(myform.elements[i].value) + "&";
            }
        }
        else if (myform.elements[i].type == 'radio') {
            if (myform.elements[i].checked == true) {
                f = f + myform.elements[i].name + "=" + escape(myform.elements[i].value) + "&";
            }
        } else {
            f = f + myform.elements[i].name + "=" + escape(myform.elements[i].value) + "&";
        }
	}	
	return f;
}

function dl() {
    myform = document.getElementById('download_resource');
    data = assemble_download_data(myform)
	pop(250);
	action = "res_download";
	// quick_display(data, 500);
	r(action, data);
}

function version(id) {
	data = "id="+id;
	action = "version";
	r(action, data);	
}

function update_profile(myform) {
	loader();
	ldata = assemble_data(myform);
	action = "res_download";
	// quick_display(ldata, 600);
	r2(action, ldata);
	return false;
}


function w_errors(errors, w){
	close_button();
	sw = f_clientWidth(); // screen width
	bw = w; // box width
	off = (sw/2) - (bw/2);
	var errlist= "";
	for (i = 0; i <= (errors.length-1); i++)
	{
		// Buffer the error list
		errlist += '<strong>'+errors[i].firstChild.nodeValue+'</strong><br />\n';
	}

	var l = document.getElementById("loader");
	l.style.display = 'none';
	
	var p = document.getElementById("pop");
	p.style.width = bw+"px";
  p.style.left = off+"px";

	var e = document.getElementById("pop_in");
	e.style.display = 'block'
	e.innerHTML = errlist;	
}

function quick_display(msg, w) {
	
	pop_width(w);
	
	var l = document.getElementById("loader");
	l.style.display = 'none';
	
	var p = document.getElementById("pop_in");
	p.innerHTML = msg;
	// p.style.width = w+"px";
	p.style.display = 'block'	

}

function dump_xml() {
	quick_display(new XMLSerializer().serializeToString(xmlhttp.responseXML), 300);
}

function update_tag_list(tags) {
	var t = document.getElementById("tag-list");
	t.innerHTML = tags;
	t.display = "block";
	new Effect.Highlight(t,{duration: 1.0});
}

function close_button() {
	var c = document.getElementById("pop-close");
	c.style.display = 'block';
	return true;
}

function resp_add_tag() {
	if(xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {	
			// Any problems? 
			var errors = xmlhttp.responseXML.getElementsByTagName('error');
			if (errors.length > 0) { // Whoops. 
				w_errors(errors, 200);
			} else {
				var action = xmlhttp.responseXML.getElementsByTagName('action');
				var a = action[0].firstChild.nodeValue;
				if (a == 'tag-form') { 
					var data = xmlhttp.responseXML.getElementsByTagName('data');
					oDomDoc = (new DOMParser()).parseFromString(data[0].firstChild.nodeValue, "text/xml"); 	
					var xmlString = new XMLSerializer().serializeToString(oDomDoc); // I honestly can't believe this works...
					close_button();
					quick_display(data[0].firstChild.nodeValue, 250);	
				} else if (a == 'tag-list') { // We're done, close this down. 
					drop();
					var data = xmlhttp.responseXML.getElementsByTagName('data');
					// alert(data[0].firstChild.nodeValue);
					// Rebuild the tag list
					update_tag_list(data[0].firstChild.nodeValue)
				}	else {
					close_button();
					quick_display("<h1>Sorry!</h1>Something went really wrong. The kids these days would call this a FAIL.", 250);	
				}	
    	}
		}
	}
}

function resp_res_download() {
	if(xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {	
			// Any problems? 
			// var errors = xmlhttp.responseXML.getElementsByTagName('error');
			errors = "";
			if (errors.length > 0) { // Whoops. 
				w_errors(errors, 200);
			} else { // Nope.
				var action = xmlhttp.responseXML.getElementsByTagName('action');
				var a = action[0].firstChild.nodeValue;
				if (a == 'download_file') {
					close_button();
					var data = xmlhttp.responseXML.getElementsByTagName('data');
					quick_display(data[0].firstChild.nodeValue, 300);
					window.location = xmlhttp.responseXML.getElementsByTagName('url')[0].firstChild.data; 
				} else if (a == 'update_profile') { 
					var data = xmlhttp.responseXML.getElementsByTagName('data');
					close_button();
					quick_display(data[0].firstChild.nodeValue, 550);
				}	else {
					close_button();
					quick_display("<h1>Sorry!</h1>Something went really wrong. The kids these days would call this a FAIL.", 250);	
				}	
    	}
		}
	}
}

function resp_version() {
  if(xmlhttp.readyState == 4){
		if (xmlhttp.status == 200) {	
			//alert(new XMLSerializer().serializeToString(xmlhttp.responseXML));
			var v = xmlhttp.responseXML.getElementsByTagName('api-version')[0].firstChild.data;
			alert("API Version: "+v);
		} else{
			alert("API Failed");
		}
	}
}


function resp_update_list_sub() {
  if(xmlhttp.readyState == 4){
      enable_subscriptions();
		if (xmlhttp.status == 200) {	
			//alert(new XMLSerializer().serializeToString(xmlhttp.responseXML));
			var v = xmlhttp.responseXML.getElementsByTagName('type')[0].firstChild.data;
			if (v == "success") {
    			l = xmlhttp.responseXML.getElementsByTagName('list')[0].firstChild.data;
			    statusmsg.innerHTML = "Newsletter subscription updated";
			    statusmsg = document.getElementById(l+"_status");
			} else {
    			l = xmlhttp.responseXML.getElementsByTagName('list')[0].firstChild.data;
			    var errormsg = xmlhttp.responseXML.getElementsByTagName('data')[0].firstChild.data;
   			    statusmsg = document.getElementById(l+"_status");
			    statusmsg.innerHTML = errormsg;
			}
			
		} else{
			alert("We're sorry, an error occured. A ticket has been created and we will attempt to notify you as soon as it has been resolved.");
		}
	}
}

function resp_create_textad() {
  if(xmlhttp.readyState == 4){
		close_button();
		if (xmlhttp.status == 200) {
    		// alert(new XMLSerializer().serializeToString(xmlhttp.responseXML));
			var errors = xmlhttp.responseXML.getElementsByTagName('error');
			if (errors.length > 0) { // Whoops. 
				w_errors(errors, 400);
			} else {
    		var data = xmlhttp.responseXML.getElementsByTagName('data');
			quick_display(data[0].firstChild.nodeValue, 400);
            }
        }
	}
}


function update_list_subscription(list, sub) {
	action = "update_list_sub";
	ldata = "action=" + action + "&list=" + list + "&flag=" + sub
	// quick_display(ldata, 600);
	r2(action, ldata);
	return false;
}

function create_textad(list, sub) {
	pop(250);
	// loader();
	action = "create_textad";
	ldata = assemble_data(document.getElementById('new_textad'));
	//quick_display(ldata, 600);
	r2(action, ldata);
	return false;
}

function toggle_list_subscription(s) {
    disable_subscriptions();

    /* Blank the status msg */
    statusmsg = document.getElementById(s.name+"_status");
    statusmsg.innerHTML = "Updating...";
    if (s.checked) {
        subvalue = "Yes"
    } else {
        subvalue = "No"
    }
    update_list_subscription(s.name, subvalue)
}

function disable_subscriptions() {
    d = document.list_subscriptions;
     for (i = 0; i < d.elements.length; i++) {
       if (d.elements[i].type == "checkbox") {
         d.elements[i].disabled=true;
       }
     }
}

function enable_subscriptions() {
    d = document.list_subscriptions;
     for (i = 0; i < d.elements.length; i++) {
       if (d.elements[i].type == "checkbox") {
         d.elements[i].disabled=false;
       }
     }
}


