// JavaScript Document
Date.prototype.getWeek = function() { // get workweek
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 
    //==============================================================
    var today = new Date();
    // today= new Date(Date.parse(prompt('date',"12/7/2010")))  // for testing
    var weekno = today.getWeek(); 
    var month = today.getUTCMonth()
    if (month == 0){// special case for jan 1, 2011
        if (today.getUTCDate() < 2) { weekno = 53 } 
    }
    // global variables
    var warning = "";
    var rdata = "";
    var gametime = 0;  // global value set from flash
    // alert("workweek "+weekno) // for testing
    
    $(document).ready(function() {

    $('#post').jqm();  // initialize the modal windows
    $('#modalbox').jqm();
    $('#leaderbox').jqm();
    $("#continue").hide();
    
    // show the main start screen
    
    $("#mainText").load("/includes/pagesnippets.htm #firstpage",function()
    {
      $("#mainText").slideDown(1000,function()
      {
          $("#oems").fadeIn(1000);
          $("#help-agent-reliable-game_div").fadeIn(1000)
      });
    })
    $(".w"+weekno).show(); // show this weeks oems

 
    //==============================================================
    $(".facebooklink").click(function()
    {
       href=$(this).attr('href').replace(/\[time\]/,sec2hms(gametime))
       $(this).attr('href',href)
       $("#continue").show()
       return true;
    });
    $(".twitterlink").click(function()
    {
       href=$(this).attr('href').replace(/\[time\]/,sec2hms(gametime).replace(/ /g,""))
       $(this).attr('href',href)
       $("#continue").show()
       return true;
    });
    //==============================================================
    $("#continue").click(function()
    {
       $("#post").jqmHide();
       $("#mainText").hide().load("/includes/pagesnippets.htm #clickwin",function()
        {
            $(this).fadeIn()

               $("#help-agent-reliable-game_div").animate({"opacity":0},"slow")
               $("#form").fadeIn();
        });
    });
    //==============================================================
    $("#sname").change(function()
    {
      if ($.trim(document.getElementById('email').value) != "" 
          && $.trim(document.getElementById("sname").value) != ""  )
        {
            checkname($.trim(document.getElementById("sname").value),$.trim(document.getElementById('email').value))
            $(".warning").html(warning)
        }        
    
    })
    //==============================================================
     $("#leaderboard").live('click',function()
              {
                 $.ajax({  
                       type: "GET",  
                       url: "leaderboard.php",  
                       async: false,
                       success: function(data) { 
                         
                         $("#leaderbox .modalcontent").html("<div id='message'></div>");  
                         $('#message').html("<h2>LEADERBOARD</h2>")  
                         .append(data)  
                         .hide()  
                         .fadeIn(1500);
                         $("#leaders tr:even").addClass("alt")
                         $("#leaderbox").jqmShow(); 
                       },
                       error: function(err)
                       {
                        
                        $("#leaderbox .modalcontent").html("<div id='message'></div>");  
                         $('#message').html("<h2>Error showing leaderbaord!</h2>")  
                         .append("<p>We had a problem....</p><p>"+err+"</p>")  
                         .hide()  
                         .fadeIn(1500);
                         $("#leaderbox").jqmShow(); 
                       }  
                     });     
                     return false;
              });
    //==============================================================
    $("#email").blur(function()
    {
      if ($.trim(document.getElementById('email').value) != "" 
          && $.trim(document.getElementById("sname").value) != ""  )
        {
             getsname($.trim(document.getElementById('email').value),"get")
             if (rdata != "")
             {
                document.getElementById('sname').value = $.trim(rdata)
             }
        }        
    
    });
    $("#shareyourtime").live("click",function()
    {
       $("#post").jqmShow();
    });
    //==============================================================
    $('#agree').click(function()
    {
        $(".rules").css("color","#ffffff")
    });
   //==============================================================
    $('#cancelform').click(function()
    {
        $("#form").hide();
        $("#mainText").hide().load("/includes/pagesnippets.htm #thankyou").fadeIn(1000,function()
        {
           $("#help-agent-reliable-game_div").animate({"opacity":1},"slow")
        });
        return false;
    });
    //==================================================================================
    // clear the form field prompt value during form entry and reset it if no entry on blur
    $(".prompt").focus(function()
    {
      if ($(this).attr("title") == $(this).attr("value"))
      {
        $(this).attr("value","")
        $(this).css("color","#828282")
      }
    });
    //==============================================================
    $(".prompt").blur(function()
    {
      if ($(this).attr("value").match(/^\s*$/))
      {
        $(this).attr("value",$(this).attr("title"))
      }
    });
    //==============================================================
    // load the flash game
    var so = new SWFObject('help-agent-reliable-game.swf','game_swf','800','600','10','#000066');
        so.addParam('quality','high');
        so.write('help-agent-reliable-game_div');

    });

 
    
    
    //==============================================================
    // email pattern for validation
    epatt = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    //==============================================================
    // form validation routine
    function validate(o)
    {
      fname = document.getElementById("fname");
      email = document.getElementById("email");
      phone = document.getElementById("phone");
      lname = document.getElementById("lname");
      sname = document.getElementById("sname");
      time = document.getElementById("time");
      agree = document.getElementById("agree")
      
      msg = "";
      if (!$("#agree").attr('checked'))
      { 
          msg += "You must read and agree to the contest rules<br />";
          $(".rules").css("color","#ff0000") 
      }
      msg += req("First name is required<br/>",fname,/\*First Name/);
      msg += req("Last name is required<br/>",lname,/\*Last Name/);
      msg += req("Phone number is required<br/>",phone,/\*Phone Number/);
      checkname($.trim(document.getElementById("sname").value),$.trim(document.getElementById('email').value))
      msg += warning;
      if (!email.value.match(epatt))
      {
          msg += "Email does not appear to be valid<br />";
          email.style.color = "#ff0000";
      }
      msg += req("Screen name is required<br/>",sname,/\*Screen Name/);
      if (msg != "") 
      { 
        $("#modalbox .modalcontent").html("<h1>The form has the following errors</h1>"+msg+"<p>Please correct the errors and try submitting again.</p>");
        $("#modalbox").jqmShow(); 
        return false;
      }
      time.value  = gametime;
      // ajax call to submit the form
      var dataString = 'fname='+ fname.value + '&email=' + email.value + '&phone=' + phone.value;  
      dataString += '&lname='+ lname.value + '&sname=' + sname.value; 
      dataString += '&time='+ time.value; 
      var features = "";
      $(".features").each(function()
      {
          if ($(this).attr("value") != $(this).attr("title"))
          {
              features += $(this).attr("value") + ";";
          }
      });
      dataString += '&features='+ features ;
      var likes = "";
      $(".likes:checked").each(function()
      {
              likes += $(this).attr("value") + ";";
      });
      dataString += '&likes='+ likes; 
      dataString += '&agree='+ agree.value  ;   
      //alert(dataString)

      $("#form").hide() 
      $.ajax({  
       type: "POST",  
       url: "process.php",  
       async: false,
       data: dataString,  
       success: function(data) { 
         
        $("#mainText").hide().load("/includes/pagesnippets.htm #thankyou").fadeIn(1000,function()
        {
           $("#help-agent-reliable-game_div").animate({"opacity":1},"slow")
        });
       },
       error: function(err)
       {
        
        $("#modalbox .modalcontent").html("<div id='message'></div>");  
         $('#message').html("<h2>Entry Form Error!</h2>")  
         .append("<p>We had a problem....</p><p>"+err+"</p><img id='checkmark' src='images/check.png' class='jqmClose' />")  
         .hide()  
         .fadeIn(1500);
         $("#modalbox").jqmShow(); 
       }  
     });  
      return false;
    }
    //==============================================================
    // req is used to test for required fields
    function req(s,i,v)
    {
      if (i.value.match(/^\s*$/) || i.value.match(v) )
      {
        i.style.color="#ff0000";
        return s;
      }
      return ""
    }
function sec2hms (seconds) 
  {
    seconds = parseInt(seconds);
    var h = parseInt(parseInt(seconds/1000)/3600);
    var ms =  seconds % 1000;
    seconds = seconds - ( h * 3600000);
    var min = parseInt(seconds/60000);   

    seconds = parseInt((seconds - (min * 60000))/1000);
    if (h < 10) { h = "0"+h; } 
    if (seconds < 10) { seconds = "0"+seconds; } 
    if (min < 10) { min = "0"+min; } 
    if (ms < 100) { $ms = "0"+ms; } 
    if (ms < 10) { $ms = "0"+ms;} 
    return h+"h : "+min+"m : "+seconds+"s : "+ms+"ms";
    
  }
  //==============================================================
  
    function doshare()
    {
    // load the share your time block
      $("#form").hide();
      $("#mainText").load("/includes/pagesnippets.htm #sharetime",function()
      {
              $(this).fadeIn(1000);
      });
 
    }
    //==============================================================
    function gotoScreen(screen)
    {
        if (screen == "start")
        {
            $("#form").hide();
            $("#help-agent-reliable-game_div").show();
            $("#mainText").hide().load("/includes/pagesnippets.htm #play").fadeIn()
        }
        if (screen == "replay")
        {
            $("#mainText").hide().load("/includes/pagesnippets.htm #play").fadeIn()
        }
    }
    //==============================================================
    function showNewTime(newTime)
    {
          document.getElementById("time").value = newTime;
          gametime=newTime;
          doshare()
    }
    //==============================================================
    // get sname from email
    function getsname(email,f)
    {
          $.ajax({  
             type: "GET",  
             url: "getscreenname.php?type="+f+"&sname=&email="+email,  
             async: false,
             success: function(data) { 
                rdata = data;  // warning is a global used to test
             },
             error: function(err)
             {
              
              $("#modalbox .modalcontent").html("<div id='message'></div>");  
               $('#message').html("<h2>Entry Form Error!</h2>")  
               .append("<p>We had a problem....</p><p>"+err+"</p><img id='checkmark' src='images/check.png' class='jqmClose' />")  
               .hide()  
               .fadeIn(1500);
               $("#modalbox").jqmShow(); 
             } 
             }); 
    }
    //==============================================================
    // see if the email and screen name have been taken
    function checkname(sname,email)
    {
          $.ajax({  
             type: "GET",  
             url: "getscreenname.php?type=check&sname="+sname+"&email="+email,  
             async: false,
             success: function(data) { 
                warning = $.trim(data);  // warning is a global used to test
             },
             error: function(err)
             {
              
              $("#modalbox .modalcontent").html("<div id='message'></div>");  
               $('#message').html("<h2>Entry Form Error!</h2>")  
               .append("<p>We had a problem....</p><p>"+err+"</p><img id='checkmark' src='images/check.png' class='jqmClose' />")  
               .hide()  
               .fadeIn(1500);
               $("#modalbox").jqmShow(); 
             } 
             }); 
    }
