$(document).ready(function()
{
		var time = new Date();
		
		var current_date;
		
		if ($("#section").val() == "archief")
		{
			current_date = (time.getDate()-1) + "-" + (time.getMonth() + 1) + "-" + time.getFullYear();
		}
		else
		{
			current_date = time.getDate() + "-" + (time.getMonth() + 1) + "-" + time.getFullYear();
		}

        $(".tooltip").tooltip(
            {
                track: true,
                delay: 0,
                showURL: false,
                opacity: 1,
                fixPNG: true,
                showBody: " - ",
                extraClass: "tooltip",
                top: -110,
                left: -50,
                width: 300
            }
        ); 
        
        // Datepicker
		$("#datepicker").datepicker(
            {
    			showOn: "button",
    			buttonImage: "/images/b-calendar.gif",
    			buttonImageOnly: true, 
                onSelect: function(dateText, inst) 
                    {
                        if (SA_ValidateEventFilter(dateText))
                        {
                            $("#eventlistviewform").submit();
                        } 
                        else
                        {
                            // Cancel
                            $("input[name='startdate']").val(current_date);   
                            return false; 
                        }
                    }                                   
    		}
        );
        
        $('#datepicker').keypress(function(event) 
            {
                if (event.which == '13') 
                {
                    var t = $("#datepicker").val(); 
                
                    if (!isValidDate(t))
                    {
                        alert("De opgegeven startdatum is niet helemaal juist ingevoerd, probeer het nog een keer\n");
                        return false;  
                    }                                        
                    
                    if (SA_ValidateEventFilter(t))
                    {                        
                        $("#eventlistviewform").submit();
                    } 
                    else
                    {
                        // Cancel   
                        $("input[name='startdate']").val(current_date);                                             
                        return false; 
                    }
                }
            }
        );        
    }
);

/*-----------------------------------------------------------------------------------------------------------------------------------------------*/

function SA_ValidateEventFilter(dateValue)
{   
    var time = new Date();                    
    var current_date = (time.getMonth() + 1) + "/" + time.getDate() + "/" + time.getFullYear();
    var selected_date = dateValue.replace(/-/gi, "/");

    var tmpAry = selected_date.split("/");
    selected_date = tmpAry[1] + "/" + tmpAry[0] + "/" + tmpAry[2];
        
    // Compare Current Date To What's Been Selected   
    var x = dates.compare(selected_date, current_date);     

    // Grab/Format QueryString, Set Defaults    
    var section  = document.getElementById("section");
    var start_date  = document.getElementById("datepicker");
    
    var view = URLEncode(GetQueryString("view"));
    if (!view)
    {
        view = "list";
    }
    var soort = URLEncode(GetQueryString("soort"));
    if (!soort)
    {
        soort = "0";
    }

    if (section.value == "programma")
    {        
        if(x == -1)
        {
            // Selected Date Lies In The Past - Cancel
            //alert("Het is niet mogelijk om bijeenkomsten uit het verleden weer te geven. \nBekijk hiervoor ons archief.");            
            
            var redirect_url = "/archief/?view=" + view + "&startdate=" + URLEncode(start_date.value) + "&soort=" + soort + "&section=archief";            
            window.location = redirect_url; 
            return false; 
        }  
    }  
    
    if (section.value == "archief")
    {
        if (x >= 0)
        {
            // Selected Date Lies In The Future - Cancel
            //alert("Het is niet mogelijk om bijeenkomsten die in de toekomst liggen weer te geven. \nBekijk hiervoor ons programma.");            
            
            var redirect_url = "/programma/?view=" + view + "&startdate=" + URLEncode(start_date.value) + "&soort=" + soort + "&section=programma";            
            window.location = redirect_url;     
            return false;        
        }
    }
    
    return true;            
}

function SA_ValidateArchiveFilterMonth()
{   
    var time = new Date();                    
    var current_date = (time.getMonth() + 1) + "/" + time.getDate() + "/" + time.getFullYear();  
    
    var month = document.getElementById("month").options;  
    var month_selIndex = document.getElementById("month").selectedIndex;
          
    var year = document.getElementById("year").options;  
    var year_selIndex = document.getElementById("year").selectedIndex; 
    
    var selected_date = month[month_selIndex].value + "/1/" + year[year_selIndex].value;
    
    // Compare Current Date To What's Been Selected   
    var x = dates.compare(selected_date, current_date);     
        
    if(x == 1)
    {
        // Selected Date Lies In The Future - Cancel
        alert("Het is niet mogelijk om bijeenkomsten in de toekomst weer te geven. \nBekijk hiervoor ons programma.");
        
        // Reset Selected Month To Current
        document.getElementById("month").selectedIndex = time.getMonth();
        
        // Reset Selected Year To Current To Be Safe
        for (i = 0; i < year.length; i++)
        {
            if (year[i].value == time.getFullYear())
            {                
                document.getElementById("year").selectedIndex = i;
            }
        }
    }    
    
    var xForm = document.getElementById("eventlistviewform");
    xForm.submit();     
}
    
// Date Validation Function(s)    
function isValidDate(s) 
{
    // Format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|-|-]\d{1,2}[\.|-|-]\d{1,4}$/;

    if (dateFormat.test(s)) 
    {
        // Remove Any Leading Zeros From Date Values
        s = s.replace(/0*(\d*)/gi,"$1");
        var dateArray = s.split(/[\.|-|-]/);
      
        // Correct Month Value
        dateArray[1] = dateArray[1] - 1;

        // Correct Year Value
        if (dateArray[2].length < 4) 
        {
            // Correct Year Value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate() != dateArray[0] || testDate.getMonth() != dateArray[1] || testDate.getFullYear() != dateArray[2]) 
        {
            return false;
        } 
        else 
        {
            return true;
        }
    } 
    else 
    {
        return false;
    }
}

var dates = {
    convert:function(d) 
    {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp) 
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
            d.constructor === Number ? new Date(d) :
            d.constructor === String ? new Date(d) :
            typeof d === "object" ? new Date(d.year, d.month, d.date) :
            NaN
        );
    },
    compare:function(a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a = this.convert(a).valueOf()) &&
            isFinite(b = this.convert(b).valueOf()) ?
            (a > b)-(a < b) :
            NaN
        );
    },
    inRange:function(d, start, end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
       return (
            isFinite(d = this.convert(d).valueOf()) &&
            isFinite(start = this.convert(start).valueOf()) &&
            isFinite(end = this.convert(end).valueOf()) ?
            start <= d && d <= end :
            NaN
        );
    }
}

function GetQueryString(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}

function URLEncode(clearString) 
{
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	
	while (x < clearString.length) 
	{
    	var match = regex.exec(clearString.substr(x));
    	if (match != null && match.length > 1 && match[1] != '') 
		{
    		output += match[1];
		    x += match[1].length;
		} 
		else 
		{
      		if (clearString[x] == ' ')
	        output += '+';
			else 
			{
				var charCode = clearString.charCodeAt(x);
		        var hexVal = charCode.toString(16);
        		output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      		}
			x++;
		}
	}
	return output;
}

function URLDecode(encodedString) 
{
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') 
	{
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	return output;
}

