// from http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

var clips = new Array('#sustainable-construction','#safety-policy','#icra-policy');

function divSlide(div_id,setHeight,setTop,timeMs) {
  $(div_id).stop().animate({
      height: setHeight, 
      top: setTop
    }, {
      duration: timeMs
    }
  );
  
//  $('#news-panel-top-border').stop().animate({
//      top: setTop
//    }, {
//      duration: timeMs
//    }
//  );
}

function divExpand(div_id) {
	$(div_id).stop().animate({height: "100%"},{duration: 500});
}

function newsPanelSlideIn() {
  divSlide("#news-panel","102px","-104px",500);
  divSlide("#news-panel-top-border","102px","-104px",500);
}
  
function newsPanelSlideOut() {
  divSlide("#news-panel","42px","-44px",500);
  divSlide("#news-panel-top-border","42px","-44px",500);
}

function loginSlideIn() {
  if ( is_admin )
    divSlide("#login_form","75px","-50px",500);
  else
    divSlide("#login_form","180px","-155px",500);
}

function loginSlideOut() {
  divSlide("#login_form","30px","-5px",500);
}


function f_setLogin() {
  var nlreq_form = $('#nlreq_form');

  if( !is_admin ) { // is_admin is a global variable set in head.php
    // Launch MODAL BOX if the Login Link is clicked
    $("#btnLogin").click(function(){
      $('#login_form').modal();
    });
  
    // When the form is submitted
    $("#status > form").submit(function(){
      $('#submit').hide();
      $('#ajax_loading').show();
      var str = $(this).serialize();  
      $.ajax({  
        type: "POST",
        url: "do-login.php",  
        data: str,  
        success: function(msg){
          $("#status").ajaxComplete(function(event, request, settings){  
            $('#submit').show();
            $('#ajax_loading').hide();  
            if(msg == 'OK') {  
              var login_response = "<div style='padding:20px;'>Login Successful : Please wait! Loading Admin content..</div>";  
              $('a.modalCloseImg').hide();  
              $('#simplemodal-container').css("width","300px");
              $('#simplemodal-container').css("height","120px");
              $(this).html(login_response); 
              // After 3 seconds reload the page
              setTimeout('window.location.reload()', 3000); 
            } else {
              var login_response = msg;
              $('#login_response').html(login_response);
            }  
          });  
        }     // end sucess function
      });  // end ajax
      return false;
    }); // end submit

    if( nlreq_form.length ) {
      // form validator for newsletter request form
      nlreq_form.validate({
        rules: {
          first_name: "required",
          last_name: "required",
          email_address: {
            required: true,
            email: true
          }
        }
      });
        
      $("#nlreq_form_area > form").submit(function(){
        if ( nlreq_form.valid() ) {
          $('#nlreq_submit').hide();
          $('#nlreq_ajax_loading').show();
          $.ajax({  cache: false,
            data: {
              first_name: $('#first_name').val(),
              last_name: $('#last_name').val(),
              email_address: $('#email_address').val()
            },
            type: "POST",
            dataType: "html",
            url: "include/add_nlreq.php",  
            success: function(msg){
              $("#nlreq_form_area").ajaxComplete(function(event, request, settings){  
                if(msg == 'OK') {  
                  var nlreq_response = "<div style='padding:20px; color:#439644'>Thank you for your interest!<br><br></div>";  
                } else {
                  var nlreq_response = "<div style='padding:20px;color:red'>We are sorry but some error has occured! <br><br>Your request could not be completed.. Please try again later..<br><br></div>";  
                }  
                $(this).html(nlreq_response); 
              });  
            }     // end sucess function
          });  // end ajax
        }
        return false;
      }); // end submit
    }
  }
}

function rotateClips() {
  var fold_re = new RegExp("-fold.gif$");
  var plain_re = new RegExp(".gif$");
  
  $(clips[2]).animate({
    top: "91px"
  }, 900, "easeOutBack", function () {
    var src = $(clips[2]).attr('src');
    src = src.replace(fold_re,".gif");
    
    $(clips[2]).attr('src',src).height(63).css('z-index',6);

    src = $(clips[1]).attr('src');
    src = src.replace(plain_re,"-fold.gif");
    $(clips[1]).attr('src',src).height(79).css('z-index',2).animate({
      top: "38px"
    }, 900);
    
    $(clips[0]).css('z-index',4).animate({
      top: "32px"
    },900);

    $(clips[2]).animate({
      top: "26px"
    }, 900, "easeOutQuint", function () {
      $(clips[2]).addClass('top').removeClass('bottom'); // new top
      $(clips[1]).addClass('bottom').removeClass('middle');  // new bottom
      $(clips[0]).addClass('middle').removeClass('top'); // new middle
      
      clips.unshift(clips.pop());
    });
  });
}

$(document).ready(function () {
  jQuery.preLoadImages(
    "images/PaperClip-SustainableCon.gif","images/PaperClip-SustainableCon-fold.gif","images/PaperClip-SafetyPolicy.gif",
    "images/PaperClip-SafetyPolicy-fold.gif","images/PaperClip-ICRAPolicy.gif","images/PaperClip-ICRAPolicy-fold.gif"
  );
  
  $('#keywords').blur(function () {
    if (!$(this).val()) {
      $(this).css('background','white url(http://www.google.com/coop/images/google_custom_search_watermark.gif) no-repeat 0% 50%');
    }
  });
  
  $('#keywords').focus(function () {
    $(this).css('background','');
  });

  $('#news-panel').hover(newsPanelSlideIn,newsPanelSlideOut);
  $('#login_form').hover(loginSlideIn,loginSlideOut);
    
  // call function that sets login form
  f_setLogin();
    
    // setup show comments button and submit comment form on topic_toolbar
    f_setComments();

  $.timedInterval(12000,function () {
    rotateClips();
  });
  
  $('#keywords').css('outline','0 none');
  $('#keywords').blur();
});


function f_setComments() {
  $(".btnComnt").click(function(){
    $clicked = $(this);         
    var idToLoad = $clicked.attr("id").split('__');
    $(".divComnt").hide("fast");
    $(".divComnt").html("<img src='images/spinner.gif' width='16' height='16' alt='Loading' /> Loading..");
    $("#divComnt__"+idToLoad[1]).show("slow");
    $.ajax({
      cache: false,
      data: { cid: idToLoad[1] },
      dataType: "text",
      error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("Error: Failed to load comments\n" + XMLHttpRequest.responseText + "\n" +
              textStatus + "\n" + errorThrown);
          $("#divComnt__"+idToLoad[1]).hide();
      },
      success: function (data, textStatus) {
              $("#divComnt__"+idToLoad[1]).html(data);
              f_setComntForm();
      },
      type: "GET",
      url: "include/get_comnt_view.php"
    });
  });
}

function f_setComntForm() {
  var comnt_form = $('#comnt_form');
  if( comnt_form.length ) {
      // form validator for newsletter request form
      comnt_form.validate({
          rules: {
              first_name: "required",
              comments: "required",
              email_address: {
                  required: true,
                  email: true
              }
          }
      });
    
        $("#comnt_form_area > form").submit(function(){
            if ( comnt_form.valid() ) {
                $('#comnt_submit').hide();
                $('#comnt_ajax_loading').show();
                $.ajax({  cache: false,
                    data: {
                        first_name: $('#first_name').val(),
                        comment: $('#comments').val(),
                        cid: $('#cid').val(),
                        email_address: $('#email_address').val()
                    },
                    type: "POST",
                    dataType: "html",
                    url: "include/add_comnt.php",  
                    success: function(msg){
                        $("#comnt_form_area").ajaxComplete(function(event, request, settings){  
                            if(msg == 'OK') {  
                                var comnt_response = "<div style='padding:20px; color:#439644'>Thank you for your feedback!<br><br></div>";  
                            } else {
                                var comnt_response = "<div style='padding:20px;color:red'><br>We are sorry but some error has occured! <br><br>Your request could not be completed.. Please try again later..<br><br></div>";  
                            }  
                            $(this).html(comnt_response); 
                        });  
                    }     // end sucess function
                });  // end ajax
            }
            return false;
        }); // end submit

  }
}





