/* Helper Object
 * Adds helper methods to simplify development.
--------------------------------------------------------------- */
var helper = new Helper();

function Helper() {
    this.inArray = function (needle, haystack) {
        var length = haystack.length;
        for (var i = 0; i < length; i++) {
            if (haystack[i] == needle) return true;
        }
        return false;
    }
}

//CHECK FOR IE6
function is_ie6(){
     return ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined));
 }

 $(document).ready(function () {

     // colorbox
     if ($(".cb-testimonial-1").length > 0) {
         $(".cb-testimonial-1").colorbox({ inline: true, href: "#testimonial-1" });
         $(".cb-testimonial-2").colorbox({ inline: true, href: "#testimonial-2" });
         $(".cb-testimonial-3").colorbox({ inline: true, href: "#testimonial-3" });
         $(".cb-testimonial-4").colorbox({ inline: true, href: "#testimonial-4" });
     }

     if ($("#shareit").length > 0) {
         $("#shareit").fancybox({
             'type': 'inline',
             'overlayShow': true,
             'overlayOpacity': 0.6,
             'overlayColor': '#000'
         });

         var switchTo5x = true;
         stLight.options({ publisher: 'de75e2a0-08db-48ec-9b33-3d6031f9809f' });
     }


     //float
     if ($('#guide-box').length) {
         $('#guide-box').makeFloat({ x: 710, y: 120, Speed: "fast" });
     }

     //hide the background image from IE6
     if (!is_ie6()) {

         $('img.maximage').maxImage({
             maxFollows: ('width'),
             overflow: ('auto'),
             position: ('absolute'),
             isBackground: (true),
             zIndex: (1),
             slideDelay: 15,
             verticalAlign: ('top'),
             horizontalAlign: ('center'),
             maxAtOrigImageSize: (false),
             slideShow: (true)
         });
     } else {
         $('#mainImage').show();
     }

     // get height of breadcrumb box; apply it to subnav header
     var bheight = "height: " + $('#breadcrumbs').height() + "px";
     $('.section-name-outer').attr('style', bheight);

     if ($('#sub-menu').height() > $('#main').height()) {
         var subheight = "height: " + $('#sub-menu').height() + "px";
         $('#main').attr('style', subheight);
     }

     // focus/blur search form field
     $("input.search").focus(function () {
         if (this.value == this.defaultValue) { this.value = ""; }
     }).blur(function () {
         if (!this.value.length) { this.value = this.defaultValue; }
     });

     // go button hover
     $('input.bttn').hover(function () {
         $(this).css('background-position', '0 -28px');
     },
		function () {
		    $(this).css('background-position', '0 0');
		}
	);

		// footer search button hover
		$('#footer div.col4 input.bttn').hover(function () {
		    $(this).css('background-position', '0 -32px');
		},
		function () {
		    $(this).css('background-position', '0 0');
		}
	);



     // add 'last' class to last items in sub-menu (removed bottom border)
     $('ul.sub-menu li:last').addClass('last');
     $('ul.sub-menu ul li:last').addClass('last');

     // add selected class to parent li for submenus (add grey arrow)
     $('ul.sub-menu ul li a').each(function (index) {
         if ($(this).attr("class") == "selected") { $(this).parent().addClass("selected"); }
     });

     // main navigation/dropdowns
     $('#nav').superfish({
         hoverClass: 'sfHover', // the class applied to hovered list items 
         delay: 300, // the delay mouse can remain outside a submenu without it closing 
         animation: { opacity: 'show', height: 'show' },
         speed: 'fast', // speed of the animation. 
         dropShadows: true,
         autoArrows: false,
         // onBeforeShow: hidePopup,
         onShow: hidePopup,
         onHide: showPopup
     }).find('ul').bgIframe({ opacity: false }); // fix IE6 bug overlapping <select> elements

     // init background images  
     $("#background img").each(function () {
         if ($(this).hasClass('hide')) {
             $(this).hide();
             $(this).removeClass('hide');
         }
     });

     // init pop-up boxes 
     $("#popup-container div").each(function () {
         if ($(this).hasClass('hide')) {
             $(this).hide();
             $(this).removeClass('hide');
         }
     });

     // init pop-up bars  
     $("#popup-bar div").each(function () {
         if ($(this).hasClass('hide')) {
             $(this).hide();
             $(this).removeClass('hide');
         }
     });


     // removes default values from form
     if (document.getElementById("consult-short-form")) {
         $("#consult-short-form input").bind("click", function () {
             var stripStrings = ["First Name", "Last Name", "Email", "Phone"];
             var $target = $(this);

             if (helper.inArray($target.val(), stripStrings)) { $target.val(""); }
         });

         $.getScript('http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js', function () {
             jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
                 phone_number = phone_number.replace(/\s+/g, "");
                 return this.optional(element) || phone_number.length > 9 &&
		            phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
             }, "Invalid phone number.");
             jQuery.validator.addMethod("fRequired", $.validator.methods.required,
                "First name is required.");
             jQuery.validator.addMethod("lRequired", $.validator.methods.required,
                "Last name is required.");
             jQuery.validator.addMethod("eRequired", $.validator.methods.required,
                "Email is required.");
             jQuery.validator.addMethod("eValidShort", $.validator.methods.email,
                "Email is required.");
             jQuery.validator.addMethod("pRequired", $.validator.methods.required,
                "Email is invalid.");
             $("#consult-short-form").validate({
                 rules: {
                     FirstName: {
                         fRequired: true
                     },
                     LastName: {
                         lRequired: true
                     },
                     Email: {
                         eRequired: true,
                         eValidShort: true
                     },
                     Phone: {
                         pRequired: true,
                         phoneUS: true
                     }
                 },
                 errorPlacement: function (error, element) {
                     $(element).parent().children(".errors").append(error);
                 },
                 highlight: function (element) {
                     $(element).addClass("error");
                 },
                 unhighlight: function (element) {
                     $(element).removeClass("error");
                 }

             });
         });
     }

     // consultation form validations
     if (document.getElementById("consultationform")) {
         $.getScript('http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js', function () {
             jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
                 phone_number = phone_number.replace(/\s+/g, "");
                 return this.optional(element) || phone_number.length > 9 &&
		            phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
             }, "Please specify a valid phone number");

             $("#consultationform").validate({
                 rules: {
                     FirstName: {
                         required: true
                     },
                     LastName: {
                         required: true
                     },
                     Email: {
                         required: true,
                         email: true
                     },
                     Accept: {
                         required: true
                     },
                     Phone: {
                         required: true,
                         phoneUS: true
                     }
                 },
                 errorPlacement: function (error, element) {
                     error.insertBefore(element.parent().children("li"));
                 },
                 highlight: function (element) {
                     $(element).parent().addClass("error");
                 },
                 unhighlight: function (element) {
                     $(element).parent().removeClass("error");
                 }

             });
         });
     }

     // referral form validations
     if (document.getElementById("referralform")) {
         $.getScript('http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js', function () {
             $("#referralform").validate({
                 rules: {
                     FirstName: {
                         required: true
                     },
                     LastName: {
                         required: true
                     },
                     Email: {
                         required: true,
                         email: true
                     },
                     FirstNameReferral: {
                         required: true
                     },
                     LastNameReferral: {
                         required: true
                     },
                     EmailReferral: {
                         required: true,
                         email: true
                     },
                     Captcha: {
                         required: true,
                         minlength: 5,
                         remote: {
                             url: "/consultation/CheckCaptcha/",
                             data: { captchaguid: function () {
                                 return $("#captcha-guid").val();
                             },
                                 cache: false
                             }
                         }
                     }
                 },
                 errorPlacement: function (error, element) {
                     error.insertBefore(element.parent().children("li"));
                 },
                 highlight: function (element) {
                     $(element).parent().addClass("error");
                 },
                 unhighlight: function (element) {
                     $(element).parent().removeClass("error");
                 }

             });
         });
     }



     // print page
     $('#print-page').prepend('<a href="#">print this page</a>');
     $('#print-page a').click(function () {
         window.print();
         return false;
     });

     // newsletter form validations
     if ($("#newsletterform").length) {
         $.getScript('http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js', function () {
             $("#newsletterform").validate({
                 rules: {
                     Name: {
                         required: true
                     },
                     Email: {
                         required: true,
                         email: true
                     }
                 },
                 errorElement: "div",
                 wrapper: "div",  // a wrapper around the error message
                 errorPlacement: function (error, element) {
                     offset = element.offset();
                     error.insertAfter(element)
                     error.addClass('message');  // add a class to the wrapper
                 }
             });
         });
     }

     //find terms

     var termList = [];

     $('.def').each(function () {
         termList.push($(this).text());
     });

     $('.def').mouseover(function () {
         $('#linkList').text('');

         //var lo = hoverData.length;
         // if (hoverData.length > 5) {
         //     lo = 5;
         //  }
         var c = 0;
         for (var x = 0; x < hoverData.length; x++) {
             if (hoverData[x].Term.toLowerCase() == $(this).text().toLowerCase()) {
                 //found it
                 if (c < 6) {
                     setToolText(hoverData[x]);
                     c++;
                 }

             }
         }
     });


     var postData = { terms: termList };

     if (termList.length > 0) {
         $.ajax({
             type: "POST",
             url: "/Home/ToolboxTerms",
             data: postData,
             success: function (data) {
                 setupDgTool(data);
             },
             error: function (data) {
                 alert("Sorry, there was a problem connecting to the server");
             },
             dataType: "json",
             traditional: true
         });
         return false;
     } else {
         $('#guide-box-middle .title').text('Search keywords');
         $('#guide-box-middle .subheading').text('');
         $('#linkList').text('');
     }


     $('#sub-nav').mouseover(function () {
         $.fn.maxImage.pauseSlider();
     });

     $('#sub-nav').mouseout(function () {
         $.fn.maxImage.resumeSlider();
     });

     $('#sub-nav a').click(function () {
         // $("#popup-container div").each(function() {
         //     $(this).hide();
         // });
         var clicked = $(this);
         var index = $(this).parent().index();
         $.fn.maxImage.jumpToSlide(index);
     });

 });

var hoverData;

function setupDgTool(data) {
    
    hoverData = data;

    if (hoverData.length > 0) {
        $('#linkList').text('');
        setToolText(hoverData[0]);
    } else {
        //setToolText("No terms available"); 
        //no links available
        //alert("No terms available");
    }
}


function setToolText(data) {
    $('#guide-box-middle .title').text('"' + data.Term + '"');
    $('#linkList').append('<li><a href="/california-divorce-guide/' + data.CategoryUrlKey + '/' + data.UrlKey + '/' + '">' + data.Title + '</a></li>');
}


// superfish callbacks
function hidePopup() {
    $.fn.maxImage.pauseSlider();
    
	clearTimeout($("#popup-container").data('timeoutId'));
	$("#popup-container").find(".active").fadeTo(200, 0);
}

function showPopup() {
    //debugger;
    $.fn.maxImage.resumeSlider();
    var timeoutId = setTimeout(function() { $("#popup-container").find(".active").fadeTo(200, 1, ieFix); }, 400);
	$("#popup-container").data('timeoutId', timeoutId); 
}

function ieFix() {
    try {
        this.style.removeAttribute('filter');
    } catch(e) {}
}

function printPage() {
    window.print();
}

