function createObject(){
    var request_type;
    var browser=navigator.appName;
    if(browser=="Microsoft Internet Explorer"){
        request_type=new ActiveXObject("Microsoft.XMLHTTP")
    }else{request_type=new XMLHttpRequest()
    }return request_type
}
var http=createObject();
var nocache=0;

function initiateCal(month,year){
    var loader=document.getElementById('loader');
    var cal=document.getElementById('calendar');
    cal.style.display='none';loader.style.display="block";
    nocache=Math.random();
    http.open('get','/wp-content/themes/template/mod/calendar.php?month='+month+'&year='+year+'&'+nocache);
    http.onreadystatechange=outputCal;
    http.send(null); 
    return false
}

function outputCal(){
    var cal=document.getElementById('calendar');
    var loader=document.getElementById('loader');
    if(http.readyState==4){
        var response=http.responseText;
        if(response!==0){
            cal.innerHTML=response;
            $('#loader').fadeOut(300);
            $('#calendar').fadeIn(300);
            showMonthYear();
            ReservationCopy()
        }
    }
}

function showEvent(eid){
    $('#loader').show();
    http.open('get','/wp-content/themes/template/mod/event-info.php?eid='+eid+'nocache='+nocache);
    http.onreadystatechange=showEventInfo;http.send(null);
    return false
}

function showEventInfo(){
    if(http.readyState==4){
        var response=http.responseText;
        if(response!==0){
            $('#loader').fadeOut(300);
            $('#text').hide();
            $('#text').fadeIn(500);
            $('#text').html(response);
            $('.post').css('overflow','auto');
            sIFR.replace(walbaum,{
                selector:'.text h1',wmode:'transparent',ratios:[8,1.3,11,1.21,12,1.2,14,1.19,21,1.16,28,1.13,38,1.12,61,1.11,94,1.1,95,1.09,103,1.1,107,1.09,110,1.1,119,1.09,120,1.1,1.09],css:['.sIFR-root { color:#000000; font-size:16px;}','a {color: #000000; text-decoration: none;}','a:hover {color: #000000;}']
            })
        }
    }
}

function addLoadEvent(func){
    var oldonload=window.onload;
    if(typeof window.onload!='function'){
        window.onload=func
    }else{
        window.onload=function(){
            if(oldonload){oldonload()}func()}}}
addLoadEvent(function(){
    initiateCal("","")
});

function showMonthYear(){
  
    var month_year=document.getElementById('m-y').innerHTML;month_year=month_year.replace(',',' ');
    $('#text').html('<h1>The Loft Project Calendar</h1><h1>'+month_year+'</h1>');
    $('#text').hide();
    $('#text').fadeIn(500);
    sIFR.replace(walbaum,{
        selector:'.text h1',wmode:'transparent',ratios:[8,1.3,11,1.21,12,1.2,14,1.19,21,1.16,28,1.13,38,1.12,61,1.11,94,1.1,95,1.09,103,1.1,107,1.09,110,1.1,119,1.09,120,1.1,1.09],css:['.sIFR-root { color:#000000; font-size:16px;}','a {color: #000000; text-decoration: none;}','a:hover {color: #000000;}']
    });
}


function ReservationCopy(){
    $.ajax({
        type : 'POST',
        url : '/wp-content/themes/template/mod/reservations.php',
        dataType : 'script',
        data: {},
        success : function(data){
            $("#text h1:last").after("<p>" +data+"</p>").hide().fadeIn("slow");
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert("A system error occured! Please try again later");
        }
    });

    
}

function showBooking(eid){

     $('#seats-popup').animate({
        top: '30%',
        left: '47%',
        width: '339px',
        height: '220px',
        opacity: 1,
		filter: 'alpha(opacity=100)'


     }, 600);

     $('#overlay').show();
     $('input[name=eid]').val(eid);

     return false;
}




$(document).ready(function(){
  
   var nseats = $('#seats-popup input');
   $('#seats-popup span').click(function(){

     $('#seats-popup').animate({
        top: '0%',
        left: '0%',
        width: '0px',
        height: '0px',
        opacity: 0

     }, 600);

     $('#overlay').hide();
     nseats.removeClass();
     $('#seats-popup div').removeClass('error').html('');
    
    

   });


   $('#seats-popup form').submit(function(){

       $('#seats-popup div').removeClass('error').html('').removeClass('processing');

      if(nseats.val() == ''){

          $('#seats-popup div').addClass('error').html('Please specify how many seats you wish to book for this event!')
          .hide().fadeIn('slow');
          
      }else if(!IsNumeric(nseats.val())){

           $('#seats-popup div').addClass('error').html('Please specify valid number!')
          .hide().fadeIn('slow');

      }else{

           $('#seats-popup div').addClass('processing').html('Processing, please wait...')
           .hide().fadeIn('slow');
           var seats = nseats.val(),
               eid = $('input[name=eid]').val();

         $.ajax({
            type : 'POST',
            url : '/wp-content/themes/template/mod/check-seats-availability.php',
            dataType : 'script',
            data: {
                eid : eid,
                seats : seats
            },
            success : function(data){
              
               
              if(data == 0){
                  
                  document.location = '/membership?event=' + eid + '&seats=' + seats;


              }else{
                   if(data == 1){
				     var s = 'seat';
					 var i = 'is';
				   }else{
				     var s = 'seats';
					 var i = 'are';
				   }
				   
                   $('#seats-popup div').addClass('error').html('There '+i+' only <strong>'+ data + '</strong> '+s+' available for this event!')
                  .hide().fadeIn('slow');
                  $('#seats-popup div').removeClass('processing');

              }
			  
			  
              
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                 $('#seats-popup div').addClass('error').html('A system error occured. Please try again later! Appologies for any inconvenience.')
                  .hide().fadeIn('slow');
                  $('#seats-popup div').removeClass('processing');
            }
       });

      }

        return false;
       
   });


    processMembership();
    monthDays();

     $('#newsletter').submit(function(){

        return processSubscribe();
     });
	 
	 
	
	    

});

function IsNumeric(sText){
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++){
        Char = sText.charAt(i);
       if (ValidChars.indexOf(Char) == -1){
          IsNumber = false;
       }
     }
    return IsNumber;

}

function processMembership(){

    $('#.form form button').click(function(){
    $('.form input,select').css({'border-color' : '#000', 'background' : 'white'});
    $('.form-error').html('');
     //validate form first

     if($('input[name=rememberme]:checked').val()){

           var remember = 1;

     }else{

         var remember = 0;
     }
	 
	 if($('input[name=subscribe]:checked').val()){

           var subscribe = 1;

     }else{

         var subscribe = 0;
     }
	 
	 
     var name = $('input[name=name]'),
         title = $('select[name=title]'),
         address = $('input[name=address]'),
         county = $('input[name=county]'),
         postcode = $('input[name=postcode]'),
         mphone = $('input[name=mphone]'),
         dphone = $('input[name=dphone]'),
         occupation = $('input[name=occupation]'),
         doby = $('select[name=doby]'),
         dobm = $('select[name=dobm]'),
         dobd = $('select[name=dobd]'),
         email = $('input[name=email]'),
         hphone = $('input[name=hphone]'),
         mname = $('input[name=mname]'),
         seats = $('input[name=quantity_1]').val(),
         eid = $('input[name=eid]').val();
         

        
         if(name.val() == '' || title.val() == '' || address.val() == '' || postcode.val() == ''
            || county.val() == '' || mphone.val() == ''
            || dphone.val() == '' || email.val() == '' || occupation.val() == ''
            || doby.val() == '' || dobd.val() == '' || dobm.val() ==''
            || !ValidateEmail(email.val())){

            if(name.val() == ''){
                name.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
            }

             if(title.val() == ''){
                title.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(address.val() == ''){
                address.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(postcode.val() == ''){
                postcode.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(county.val() == ''){
                 county.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(mphone.val() == ''){
                mphone.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(dphone.val() == ''){
                mphone.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(occupation.val() == ''){
                occupation.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(doby.val() == ''){
                doby.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(dobm.val() == ''){
                dobm.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(dobd.val() == ''){
                dobd.css({
                    'border' : '1px solid #CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             if(email.val() == ''){
                email.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             

             if(!ValidateEmail(email.val())){
                email.css({
                    'border-color' : '#CC0000',
                    'background' : '#FFEBE8'
                 });
             }

             $('.form-error').html('Please correct marked fields!');



            return false;

          }else{
  
             
                $('#progress-loader').show().html('Processing Application...');
                $('#overlay').show();

                 $.ajax({
                  type : 'POST',
                  url : '/wp-content/themes/template/mod/process-membership.php',
                  dataType : 'script',
                  data: {
                         name : name.val(),
                         title : title.val(),
                         address : address.val(),
                         county : county.val(),
                         postcode : postcode.val(),
                         mphone : mphone.val(),
                         dphone : dphone.val(),
                         occupation : occupation.val(),
                         doby : doby.val(),
                         dobm : dobm.val(),
                         dobd : dobd.val(),    
                         email : email.val(),
                         hphone : hphone.val(), 
                         mname : mname.val(),
                         remember: remember,
                         seats : seats,
                         eid : eid,
						 subscribe : subscribe
                         
                   },
                success : function(data){
                    //data.replace("\n\n\r", "");
					var t = "\n \n\r";
					var id = trim(data,t);
                    $('input[name=custom]').val(id);
					$('input[name=notify_url]').val('http://www.theloftproject.co.uk/wp-content/themes/template/mod/notify.php?member_id='+id);
                    $('input[name=return]').val('http://www.theloftproject.co.uk/thank-you?id='+id);
					formSubmit();
                    $('#progress-loader').html('Redirecting to Paypal...');
                    
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                        $('#progress-loader').hide().html('');
                        $('#overlay').hide();
                        alert("A system error occured! Please try again later");
                        return false;
                }
            });

              
            return false;
 
          }
    });
	
	
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
  
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

}


function formSubmit(){
    $('.form form').submit();
}

function ValidateEmail(email){

var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

if(reg.test(email) == false){

    return false;

 }else{

   return true;
  }
}

function monthDays(emonth){
   var months = new Array();
   months[0] = 31;
   months[1] = 29;
   months[2] = 31;
   months[3] = 30;
   months[4] = 31;
   months[5] = 30;
   months[6] = 31;
   months[7] = 31;
   months[8] = 30;
   months[9] = 31;
   months[10] = 30;
   months[11] = 31; 
   
   
   
   
  $('select[name=dobm]').change(function(){ 
      var month = $('select[name=dobm]').val();
      var m = [];
	 

      for(var i = 1; i <= months[month]; i++){  

          m.push('<option value="' + i + '">' + i + '</option>')
      }

      var days = m.join(' ');
      days = '<option value="">(Day)</option>' + days;
             $('select[name=dobd]').html(days);
        
  });
}

function loadDays(){
   var selected = $('input[name=hdobd]').val();
   var month = $('select[name=dobm]').val();
   var months = new Array();
   months[0] = 31;
   months[1] = 29;
   months[2] = 31;
   months[3] = 30;
   months[4] = 31;
   months[5] = 30;
   months[6] = 31;
   months[7] = 31;
   months[8] = 30;
   months[9] = 31;
   months[10] = 30;
   months[11] = 31; 
   var m = [];
   
   
   if(month == ''){
	      month = 0;
	 }
	 
	 
   
      for(var i = 1; i <= months[month]; i++){  
          
		  if(selected == i){
		    var s = 'selected="selected"';
		  }else{
		    var s = '';
		  }
		  
          m.push('<option '+s+' value="' + i + '">' + i + '</option>')
      }

      var days = m.join(' ');
      days = '<option value="">(Day)</option>' + days;
             $('select[name=dobd]').html(days);
   
   
}


function outputYear(){
  var selected = $('input[name=hdoby]').val();
  var cdate = new Date();
  var year = parseInt(cdate.getFullYear());
  var y = [];
  
  

  for(var i = 1900; i <= year; i++){
      if(selected == i){
	      var s = 'selected="selected"';
	  }else{
	      
		  var s = '';
	  }
      y.push('<option '+s+' value="' + i + '">' + i + '</option>')

  }
   var years = y.join('');
  $('select[name=doby]').html('<option value="">(Year)</option>' + years);


}

function processSubscribe(){
   var email = $('input[name=subscribe]'),
   error = $('#newsletter div');

   error.html('');
   email.css({
                    'border' : '1px solid #FFF',
                    'background' : '#FFF'
                 });

       if(!ValidateEmail(email.val())){
           
            email.css({
                    'border' : '1px solid #CC0000',
                    'background' : '#FFEBE8'
                 });
              error.html('Please enter valid email!').css('color' , '#CC0000').css('font-size', '10px');

      

       }else{
           
           $('.submit').hide();
           $('form#newsletter span').show();
           $.ajax({
            type : 'POST',
            url : '/wp-content/themes/template/mod/add-subscriber.php',
            dataType : 'script',
            data: {

            email : email.val()

            },
            success : function(data){ 

               if(data == 1){
                   
                   $('.submit').show();
                   $('#newsletter span').hide();
                   error.html('Your email has been successfully added to our subscribers list!').css('color', 'green').css('font-size', '10px');
                
			   }else if(data == 2){
				    email.css({
                    'border' : '1px solid #CC0000',
                    'background' : '#FFEBE8'
                 });
                  error.html('This email already exist in our subscribers list!').css('color' , '#CC0000').css('font-size', '10px');
                  $('.submit').show();
                   $('#newsletter span').hide();
			   
			   }else{

                    alert("A system error occured! Please try again later");
                    $('.submit').show();
                    $('#newsletter span').hide();
               }

            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert("A system error occured! Please try again later");
                $('.submit').show();
                $('#newsletter span').hide();
            }
        });
           
       }
  
 return false;
}



