$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback )
{
	if ( typeof sNewSource != 'undefined' )
	{
		oSettings.sAjaxSource = sNewSource;
	}
	this.oApi._fnProcessingDisplay( oSettings, true );
	var that = this;
	
	oSettings.fnServerData( oSettings.sAjaxSource, null, function(json) {
		/* Clear the old information from the table */
		that.oApi._fnClearTable( oSettings );
		
		/* Got the data - add it to the table */
		for ( var i=0 ; i<json.aaData.length ; i++ )
		{
			that.oApi._fnAddData( oSettings, json.aaData[i] );
		}
		
		oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
		that.fnDraw( that );
		that.oApi._fnProcessingDisplay( oSettings, false );
		
		/* Callback user function - for event handlers etc */
		if ( typeof fnCallback == 'function' )
		{
			fnCallback( oSettings );
		}
	} );
}

$(document).ready(function(){
   //initSiteAccess();
//    $(document).pngFix(); 
    var ezv = new ezp_voestalpine();
    ezv.initSite();
});
var dataTable;
var tooltipapi = '';
var manuellTourSelection = false;
var selectedGroupType = '';
function ezp_voestalpine() {
    
// Ajax Basic Handler
    this.getData = function(target, type) {
        var ajax_dataType = 'html';
        var ajax_async = false;
        var ajax_url = '/ajax/bookingorder/';
        var ajax_param = '';
        if(type == 'disabledDates') {
            ajax_dataType = 'json';
            ajax_async = true;
            if(!$('input[name=schedule[tour]]:checked').val()) {
                return false;
            }

            ajax_param  = 'tourtype/' + $('input[name=schedule[tour]]:checked').val() + '/sp/' + $('select#schedule-grouptype :selected').attr('singleperson');    
        } else if (type == 'getTime') {
            if(!$('#schedule-date').val() || !$('input[name=schedule[tour]]:checked').val()) {
                return false;
            }
            ajax_param = 'bookingdate/'+ $('#schedule-date').val() + '/tourtype/' + $('input[name=schedule[tour]]:checked').val() + '/grouptypekey/' + $('#schedule-grouptype').val()+ '/sp/' + $('select#schedule-grouptype :selected').attr('singleperson');
            $('#booking-time').html('<div class="ajax-loader"><img src="/design/em_plain_site/images/ajax-loader.gif" /></div>');
        } else if (type == 'getGroupTypeInfo') {
			if(selectedGroupType) {
				ajax_param = 'grouptypekey/' + selectedGroupType + '/';
			} else {
				ajax_param = 'grouptypekey/' + $('#schedule-grouptype').val() + '/';
			}
        } else if (type == 'getBookingTimeInfo' || type == 'getLanguageInfo') {
            if(!$('#booking-time input[name=schedule[time]]:checked').val()) {
                return false;
            }
            if(type == 'getBookingTimeInfo') {
                ajax_param = 'bookingtime/' + $('#booking-time input[name=schedule[time]]:checked').val() + '/';        
            } else if (type == 'getLanguageInfo') {
                if($('input[name=schedule[tour]]:checked').val() != 'with_bus') {
                    return false;
                }

                ajax_param = 'bookingtime/' + $('#booking-time input[name=schedule[time]]:checked').attr('timestamp') + '/';     
            }
        }
        ajax_url = ajax_url + target + '/' + type + '/' + ajax_param;
        
        $.ajax({
            type: "GET",
            url: ajax_url,
            async: ajax_async,
            dataType: ajax_dataType,
            success: function(msg) {
                var ezv = new ezp_voestalpine();
                if(target == 'getBookings') {
                    if(type == 'disabledDates') {
                        var blookdays = new Array();
                        var blookweekdays = new Array();
                        var specialdays = new Array();
						
                        if(msg.blockeddays) {
                            $.each(msg.blockeddays, function(key,val) {
                               blookdays[key] = val.date;
                            });
                        }
                        
                        var index=0;
                        if(msg.blockweekdays) {
                            $.each(msg.blockweekdays, function(key,val) {
                                blookweekdays[index] = val;
                                index++;
                            });
                        }
                        index=0;
                        if(msg.specialdays) {
                            $.each(msg.specialdays, function(key,val) {
                                specialdays[index] = key;
                                index++;
                            });
                        }
                        if($('#application').length > 0) {
                            var enableClickInput = true;
                        } else {
                            var enableClickInput = false;
                        }
                        $('#schedule-date').removeClass('dp-applied');
                        $('.date-pick').datePicker({
                            clickInput: enableClickInput,
                            renderCallback:function($td, thisDate, month, year) {
                                if (jQuery.inArray(thisDate.asString(),blookdays) >= 0) {
                                    //disabled date
                                    $td.addClass('closed');
                                    $td.addClass('disabled');
                                    $td.addClass('full');
                                } else if (jQuery.inArray(thisDate.getDayName(),blookweekdays) >= 0) {
                                    if(jQuery.inArray(thisDate.asString(),specialdays) < 0) {
                                        //disabled date
                                        $td.addClass('closed');
                                        $td.addClass('disabled');
                                    }
                                } else {
                                    // reset day
                                    $td.removeClass('closed');
                                    $td.removeClass('disabled');
                                    $td.removeClass('full');
                                    $td.removeClass('selected');
                                }
                            }
                        })
                        .trigger('change')
                        .bind(
                            'keydown',
                                function() {
                                    if(enableClickInput) {
                                        $(this).attr('value','').dpDisplay();
                                    }
                                }
                            )
                        .bind(
                            'dateSelected',
                            function(e, selectedDate, $td, state) {
                                selectedDate.asString();
                                ezv.getData('getBookings','getTime');
                                $('#infoLanguage').remove();
                            }
                        );
                    } else if(type == 'getTime') {
                        $('#info-tour').hide();
                        $('#groupsizeinfo').html('');
                        $('#info-date-time').html('');
                        $('.booking-time-box').show();
                        $('#booking-time').html(msg);
                        
                        if ($('#selected-time').length) {
                            // after post
                            $('#booking-time input[value='+$('#selected-time').html()+']')[0].checked = true;
                            ezv.setGroupError();
                        }
                    } else if(type == 'getGroupTypeInfo') {
                        $('#info-tour').show();
                        $('#info-duration').html(msg);
                    } else if(type == 'getBookingTimeInfo') {
                        $('#info-tour').show();
                        $('#info-date-time').html(msg);
                        
                        // get Language Info
                        ezv.getData('getBookings','getLanguageInfo');    
                    } else if (type == 'getLanguageInfo') {
                        if(msg.length > 10) {
                            if($('#infoLanguage').length > 0) {
                                $('#infoLanguage').html(msg);
                            } else {
                                $('#more_information-language').after('<div id="infoLanguage">' + msg + '</div>');    
                            }    
                        }
                    }
                }
            }
        });
    },
    
    this.resetTour = function() {
        ezv.getData('getBookings','disabledDates');
        $('#schedule-date').hide();
        $('#schedule-date').dpSetSelected('01.01.2010');
        $('#schedule-date').show();
        $('#schedule-date').val('');
        $('#booking-time, #info-duration, #info-date-time').html('');
        $('#application .booking-time-box').show();
        $('#booking-time').html($('#default-time-text').html());
        $('#groupsizeinfo').html('');
        $('#infoLanguage').remove();
//		$('.booking-time-box').hide();
        ezv.loadTourInfo();
    },
    this.loadTourInfo = function() {
        if($('#application').length > 0 && $('.tour-box input:checked').attr('value') != '' && $('.tour-box input:checked').attr('value') != undefined) {
            $.ajax({
                type: "POST",
                url: "http://"+jQuery.url.attr("host")+"/stage/stage/" + $('.tour-box input:checked').attr('value'),
                success: function(msg){
                    $('.applicationform-right').html(msg);
                }
            });
        }
    },
    
    this.initBookingForm = function() {
        ezv = this;

        if($('#application').length || $('#applicationedit').length) {
            if($('input[name=schedule[tour]]:checked')) {
                ezv.getData('getBookings','disabledDates');    
            }
            
        }
        if($('#applicationedit').length) {
			$('#submit_buttons input[type=submit], #mailsend-box input[type=submit]').click(function() {
	            $('#submit_applicationedit').attr('value',$(this).attr('id'));
	            return true;
	        });
		}


        ezv.loadTourInfo();
        
        if($('#schedule-grouptype').attr('value') != '') {
            $('.tour-box').show();
        }
        
        
        if($('select#schedule-grouptype :selected').attr('with_bus') == 'true') {
            $('label[for=schedule-tour-withbus]').show();
        } else {
            $('label[for=schedule-tour-withbus]').hide();
        }
        if($('select#schedule-grouptype :selected').attr('without_bus') == 'true') {
            $('label[for=schedule-tour-withoutbus]').show();
        } else {
            $('label[for=schedule-tour-withoutbus]').hide();
        }
        
		if($('select#schedule-grouptype :selected').attr('company_required') == 'yes' && $('select#schedule-grouptype :selected').val() != '') {
			$('#label_company').html($('select#schedule-grouptype :selected').attr('label') + ' <em>*</em>');
		} else if($('select#schedule-grouptype :selected').val() != '') {
			$('#label_company').html($('select#schedule-grouptype :selected').attr('label'));
		}

        $('select[name=schedule[grouptype]]').change(function () {
			if($('select#schedule-grouptype :selected').attr('company_required') == 'yes' && $('select#schedule-grouptype :selected').val() != '') {
				$('#label_company').html($('select#schedule-grouptype :selected').attr('label') + ' <em>*</em>');
			} else if($('select#schedule-grouptype :selected').val() != '') {
				$('#label_company').html($('select#schedule-grouptype :selected').attr('label'));
			}
	
            var _withbus = '';
            var _withoutbus = '';
            if($(this).attr('value') == '') {
                $('.tour-box').fadeOut(); 
            } else {
                if($('select#schedule-grouptype :selected').attr('with_bus') == 'true') {
                    $('label[for=schedule-tour-withbus]').show();
                    var _withbus = 'show';
                } else {
                    $('label[for=schedule-tour-withbus]').hide();
                }
                if($('select#schedule-grouptype :selected').attr('without_bus') == 'true') {
                    $('label[for=schedule-tour-withoutbus]').show();
                    var _withoutbus = 'show';
                } else {
                    $('label[for=schedule-tour-withoutbus]').hide();
					ezv.resetTour();
					$('.booking-time-box').hide();
                }
                
                if($('.tour-box input:checked').attr('value') == 'with_bus' && _withbus != 'show') {
                    $('input#schedule-tour-withoutbus').click();
                    ezv.resetTour();
                }
                
                if($('.tour-box input:checked').attr('value') == 'with_bus' && _withoutbus != 'show') {
                    $('input#schedule-tour-withbus').click();
                    ezv.resetTour();
                }
                
                $('.tour-box').fadeIn();
            }
        });
        
        $('#timeinfo-show-other').live('click',function() {
            $('#timeinfo-other-box').fadeIn();
            $('#timeinfo-show-other').fadeOut();
        });
        
        if($('#timeinfo-other-box').length>0) {
            $('#timeinfo-other-box').fadeIn();
        }
        
        
        $('#submit_application').click(function() {
			jQuery.data(document.body, 'lastPressedKey','unset');
            return true;
        });
        $('input[name=schedule[tour]]').click(function () {
            if($('#application-buffer').html() == '') {
                ezv.resetTour();
                $('#application-buffer').html('');
            } 
        });
        if($('#application #schedule-date').length) {
            this.getData('getBookings','getTime');
        }
        
        
        $('#contact_person-copydata').click(function() {
            if($(this).attr('checked')) {
                $('#contact_person-contact_surname').attr('value',$('#personal_data-surname').attr('value'));
                $('#contact_person-contact_email').attr('value',$('#personal_data-email').attr('value'));
                $('#contact_person-contact_phone').attr('value',$('#personal_data-phone').attr('value'));
                $("#personal_data-salutation option:selected").each(function (e) {
                    $("#contact_person-contact_salutation").val($(this).val());
                });
            }
        });
        $('.mail-text b').click(function() {
            $(this).next().next('.mail-content').toggleClass('display-content');
            $('#history-scoller, #mailhistory-scoller').jScrollPane({showArrows:false,scrollbarWidth:10});
        });
        $('#booking-time input').live('click', function() {
            $('.radio-time span').css({"backgroundColor":"",'color':'#555555'});    
            $(this).parent().children('span').css({"backgroundColor":"#006298",'color':'#FFFFFF'});
            ezv.getData('getBookings','getBookingTimeInfo');
            if($('input[name=schedule[tour]]:checked').val() != $(this).attr('tour')) {
				$('#application-buffer').html('manuellTourSelection');
                var tour = $(this).attr('tour');
                tour = tour.replace('_','');
                $('input#schedule-tour-'+tour).click();
                ezv.loadTourInfo();
            }
            
            $('#groupsizeinfo').html('<br />' + $(this).attr('title'));
            ezv.setGroupError();
        });
        $('#application #schedule-date[type=text]').change(function() {
            if($(this).attr('value') != '') {
                $(this).addClass('inputcheck');
            } else {
                $(this).removeClass('inputcheck');
            }
        });
        if($('#redirect_form').length) {
            window.location = 'http://'+jQuery.url.attr("host")+'/em_forms/show/382/?bookingid=' + $('#redirect_form').html();
        }
        
        $('#history-scoller, #mailhistory-scoller').jScrollPane({showArrows:false,scrollbarWidth:10});
        
        
        $('#applicationedit #schedule-datetype').change(function() {
            if($(this).val() == 'I') {
                $('#dateinfo').show();
            } else {
                $('#dateinfo').hide();
            } 
        });
        $('#moreoption').click(function() {
            $('#mailsend-box').show();
            $('#moreoption').hide();
        });
        
        $('#application #schedule-grouptype').change(function(){
            ezv.getData('getBookings','getGroupTypeInfo');
        });
        
        $('#application .booking-time-box').hide();
        
        $('#application input[name=schedule[groupsize]]').blur(function() {
            ezv.setGroupError();
        });
        if($('input[name=schedule[tour]]:checked').length) {
            $('#application .booking-time-box').show();
            $('.radio-time span').css({"backgroundColor":"",'color':'#555555'});    
            $('#booking-time input:checked').parent().children('span').css({"backgroundColor":"#006298",'color':'#FFFFFF'});
            ezv.getData('getBookings','getBookingTimeInfo');
            
            
            $('#groupsizeinfo').html('<br />' + $('#booking-time input:checked').attr('title'));
            
        }
        
        if($('#applicationedit').length > 0) {
            try {
                $('#applicationedit .weekday[title], #applicationedit .guideinfo[title]').tooltip({
                  opacity: 0.95,
                  position: 'top center',
                  effect: 'slide',
                  tip: '#tooltip',
                  onBeforeShow: function(args){
                    obj = this.getTrigger();
                    $("#tooltip").html($(obj).children('.guidetours').html());
                    return true;
                  }
                });
            } catch(e) {
                
            }
        }
        if($('#application').length > 0) {
            if($('.error-arrow').length > 0) 
                $.scrollTo($('.error-arrow'), 2000, {offset:-50});
        }

    },
    this.setGroupError = function() {
        groupsize = parseInt($('#application #schedule-groupsize').val());
        groupsizeobj = $('#application #schedule-groupsize');
        if(groupsize) {
            $(groupsizeobj).parent().children('#grouperror').remove();
            if(groupsize < parseInt($('#booking-time input:checked').attr('minplaces'))) {
                $(groupsizeobj).parent().append('<span class="error-arrow" id="grouperror"><img border="0" src="/design/em_plain_site/images/error_arrow.gif">bitte min. '+$('#booking-time input:checked').attr('minplaces')+'</span>');
            } else if (groupsize > parseInt($('#booking-time input:checked').attr('maxplaces'))) {
                $(groupsizeobj).parent().append('<span class="error-arrow" id="grouperror"><img border="0" src="/design/em_plain_site/images/error_arrow.gif">bitte max. '+$('#booking-time input:checked').attr('maxplaces')+'</span>');
            } else if(isNaN($('#application #schedule-groupsize').val())) {
                $(groupsizeobj).parent().append('<span class="error-arrow" id="grouperror"><img border="0" src="/design/em_plain_site/images/error_arrow.gif">bitte nur Zahlen</span>');
            } 
        } else if($('#application #schedule-groupsize').val() && isNaN($('#application #schedule-groupsize').val())) {
            $(groupsizeobj).parent().children('#grouperror').remove();
            $(groupsizeobj).parent().append('<span class="error-arrow" id="grouperror"><img border="0" src="/design/em_plain_site/images/error_arrow.gif">bitte nur Zahlen</span>');
        } 
    },
    
    this.initFullCalender = function() {
        if($('#fullcalendar').length) {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();
            
            $('#fullcalendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                height:500,
                allDaySlot: false,
                allDayText: 'Ganzt.',
                firstHour: 8,
                slotMinutes: 30,
                defaultEventMinutes: 120,
                axisFormat: 'H:mm',
                timeFormat: {
                    agenda: 'H:mm{ - H:mm}'
                },
                dragOpacity: {
                    agenda: .5
                },
                minTime: 0,
                maxTime: 24,
                timeFormat: "H:mm",
                defaultView: 'agendaWeek',
                monthNames:["Jänner","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],
                monthNamesShort:["Jän","Feb","März","April","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],
                dayNames:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
                dayNamesShort:["SO","MO","DI","MI","DO","FR","SA"],
                columnFormat:{month:"ddd",week:"dddd d",day:"dddd M/d"},
                buttonText:{prev:"&nbsp;&#9668;&nbsp;",next:"&nbsp;&#9658;&nbsp;",prevYear:"&nbsp;&lt;&lt;&nbsp;",nextYear:"&nbsp;&gt;&gt;&nbsp;",today:"heute",month:"Monat",week:"Woche",day:"Tag"},
                titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},
                
                firstDay:1,
                editable: true,
                theme: true,
                
                events: "/ajax/bookingcalendar/",
			
                eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                    if (!confirm("Wollen sie eine Umbuchung starten?")) {
                        revertFunc();
                    } else {
                        window.open(event.url + '&day=' + dayDelta + '&minute=' + minuteDelta,'_blank');    
                    }
                },
                
                eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
                    if (!confirm("Wollen sie eine Umbuchung starten?")) {
                        revertFunc();
                    } else {
                        window.open(event.url + '&day=' + dayDelta + '&minute=' + minuteDelta,'_blank');
                    }
                },
                
                eventClick: function(event) {
                    if(event.url) {
                        window.open(event.url);
                        return false;
                    }  
                },
                eventRender: function(event, element) {
                    $(element).attr('title',event.description);
                },
                loading: function(bool) {
                    if (bool) $('#loading').show();
                    else $('#loading').hide();
                }
            });
        }
    },
    
    this.loadDataTable = function(param) {
        dataTable = $('#bookings').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "aaSorting": [[1, "asc"]],
            "aoColumns": [ 
                {"sClass": "state"},
                {"sClass": "date"},
                {"sClass": "time", "bSortable": false},
                {"sClass": "guide", "bSortable": false},
                {"sClass": "grouptype"},
                {"sClass": "bookingtype"},
                {"sClass": "tour"},
                {"sClass": "company"},
                {"sClass": "contactperson"},
                {"sClass": "entrydate"}
            ],
            "oLanguage": {
                "sLengthMenu": "Zeige _MENU_ Touren pro Seite",
                "sZeroRecords": "Es gibt leider keine Touren",
				"sProcessing": "Lade ...",
                "sInfo": "Zeige _START_ bis _END_ von _TOTAL_ Touren",
				"sInfoEmpty": "0 Touren",
				"sSearch": "Suche:",
                "sInfoFiltered": "(_MAX_ Touren insgesamt)",
				"oPaginate": {
					"sFirst":    "Erste",
					"sPrevious": "Vorherige",
					"sNext":     "Nächste",
					"sLast":     "Letzte"
				}
            },
            "sAjaxSource": "/ajax/bookings/"
        });
    },
    this.initSearchForm = function() {
        $('#submit_search').click(function() {
			var searchParams = '?search=1';
			$('#search input, #search select').each(function() {
				key = $(this).attr('name');
				key = key.slice(10).replace(/]/g, '');
				searchParams = searchParams + '&' + key + '=' + encodeURI($(this).val());
		    });
            dataTable.fnReloadAjax("/ajax/bookings/"+searchParams);
			return false;
       });
       $('#search .date-pick').datePicker({startDate:'01.01.2010'});
       
       $('#submit_add_booking').click(function() {
            window.open('http://'+jQuery.url.attr("host")+'/em_forms/show/382/?bookingid=0','_blank');
            return false;
       });
       
    },
	this.initExportForm = function() {
        $('#submit_export').click(function() {
			var searchParams = '/?export=1';
			var exportType = '';
			$('#export input, #export select').each(function() {
				if ($(this).val()) {
					key = $(this).attr('name');
					key = key.slice(10).replace(/]/g, '');
					if (key != 'exporttype') {
						if ($(this).val() != '') {
							searchParams = searchParams + '&' + key + '=' + encodeURI($(this).val());
						}
					} else {
						exportType = '/' + $(this).val();
					}
				}
		    });
			
            $.get('/export/view' + exportType + searchParams, function(data){
				$('#export-content').html(data);
			});
			return false;
       });
       $('#export .date-pick').datePicker({startDate:'01.01.2010'});
       
    },
// init Website 
    this.initSite = function() {
        
        
        //bookings-history;
		if ($('#leftsides-guide').html()) {
			$('#bookings').addClass('bookings-hover');
			$('#bookings tr:has(td)').live('click', function() {
				var booking = $(this).children('.state').children('img[id]');
				$.each(booking, function(id_text,val) {
					bookingid = $(val).attr('id');
					bookingid = bookingid.replace('booking_','');
				});
				window.open('http://'+jQuery.url.attr("host")+'/em_forms/show/382/?bookingid=' + bookingid,'_blank');
			});
		} else {
			$('#bookings tr:has(td)').live('click', function() {
				$('#bookings').addClass('bookings-hover');
				var booking = $(this).children('.state').children('img[id]');
				$.each(booking, function(id_text,val) {
					bookingid = $(val).attr('id');
					bookingid = bookingid.replace('booking_','');
				});
				$.ajax({
			            type: "POST",
			            url: "http://"+jQuery.url.attr("host")+"/ajax/bookingorder/getBookingmessage/" + bookingid,
			            success: function(msg){
			                alert(msg);
			            }
			      });
			});
		}

        
        this.loadDataTable();
        
        
        $("#testmode").click(function(){
            var url = "/stage/startpage/314";
            $.nyroModalManual({
                url : url
            });
        });
        this.initSearchForm();
        this.initExportForm();
        this.initBookingForm();
        this.initFullCalender();
    }
}




function loadContent(contentid) {
    $.ajax({
            type: "POST",
            url: "http://"+jQuery.url.attr("host")+"/stage/stage/" + contentid,
            success: function(msg){
                $('#stage-landing').html(msg);
            }
      });
}
function hideContent() {
    $('#stage-landing').html('');
}

function loadStartpage(contentid,setcookie) {
    var show_box = true;
    if(setcookie == 1 && GetCookie('startpage') == contentid) {
        var show_box = false;
    }
    
    if(show_box == true) {
        var url = "/stage/startpage/"+ contentid + '?height=500&width=800';
        tb_show('voestalpine Stahlwelt', url, false);
            
    }    
    if(setcookie == 1) {
        // write cookie
        var expire = new Date();
        var expireTime = expire.getTime() + (5000 * 24 * 3600 * 1000);
        expire.setTime(expireTime);
        document.cookie = "startpage="+contentid+"; Path=/; expires=" + expire.toGMTString();
        
    }
}

function GetCookie (name) { 
    var arg = name + "="; 
    var alen = arg.length; 
    var clen = document.cookie.length; 
    var i = 0; 
    while (i < clen) { 
        var j = i + alen; 
        if (document.cookie.substring(i, j) == arg) 
        return getCookieVal (j); 
        i = document.cookie.indexOf(" ", i) + 1; 
        if (i == 0) break; 
    } 
    return null;
}

function getCookieVal (offset) { 
    var endstr = document.cookie.indexOf (";", offset); 
    if (endstr == -1) 
    endstr = document.cookie.length; 
    return unescape(document.cookie.substring(offset, endstr));
}

var lastPressedKey = '';
function keylog(e){
    var evtobj=window.event? event : e 
    var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
    lastPressedKey = unicode;
 	if(lastPressedKey == 13) {
		jQuery.data(document.body, 'lastPressedKey','set');
	}
}
jQuery.data(document.body, 'lastPressedKey','set');
document.onkeydown=keylog;


function validateForm() {
	_log(lastPressedKey);
    if(lastPressedKey == 13 && jQuery.data(document.body, 'lastPressedKey') != 'unset') {
		jQuery.data(document.body, 'lastPressedKey','set');
        return false;    
    }
    if($('#grouperror').length) {
        $('#schedule-groupsize').val();
    }
    return true;
}

function _log(msg) {
    if (window.console && window.console.log)
        window.console.log(msg);
}