this.tooltip = function() {
  /* CONFIG */
  xOffset = -24;
  yOffset = -15;
  // these 2 variable determine popup's distance from the cursor
  // you might want to adjust to get the right result		
  /* END CONFIG */
  $("a.tooltip").hover(function(e) {
    this.t = this.title;
    this.title = "";
    $("body").append("<p id='tooltip'>" + this.t + "</p>");
    $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
  },
	function() {
	  this.title = this.t;
	  $("#tooltip").remove();
	});
  $("a.tooltip").mousemove(function(e) {
    $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
  });
};

this.featurehelp = function() {

  /* CONFIG */
  xxOffset = 10;
  yyOffset = 20;
  // these 2 variable determine popup's distance from the cursor
  // you might want to adjust to get the right result		
  /* END CONFIG */
  $("a.featurehelp").hover(function(e) {
    this.t = this.title;
    this.title = "";
    $("body").append("<div id='featurehelp'>" + this.t + "</div>");
    $("#featurehelp")
			.css("top", (e.pageY - xxOffset) + "px")
			.css("left", (e.pageX + yyOffset) + "px")
			.fadeIn("fast");
  },
	function() {
	  this.title = this.t;
	  $("#featurehelp").remove();
	});
  $("a.featurehelp").mousemove(function(e) {
    $("#featurehelp")
			.css("top", (e.pageY - xxOffset) + "px")
			.css("left", (e.pageX + yyOffset) + "px");
  });
};


function isValidEmailAddress(emailAddress) {
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
}


// starting the script on page load
$(document).ready(function() {
    tooltip();
    featurehelp();

    $('.hostinput').hide();
    $('#trialsubmitted').hide();

    // Input fields / idle and focus

    $('.searchfield').addClass("searchidle");
    $('.searchfield').focus(function() {
        $(this).removeClass("searchidle").addClass("searchfocus");
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });

    $('.searchfield').blur(function() {
        $(this).removeClass("searchfocus").addClass("searchidle");
        if ($.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass("searchfocus").addClass("searchidle");
        }
    });

    $('input[type="text"]').not('.searchfield').addClass("idleField");

    $('input[type="text"]').not('.searchfield').focus(function() {
        $(this).removeClass("idleField").addClass("focusField");
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });

    $('input[type="text"]').not('.searchfield').blur(function() {
        $(this).removeClass("focusField").addClass("idleField");
        if ($.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass("focusField").addClass("idleField");
        } else {
            $(this).removeClass("focusField").addClass("completedField");
        }
    });


    $('textarea').addClass("idleField");
    $('textarea').focus(function() {
        $(this).removeClass("idleField").addClass("focusField");
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });

    $('textarea').blur(function() {
        if ($.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass("focusField").addClass("idleField");
        } else {
            $(this).removeClass("focusField").addClass("completedField");
        }

    });


    $('#hostaccount').alpha();

    $('.hostit').click(function() {
        $('.downloadit').slideToggle(500);
        $(this.hash).slideToggle(500);
        $(this).toggleClass('option_selected');
        return false;
    });

    $('.downloadit').click(function() {
        $('.hostit').slideToggle(500);
        $(this).toggleClass('option_selected');
        $(this.hash).slideToggle(500);
        return false;
    });

    $('#hostaccount').keyup(function(e) {
    $('#accounturl').text($(this).val() + '.' + $("#currentserver").val() + '.incentivelive.com');
        $('#status').addClass('checking');
        $('#status').text('Checking availability...');
        //var hostheader = $('#accounturl').text();
        var hostheader = $(this).val();


        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/api/exists?hostheader=" + hostheader,
            dataType: "json",
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                if (XMLHttpRequest.statusText.length > 0) {
                    $('#status').text('An error has occured');
                }
                $('#status').addClass('waiting');

            },
            success: function(data, textStatus) {
                
                if (typeof (data.Status) != "undefined" && data.Status == "error") {
                    $('#status').attr('class', 'waiting');
                    $('#status').text('An error has occured');
                } else {
                    if (data.Status.toLowerCase() == "true") {
                        $('#status').attr('class', 'exists');
                        $('#status').text('Site name already exists');

                    } else {
                        $('#status').attr('class', 'ok');
                        $('#status').text('Site name available');

                    }
                }

            }
        });
    });

    $('#hostedtrial').click(function() {
        var hostheader = $('#hostaccount').val();
        var fullname = $("#customer").val();
        var email = $("#email").val();
        var company = $("#company").val();

        if (fullname == "Name" || company == "Company" || email == "E-Mail") {
            $('#error').html("Please fill out all the required fields.");
            $('a.error').trigger('click');
            return false;
        }

        if (hostheader.indexOf(" ") != -1) {
            $('#error').html("The Incentive Live trial address is not valid.");
            $('a.error').trigger('click');
            return false;
        }

        if (!isValidEmailAddress(email)) {
            $('#error').html("Please enter a valid email address.");
            $('a.error').trigger('click');
            return false;
        }

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/api/createtrial/?name=" + fullname + "&email=" + email + "&type=0&hostheader=" + hostheader + "&company=" + company,
            dataType: "json",
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                if (XMLHttpRequest.statusText.length > 0) {
                    alert("Error: " + textStatus);
                }
            },
            success: function(data, textStatus) {
                if (typeof (data.Status) != "undefined" && data.Status == "error") {
                    alert(data.Message);
                } else {
                    $('#trialform').slideToggle(500);
                    $('#trialsubmitted').slideToggle(500);
                }
            }
        });
        return false;
    });

    $('#downloadtrial').click(function() {
        var fullname = $("#customer").val();
        var email = $("#email").val();
        var company = $("#company").val();

        if (fullname == "Name" || company == "Company" || email == "E-Mail") {
            $('#error').html("Please fill out all the required fields.");
            $('a.error').trigger('click');
            return false;
        }

        if (!isValidEmailAddress(email)) {
            $('#error').html("Please enter a valid email address.");
            $('a.error').trigger('click');
            return false;
        }

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/api/createtrial/?name=" + fullname + "&email=" + email + "&type=2&company=" + company,
            dataType: "json",
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                if (XMLHttpRequest.statusText.length > 0) {
                    alert("Error: " + textStatus);
                }
            },
            success: function(data, textStatus) {
                if (typeof (data.Status) != "undefined" && data.Status == "error") {
                    alert(data.Message);
                } else {                    
                    $('#trialform').slideToggle(500);
                    $('#trialsubmitted').slideToggle(500);
                }
            }
        });
        return false;
    });


    $('#content>h2 + div').hide();
    $('#content>h2').click(function() {
        $(this).next().slideToggle(500);
        $(this).toggleClass('selected');
    });

    $(".addCaption").each(
		function() {
		    $(this).wrap('<div class="imageWrapper"></div>');
		    $(this).parent().append('<div class="imageCaption"><h1>' + $(this).attr('title') + '</h1><p>' + $(this).attr('alt') + '</p></div>');
		}
	);



    setInterval("blogFlow()", 5000);

    $(".puffImg").each(
		function() {
		    $(this).wrap('<div class="puffImage"></div>');
		}
	);


    $("a.puffZoom").fancybox();
    $("a.dialog").fancybox({ 'hideOnContentClick': false, 'showCloseButton': false });

});


function blogFlow() {

  var $active = $('#blogflow DIV.active');
  var $next = $active.next().length ? $active.next() : $('#blogflow DIV:first');

  $active.css({ opacity: 1.0 })
        .animate({ opacity: 0.0 }, 500, function() {
          $active.removeClass('active');
        });

  $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 500, function() {
        });

  var $activecount = $('#blogflowcount DIV.active');
  var $nextcount = $activecount.next().length ? $activecount.next() : $('#blogflowcount DIV:first');

  $activecount.removeClass('active')
  $nextcount.addClass('active')
}