// JavaScript Document

// checkform();
// This function checks the form on schedule.php for valid input,
// including valid dates and names.
function checkform()
{
	if (!byid("new_comingsoon").checked && !is_valid_date(byid("new_startdate").value))
	{
		alert("Start date is not valid.");
		return false;
	}

	if ((byid("new_type").value == "movie") && !byid("new_comingsoon").checked && !is_valid_date(byid("new_enddate").value))
	{
		alert("End date is not valid.");
		return false;
	}

	if (!is_valid_date(byid("new_displaydate").value))
	{
		alert("Display date is not valid.");
		return false;
	}

	// Validation has passed
	return true;
}

function typechanged()
{
	//alert(byid("new_comingsoon"));
	if(byid("new_comingsoon").checked) {
		byid("new_startdate_label").style.display = "none";
		byid("new_startdate").style.display = "none";
		byid("new_enddate_label").style.display = "none";
		byid("new_enddate").style.display = "none";
	}
	else
	{
		byid("new_startdate_label").style.display = "block";
		byid("new_startdate").style.display = "block";

		if(byid("new_type").value == "feature" || byid("new_type").value == "indie" || byid("new_type").value == "movie" || byid("new_type").value == "midnight")
		{
			byid("new_startdate_label").innerHTML = "Event Start:";
			byid("new_enddate_label").style.display = "block";
			byid("new_enddate").style.display = "block";
		}
		else
		{
			byid("new_startdate_label").innerHTML = "Event Date:";
			byid("new_enddate_label").style.display = "none";
			byid("new_enddate").style.display = "none";
		}
	}
}

// is_valid_date(...)
// This function returns true if the string passed in to it is
// a valid date in YYYY-MM-DD format.
function is_valid_date(str)
{
	yearstr = str.substr(0,4);
	monthstr = str.substr(5,2);
	daystr = str.substr(8,2);

	if(parseInt(yearstr,10) < 2006)
		return false;

	if(parseInt(monthstr,10) < 0 || parseInt(monthstr,10) > 12)
		return false;

	if(parseInt(monthstr,10) < 0 || parseInt(monthstr,10) > 31)
		return false;

	return true;
}

// byid(elid)
// Returns a reference to the element passed in.
// By using document.getElementById(...);
function byid(elid)
{
	return document.getElementById(elid);
}

// JavaScript Document
var xmlhttp;
var xmldiv;

function changecontent(url,divid)
{
xmlhttp=null
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmldiv = document.getElementById(divid);
  xmldiv.innerHTML = '<img src="images/ajax-loader.gif" />';
  xmlhttp.onreadystatechange=state_Change;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
  {
  // if "OK"
  if (xmlhttp.status==200)
    {
    xmldiv.innerHTML = xmlhttp.responseText;
	try
{
	InitContext();
}
catch (ex)
{
	//do nuthin.
}
    }
  else
    {
	xmldiv.innerHTML = "Problem retrieving XML data<br /><br />" + xmlhttp.statusText;
    }
  }
}

function expand(strid)
{
	alert(strid);
}

function moveup(category)
{
	for(var i = 1; i < 6; i+=1)
	{
		var j = i + 1;
		document.getElementById(category + i).value = document.getElementById(category + j).value;
	}
	document.getElementById(category + "6").value = "";

}

function SubmitForm()
{
	xmlhttp=null
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  var src = ""
  src = src + "Theater=" + getval("Theater");
  src = src + "&MovieName=" + getval("MovieName");
  src = src + "&MovieSchedule=" + getval("MovieSchedule");
  src = src + "&Movie1=" + getval("Movie1");
  src = src + "&Movie2=" + getval("Movie2");
  src = src + "&Movie3=" + getval("Movie3");
  src = src + "&Movie4=" + getval("Movie4");
  src = src + "&Movie5=" + getval("Movie5");
  src = src + "&Movie6=" + getval("Movie6");
  src = src + "&Midnight1=" + getval("Midnight1");
  src = src + "&Midnight2=" + getval("Midnight2");
  src = src + "&Midnight3=" + getval("Midnight3");
  src = src + "&Midnight4=" + getval("Midnight4");
  src = src + "&Midnight5=" + getval("Midnight5");
  src = src + "&Midnight6=" + getval("Midnight6");

  var mc = document.getElementById("mainContent");
	mc.innerHTML = '<img src="images/ajax-loader.gif" />';
  xmlhttp.onreadystatechange=state_Change;
  xmlhttp.open("POST","web_settings.php",true);
   xmlhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');

  xmlhttp.send(src);
  }
}

function ChangeContent(method,url,src,divid)
{
	xmlhttp=null
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
	  xmldiv = document.getElementById(divid);
	  xmldiv.innerHTML = '<img src="images/ajax-loader.gif" />';
	  xmlhttp.onreadystatechange=state_Change;
	  xmlhttp.open(method,url,true);

	  if(method == "POST")
	  {
		  xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		  xmlhttp.send(src);
	  }
	  else
	  {
		  xmlhttp.send(null);
	  }
  }
}

function getval(the_id)
{
return document.getElementById(the_id).value
}

function showsubs(button_id)
{
	for(var i = 1; i <= 120; i += 1)
	{
		try
		{
		document.getElementById("sub" + i).style.display = "none";
		}
		catch(err)
		{
		alert(err.description);
		}
	}
	for(var i = (button_id * 6) - 5; i <= (button_id * 6); i += 1)
	{
		try
		{
		document.getElementById("sub" + i).style.display = "block";
		}
		catch(err)
		{
		//alert(err.description);
		}
	}
}

function showmenu(button_id)
{
	var _divContext = byid('divContext');
	_divContext.style.display = "block";

	var a_id = byid('activeid');
	var a_caption = byid('activecaption');
	var a_color = byid('activecolor');

	a_id.value = button_id;
	a_caption.value = byid('button' + button_id + "_itemname").value;
	a_color.value = byid('button' + button_id + "_color").value;
	a_color.style.background = a_color.value;

        /* hide the menu first to avoid an &quot;up-then-over&quot; visual effect
        _divContext.style.display = 'none';
        _divContext.style.left = event.clientX + scrollLeft + 'px';
        _divContext.style.top = event.clientY + scrollTop + 'px';
        _divContext.style.display = 'block';*/
}




// comes from prototype.js; this is simply easier on the eyes and fingers
function byid(id)
{
    return document.getElementById(id);
}

function updatebutton()
{
	var a_id = byid('activeid');
	var a_caption = byid('activecaption');
	var a_color = byid('activecolor');

	byid('button' + a_id.value + "_itemname").value = a_caption.value;
	byid('button' + a_id.value + "_color").value = a_color.value;
	byid('button' + a_id.value).value = a_caption.value;
	byid('button' + a_id.value).style.background = a_color.value;

	byid('divContext').style.display = "none";
}

function updatesub()
{
	var a_id = byid('activesubid');
	var a_caption = byid('cCaption');
	var a_name = byid('cItemName');
	var a_color = byid('cColor');
	var a_price = byid('cItemPrice');
	var a_z = byid('cZGroup');

	byid('sub' + a_id.value + "_cCaption").value = a_caption.value;
	byid('sub' + a_id.value + "_cItemName").value = a_name.value;
	byid('sub' + a_id.value + "_cZGroup").value = a_z.value;
	byid('sub' + a_id.value + "_cColor").value = a_color.value;
	byid('sub' + a_id.value + "_cItemPrice").value = a_price.value;
	byid('sub' + a_id.value).value = a_caption.value;
	byid('sub' + a_id.value).style.background = a_color.value;

	byid('sub_divContext').style.display = "none";
}

function clear_button()
{
		var a_id = byid('activeid');

	byid('button' + a_id.value + "_itemname").value = "";
	byid('button' + a_id.value + "_color").value = "#000000";
	byid('button' + a_id.value).value = "";
	byid('button' + a_id.value).style.background = "#000000";

	byid('divContext').style.display = "none";
}

function clear_sub()
{
	var a_id = byid('activesubid');

	byid('sub' + a_id.value + "_cCaption").value = "";
	byid('sub' + a_id.value + "_cItemName").value = "";
	byid('sub' + a_id.value + "_cZGroup").value = "";
	byid('sub' + a_id.value + "_cColor").value = "#000000";
	byid('sub' + a_id.value + "_cItemPrice").value = "0";
	byid('sub' + a_id.value).value = "";
	byid('sub' + a_id.value).style.background = "#000000";

	byid('sub_divContext').style.display = "none";
}

function create_xml(ext)
{
	//Make a new XML document out of all of the form variables here.
	//Then send it as a long POSTed string to be written to the new file

var T = byid('tarea');
T.value = '<?xml version="1.0" standalone="yes"?>';
	writeline(T,"<Register>");

	//Write out the buttons
	for (var i = 1; i <= 20; ++i)
	{
		try
		{
		writeline(T,"<button id=\"" + i + "\" ");
		wr(T,"itemname=\"" + byid('button' + i + "_itemname").value + "\" ");

		var a = 255; //Full alpha value
		var r = parseInt(byid('button' + i + '_color').value.substring(1,3),16);
		var g = parseInt(byid('button' + i + '_color').value.substring(3,5),16);
		var b = parseInt(byid('button' + i + '_color').value.substring(5,7),16);

		var colval = (a<<24 | r<<16 | g<<8 | b); //Put all o thy' bits in the right place.
		//code from http://www.adobe.com/devnet/flash/articles/image_api_02.html

		wr(T,"color=\"" + colval + "\" ");
		wr(T,"/>");
		}
				catch(err)
		{
		alert(err.description);
		}

	}


	//Write out the sub-buttons
	for (var i = 1; i <= 120; ++i)
	{
		writeline(T,"<Sub cID=\"" + i + "\" ");
		wr(T,"cItemName=\"" + byid('sub' + i + "_cItemName").value + "\" ");
		wr(T,"cCaption=\"" + byid('sub' + i + "_cCaption").value + "\" ");
		wr(T,"cItemPrice=\"" + byid('sub' + i + "_cItemPrice").value + "\" ");

		var a = 255; //Full alpha value
		var r = parseInt(byid('sub' + i + '_cColor').value.substring(1,3),16);
		var g = parseInt(byid('sub' + i + '_cColor').value.substring(3,5),16);
		var b = parseInt(byid('sub' + i + '_cColor').value.substring(5,7),16);

		var colval = (a<<24 | r<<16 | g<<8 | b); //Put all o thy' bits in the right place.
		//code from http://www.adobe.com/devnet/flash/articles/image_api_02.html

		wr(T,"cColor=\"" + colval + "\" ");
		wr(T,"/>");
	}


	writeline(T,"</Register>");

	ChangeContent("POST","update_button_config.php","file=" + byid('FN').value + ext + "&xml=" + T.value,"xmlarea");

}

function writeline(obj, ln)
{
obj.value += ("\n" + ln);
}

function wr(obj, txt)
{
	obj.value += txt;
}





function prices(){

OpenWindow=window.open("http://www.rosebudcinema.com/price.htm","Prices",
"height=400,width=400,toolbar=no,resizable=0,menubar=no,scrollbars=no,location=no,status=no,left=10,top=10,");
}

function ticketfaq(){
OpenWindow=window.open("http://www.rosebudcinema.com/ticketfaq.php","Prices",
"height=400,width=400,toolbar=no,resizable=0,menubar=no,scrollbars=yes,location=no,status=no,left=10,top=10,");
}

/************************************

 * Load in a list of times via AJAX *
 * for shop.php                     *
 ************************************/
function loadtimes(id,dt){
	//Selectel = $("event_" + id + "_times");
		new Ajax("ajax/get_showtime_list.php", {
		data: "eventid=" + id + "&showdate=" + dt,
		method: 'get',
		update: $("event_" + id + "_times")
	}).request();

}

/******************************************
 * Load applicable tickets for a showtime *
 ******************************************/

 var ticketSlideHolder = new Array();

function loadticketopts(id,tm){
	var selectedtime = new Date(new Date().toDateString() + ' ' + tm);
	var matineetime = new Date(new Date().toDateString() + ' ' + "17:30");
	if (!ticketSlideHolder['event_' + id + '_tickets_regular'])
		ticketSlideHolder['event_' + id + '_tickets_regular'] = new Fx.Slide('event_' + id + '_tickets_regular');
	if (!ticketSlideHolder['event_' + id + '_tickets_matinee'])
		ticketSlideHolder['event_' + id + '_tickets_matinee'] = new Fx.Slide('event_' + id + '_tickets_matinee');
	if (!ticketSlideHolder['event_' + id + '_tickets_nonte'])
		ticketSlideHolder['event_' + id + '_tickets_nonte'] = new Fx.Slide('event_' + id + '_tickets_none');


	//alert(tm + " " + selectedtime + " " + matineetime);
	if (tm == "")
	{
		//alert("Noslide");
		ticketSlideHolder['event_' + id + '_tickets_regular'].slideOut();
		ticketSlideHolder['event_' + id + '_tickets_matinee'].slideOut();
		ticketSlideHolder['event_' + id + '_tickets_nonte'].slideIn();
	}
	else
	{
		if (selectedtime < matineetime)
		{
			//alert("matslide");
			ticketSlideHolder['event_' + id + '_tickets_regular'].slideOut();
			ticketSlideHolder['event_' + id + '_tickets_matinee'].slideIn();
			ticketSlideHolder['event_' + id + '_tickets_nonte'].slideOut();
		}
		else
		{
			//alert("regslide");
			ticketSlideHolder['event_' + id + '_tickets_regular'].slideIn();
			ticketSlideHolder['event_' + id + '_tickets_matinee'].slideOut();
			ticketSlideHolder['event_' + id + '_tickets_nonte'].slideOut();
		}
	}
}

function add_ticket_to_cart(event_id, ticket_id, price, event_time_id) {
    // add the ticket (with the specified price, for the given event) to the cart
    // writes the cart out to the element with id shoppingcart
    var req = new Request.HTML({
        url: "ajax/add_tickets_to_cart.php",
        data: "event_id=" + event_id + "&ticket_id=" + ticket_id + "&price=" + price + "&event_time_id=" + event_time_id,
        onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
            //Clear the text currently inside the results div.
            $('shoppingcart').set('text', '');
            //Inject the new DOM elements into the results div.
            $('shoppingcart').set('html', responseHTML); //adopt(responseTree);
            //alert($('shoppingcart').innerHTML);
            /**
            * You usually reuse ONE instance.
            * The 4 instances we'll reuse here represent different options.
            */
            var notification = new Roar({
                position: 'lowerRight'
            });
            notification.alert(
							"Ticket Added",
							"Your ticket has been added to the shopping cart. Click Check Out to complete purchase."
						);
        },
        //Our request will most likely succeed, but just in case, we'll add an
        //onFailure method which will let the user know what happened.
        onFailure: function() {
            $('shoppingcart').set('text', 'The request failed.');
        }
    });
    req.send();
    /*	new Ajax("ajax/add_tickets_to_cart.php", {
    data: "event_id=" + event_id + "&ticket_id=" + ticket_id + "&price=" + price,
    method: 'get',
    update: $("shoppingcart")
    }).request();*/
}

/**
*
* @access public
* @return void
**/
function reset_cart() {
    var req = new Request.HTML({
        url: "ajax/reset_cart.php",
        onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
            //Clear the text currently inside the results div.
            $('shoppingcart').set('text', '');
            //$('shoppingcart').set('html',"<span style='font-weight:bold;'>bold test</span>");
            //Inject the new DOM elements into the results div.
            //alert(html);
            $('shoppingcart').set('html', responseHTML);
        },
        //Our request will most likely succeed, but just in case, we'll add an
        //onFailure method which will let the user know what happened.
        onFailure: function() {
            $('shoppingcart').set('text', 'The request failed.');
        }
    });
    req.send();
}

function print_cart(currentVenue) {
    var req = new Request.HTML({
        url: "ajax/print_cart.php",
        data: "venue=" + currentVenue,
        method: 'post',

        onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
            //Clear the text currently inside the results div.
            $('shoppingcart').set('text', '');
            //Inject the new DOM elements into the results div.
            $('shoppingcart').set('html', responseHTML);
            if ($('fb-modalCart') != null) {
                $('fb-modalCart').fade('in');

                /* hiders */
                $('fb-closeCart').addEvent('click', function (e) { $('fb-modalCart').fade('out'); window.location = "shop.php?venue=" + $('cartVenue').value });

                $('fb-emptyCart').addEvent('click', function (e) { $('fb-modalCart').fade('out'); reset_cart(); });

                window.addEvent('keypress', function (e) { if (e.key == 'esc') { $('fb-modalCart').fade('out'); } });

                $(document.body).addEvent('click', function (e) {
                    if ($('fb-modalCart') != null) {
                        if ($('fb-modalCart').get('opacity') == 1 && !e.target.getParent('.generic_dialog')) {
                            e.stop();
                        }
                    }
                });
            }
        },
        //Our request will most likely succeed, but just in case, we'll add an
        //onFailure method which will let the user know what happened.
        onFailure: function () {
            $('shoppingcart').set('text', 'The request failed.');
        }
    });
    req.send();
}

function convert_price_to_int(pricestr) {
    if (pricestr.indexOf('$') != -1) {
        pricestr = pricestr.substring(pricestr.lastIndexOf('$') + 1);
    }
    return 100 * parseFloat(pricestr);
}

function convert_int_to_price(intval) {
    var dollars = Math.floor(intval / 100);
    var cents = intval % 100;
    if (cents < 10) { cents = "0" + cents; }
    return "$" + dollars + "." + cents;
}

function update_showtime(ShowTimeID, NewShowTime) {
    var req = new Request.HTML({
        url: "ajax/update_showtime.php",
        data: "EventTimeID=" + ShowTimeID + "&ShowTime=" + NewShowTime,
        onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
            //Clear the text currently inside the results div.
            //$('shoppingcart').set('text', '');
            //Inject the new DOM elements into the results div.
            //$('shoppingcart').set('html', responseHTML); //adopt(responseTree);
            //alert($('shoppingcart').innerHTML);
            var notification = new Roar({
                position: 'lowerRight',
                duration: 0
            });
            notification.alert(
							"Showtime Updated",
							responseHTML
						);
        },
        //Our request will most likely succeed, but just in case, we'll add an
        //onFailure method which will let the user know what happened.
        onFailure: function () {
            // $('shoppingcart').set('text', 'The request failed.');
            var notification = new Roar({
                position: 'lowerRight'
            });
            notification.alert(
							"Showtime Update Failed",
							"The request failed. Please try again later."
						);
        }
    });
    req.send();
}

function delete_showtime(ShowTimeID, el) {
    var req = new Request.HTML({
        url: "ajax/delete_showtime.php",
        data: "EventTimeID=" + ShowTimeID,
        onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
            var notification = new Roar({ position: 'lowerRight', duration: 0 });
            notification.alert("Showtime Deleted", responseHTML);
            el.setStyle('display', 'none');
        },
        //Our request will most likely succeed, but just in case, we'll add an
        //onFailure method which will let the user know what happened.
        onFailure: function () {
            var notification = new Roar({
                position: 'lowerRight'
            });
            notification.alert("Showtime Update Failed", "The request failed. Please try again later.");
        }
    });
    req.send();
}

function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }

    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    if (errorType == "ImageError" || errorType == "MediaError") {
        return;
    }

    var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}
