tb_pathToImage = "loading_animation.gif";

$(document).ready(function() {

   //getToolbarState();

  // Animate the banner
  $('.banner-container, .picture-container, .text-container').hover(function(event) {
    var index = event.target.id.substring(7);
    //var icon = '#icon-'+index;
    var picture = '#picture-'+index;
    //$(icon).stop(true).animate({ top:'63px' }, 200);
    $(picture).stop(true).animate({ width:'350px', top:'-20px', right:'-20px' }, 200);
  }, function(event) {
    var index = event.target.id.substring(7);
    //var icon = '#icon-'+index;
    var picture = '#picture-'+index;
    //$(icon).stop(true).animate({ top:'15px' }, 200);
    $(picture).stop(true).animate({ width:'312px', top:'0px', right:'0px' }, 200);
  });

    jQuery('#mycarousel').jcarousel({
        animation: "slow",
        auto: 4,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });
  
    
    // <a target="link" is not validation friendly so do it with JavaScript
    setLinks();
    
});

function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function expandCollapse(element, speed) {
    var animation_speed = 'normal';
    
    if(speed){
        animation_speed = speed;
    }
    
    if($(element).is(':visible')){
        $(element).fadeOut(speed);
    } else {
        $(element).fadeIn(speed);
    }   
}

function survey_section(value)
{
    if(value == 'Yes'){
        $('#sub-2').fadeIn();
    } else {
        $('#sub-2').fadeOut();
    }
}

function concatObject(obj) {
  str='';
  for(prop in obj)
  {
    str+=prop + " value :"+ obj[prop]+"\n";
  }
  return(str);
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ( (exdays == null) ? "" : "; expires = "+exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
      x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
      y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g, "");
      if (x == c_name) {
        return unescape(y);
      }
  }
}

function office_search_preselect_country(country)
{
    $('#country_select').val(country);
    office_search();
}

function office_search()
{
    var fname = 'State';
    
    if($('#country_select').val() != 'USA') {
        fname = 'Province';
    }
    
    $.ajax({
       type: "POST",
       url: "../ajax/getStates/"+$('#country_select').val(),
       dataType: "text",
       success: function(msg) {
           // If this is in canada, change onchange to getCanadaCounties
           if($('#country_select').val() == 'Canada'){
               msg = msg.replace('getStateCounties', 'getCanadianCounties')
               
               $('#state_province').html( msg );
           
               // Replace all occurances so use some regex
               msg = msg.replace(/county_state_province_dropdown/g, 'city_state_province_dropdown');
               msg = msg.replace('getCanadianCounties', 'getCanadianCities')

               $('#city_state_province').html( msg );
           } else {
               $('#state_province').html( msg );
           
               // Replace all occurances so use some regex
               msg = msg.replace(/county_state_province_dropdown/g, 'city_state_province_dropdown');
               msg = msg.replace('getStateCounties', 'getStateCities');

               $('#city_state_province').html( msg );
           }
       }
    });
    
    $('#state_province_counties').html( defaultDropDown('county', fname) );
    $('#city_dropdown').html( defaultDropDown('cities', fname) );
    
    $('#county_state').text(fname);
    $('#city_state').text(fname);
    
    $('#country').fadeOut();
    $('#specifics').fadeIn();
}

function getCanadianCounties()
{
    $('#county_info').fadeIn();
    
    $.ajax({
       type: "POST",
       url: "../ajax/getCanadianCounties/"+$('#county_state_province_dropdown').val(),
       dataType: "text",
       success: function(msg) {
           $('#county_info').fadeOut();
           
           $('#state_province_counties').html( msg );
           $('#city_error_msg').html( '' );
       },
       error: function(msg) {
           $('#county_info').fadeOut();
           
           $('#city_error_msg').html( 'Our system encountered an error, please try again' );
           // Re-populate the states list because it has more than likely been altered
           office_search();
       }
    });
}

function getCanadianCities()
{
    $('#city_info').fadeIn();
    
    $.ajax({
       type: "POST",
       url: "../ajax/getCanadianCities/"+$('#city_state_province_dropdown').val(),
       dataType: "text",
       success: function(msg) {
           $('#city_info').fadeOut();
           
           $('#city_dropdown').html( msg );
           $('#city_error_msg').html( '' );
       },
       error: function(msg) {
           $('#city_info').fadeOut();
           
           $('#city_error_msg').html( 'Our system encountered an error, please try again' );
           // Re-populate the states list because it has more than likely been altered
           office_search();
       }
    });
}

function defaultDropDown(name, type)
{
    if(type == ''){
        type = 'State'
    }
    
    var string = '<select name="' + name + '"><option value="none">Select a ' + type + ' First</option></select>';
    
    return string;
}

function getStateCounties()
{
    $('#county_info').fadeIn();
    
    $.ajax({
       type: "POST",
       url: "../ajax/getCounties/"+$('#county_state_province_dropdown').val(),
       dataType: "text",
       success: function(msg) {
           $('#county_info').fadeOut();
           
           $('#state_province_counties').html( msg );
           $('#county_error_msg').html( '' );
       },
       error: function(msg) {
           $('#county_info').fadeOut();
           
           $('#county_error_msg').html( 'Our system encountered an error, please try again' );
           // Re-populate the states list because it has more than likely been altered
           office_search();
       }
    });
    
}


function getStateCities()
{
    $('#city_info').fadeIn();
    
    $.ajax({
       type: "POST",
       url: "../ajax/getCities/"+$('#city_state_province_dropdown').val(),
       dataType: "text",
       success: function(msg) {
           $('#city_info').fadeOut();
           
           $('#city_dropdown').html( msg );
           $('#city_error_msg').html( '' );
       },
       error: function(msg) {
           $('#city_info').fadeOut();
           
           $('#city_error_msg').html( 'Our system encountered an error, please try again' );
           // Re-populate the states list because it has more than likely been altered
           office_search();
       }
    });
    
}

function resizeFrame(f) {
    if(f)
        f.style.height = f.contentWindow.document.body.scrollHeight + "px";
}

function setLinks() {
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  if (links.length == 0) return false;
  for (var i = 0; i < links.length; i++) {
    var relation = links[i].getAttribute("rel");
    
    if (relation && relation.match(/external/)) { //}  relation == "external") {
        
      links[i].onclick = function() {
        return !window.open(this.href);
      }
    }     
  }
}

function sendReportEmail(post_url)
{
    
    // Fade the form out until we get a response
    $('#pdf_errors').html('');
    $('#pdf_sending').fadeIn();
    
    var from = $('#pdf_from').val();
    var recipient = $('#pdf_recipient').val();
    var subject = $('#pdf_subject').val();
    var message = $('#pdf_message').val();
    
    var data = { "from":from, "recipient":recipient, "subject":subject, "message":message};
    var items = [];
    var found_errors = false;
    
    $.ajax({
        type: 'POST',
        url: post_url,
        data: data,
        success: function(response){
            $('#pdf_sending').fadeOut();  
            
            // Loop through the result and look for error;
            $.each(response, function(key, val) {
                if(key == 'error')
                {
                    items.push('<li id="' + key + '">' + val + '</li>');
                    found_errors = true;
                }
            });
            
            $('<ul/>', {
                html: items.join('')
            }).appendTo('#pdf_errors');
            
            if(!found_errors)
            {
                $('#pdf_errors').html('Email Sent');
                $('#pdf_sending').fadeOut();  
                
                $('#pdf_from').val('');
                $('#pdf_recipient').val('');
                $('#pdf_subject').val('');
                $('#pdf_message').val('');
            }
        },
        timeout: function(response){
            alert(response + ' timeout');  
        },
        error: function(response){
            $('#pdf_sending').fadeOut();  
            
            $('#pdf_errors').html('An error occurred, please try again');
            /*
            $.each(response, function(key, val) {
                alert(key + ':' + val);
            });
            */
        },
        complete: function(){
            $('pdf_sending').fadeOut();  
        },
        dataType: "json"
    });
    
}

function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function checkPdfForm(url)
{
    var errors = '';
    
    if(!isValidEmail($('#pdf_from').val()))
        errors += '- Invalid From Email Address<br />';
    
    if(!isValidEmail($('#pdf_recipient').val()))
        errors += '- Invalid Recipient Email Address<br />';
    
    $('#pdf_errors').html(errors);
    
    if(errors == '')
    {
        sendReportEmail(url);
        return true;
    }
    
    return false;
}

function playSound(soundfile) {
    $("#jquery_jplayer_1").jPlayer({
        ready: function () {
            $(this).jPlayer("setMedia", {
                m4a: soundfile
                //oga: "/media/mysound.ogg"
            });
        },
        swfPath: "/assets/js/",
        supplied: "m4a"//, oga"
    });
    //alert(soundfile);
    //document.getElementById("sound_element").innerHTML = "<embed name=\"embedded_player\" id=\"embedded_player\" src=\""+soundfile+"\" hidden=\"false\" autostart=\"false\" loop=\"false\" />";   
}

function sound_stop()
{
    //var player = $('#embedded_player');
    //player.stop();
    document.embedded_player.stop();
}

function sound_play()
{
    var player = $('#embedded_player');
    player.pause();
    //document.embedded_player.pause();
}

function newsletter_subscribe(subscribe)
{
    // Fade the form out until we get a response
    var first = $('#newsletter_first_name').val();
    var last = $('#newsletter_last_name').val();
    var email = $('#newsletter_email').val();
    var zip = $('#newsletter_zip').val();
    var items = [];
    var errors = '';
    var found_errors = false;
    
    $('#newsletter_errors').html('');
    $('#newsletter_success').html('');
    
    if(first.length < 1)
    {
        errors += '<li>Please Enter a valid first name</li>';
    }
    
    if(last.length < 1)
    {
        errors += '<li>Please Enter a valid last name</li>';
    }
    
    if(zip.length < 5)
    {
        errors += '<li>Please Enter a valid Zip/Postal Code</li>';
    }

    if(!isValidEmail(email))
    {
        errors += '<li>Please Enter a valid email address</li>';
    }
    
    var data = { "first_name":first, "last_name":last, "email":email, "zip":zip};
    
    if(errors != '')
    {
        $('#newsletter_errors').html('<ul>'+errors+'</ul>');
        return false;
    }
    
    $('#newsletter_success').html('Processing . . .');
    
    $.ajax({
        type: 'POST',
        url: subscribe,
        data: data,
        success: function(response){
            // Loop through the result and look for error;
            $.each(response, function(key, val) {
                if(key == 'error')
                {
                    items.push('<li id="' + key + '">' + val + '</li>');
                    found_errors = true;
                }
            });
            
            $('<ul/>', {
                html: items.join('')
            }).appendTo('#newsletter_errors');
            
            if(!found_errors)
            {
                $('#newsletter_errors').html('');
                $('#newsletter_success').html('Thank you for subscribing to our newsletter');
                
                $('#newsletter_first_name').val('');
                $('#newsletter_last_name').val('');
                $('#newsletter_email').val('');
                $('#newsletter_zip').val('');
            }
            
        },
        timeout: function(response){
            //alert(response + ' timeout');  
        },
        error: function(response){
            $('#newsletter_success').html('');
            $('#newsletter_errors').html('An error occurred, please try again');
        },
        complete: function(){
            
        },
        dataType: "json"
    });
    
}

function resize_image(image, w, h) {

    if (typeof(image) != 'object') image = document.getElementById(image);

    // Find out which is bigger height/width
    if(image.clientHeight > image.clientWidth)
        image.style['height'] = h + 'px';
    else
        image.style['width'] = w + 'px';
    
    /*
    if (w == null || w == undefined)
        w = (h / image.clientHeight) * image.clientWidth;

    if (h == null || h == undefined)
        h = (w / image.clientWidth) * image.clientHeight;

    image.style['height'] = h + 'px';
    image.style['width'] = w + 'px';
    */
    return;
}
