﻿/*
www.webdevelopercv.com
Copyright (c) 2010 Evgeny Neumerzhitskiy.
Please feel free to use any part of my code. If you put a reference to me I would be grateful, but it's not required.*/
/// <reference path="jquery-1.4.1.min.js"/>

 // implement JSON.stringify serialization     
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj); 
    if (t != "object" || obj === null) { 
        // simple data type 
        if (t == "string") obj = '"'+obj+'"'; 
        return String(obj); 
    } 
    else { 

        // recurse array or object 
        var n, v, json = [], arr = (obj && obj.constructor == Array); 

        for (n in obj) { 
            v = obj[n]; t = typeof(v); 

            if (t == "string") v = '"'+v+'"'; 
            else if (t == "object" && v !== null) v = JSON.stringify(v); 

            json.push((arr ? "" : '"' + n + '":') + String(v)); 
        } 

        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); 
    }
};


var ftc_obb = {
    isAdmin: false,
    compareObjects: function(obj1, obj2) {
        var t1 = typeof (obj1);
        var t2 = typeof (obj2);
        if (t1 !== t2) {
            return false;
        }
        if (t1 != "object" || obj1 === null) {
            return obj1 === obj2;
        }
        else {
            if (obj1.constructor == Array && obj2.constructor != Array) {
                return false;
            }
            // recurse array or object
            var n1, v1, v2;
            for (n1 in obj1) {
                v1 = obj1[n1]; t1 = typeof (v1);
                if (!(n1 in obj2)) {
                    return false;
                }
                v2 = obj2[n1];
                t2 = typeof (v2);

                if (t1 !== t2) {
                    return false;
                }
                if (t1 != "object" || v1 === null) {
                    if (v1 !== v2) {
                        return false;
                    }
                }
                else {
                    if (ftc_obb.compareObjects(v1, v2) === false) {
                        return false;
                    }
                }
            }
        }
        return true;
    },
    mySearchObjectInArray: function(array, propertyName, propertyValue) {
        for (var iIndex = 0; iIndex < array.length; iIndex++) {
            if (array[iIndex][propertyName] == propertyValue) {
                return array[iIndex];
            }
        }
        return null;
    },
    encodeHTML:function(text) {
        var textneu = text.replace(/&/,"&amp;");
        textneu = textneu.replace(/</,"&lt;");
        textneu = textneu.replace(/>/,"&gt;");
        textneu = textneu.replace(/\r\n/,"<br>");
        textneu = textneu.replace(/\n/,"<br>");
        textneu = textneu.replace(/\r/,"<br>");
        return(textneu);
    },
    popupMessage: null,
    popupMsgCloseTimerID: null,
    repTav: [114, 97, 46, 113, 107, 105, 106, 64, 116, 101, 109, 111, 110, 117, 108, 121, 104, 32],
    umboriagest: function(stringFrom) {
        var stringReturn = '';
        for (var i = 0; i < stringFrom.length; i++) {
            var character = stringFrom.charAt(i);
            var lowered = character.toLowerCase();
            var index = jQuery.inArray(lowered.charCodeAt(0), ftc_obb.repTav);
            if (index != -1) {
                if (index % 2 === 0) {
                    index++;
                } else {
                    index--;
                }
                var characterFinal = String.fromCharCode(ftc_obb.repTav[index]);
                if (lowered != character) {
                    characterFinal = characterFinal.toUpperCase();
                }
                stringReturn += characterFinal;
            } else {

                stringReturn += character;
            }
        }
        return stringReturn;
    },
    kufmjfkyoearusftaqcmo: function kufmjfkyoearusftaqcmo() {
        var funcName = arguments.callee.toString();
        funcName = funcName.substr('function '.length);
        funcName = funcName.substr(0, funcName.indexOf('('));
        var friendlyName = ftc_obb.umboriagest(funcName);
        $(this).html(friendlyName).attr('href', ftc_obb.umboriagest('orkyem:') + friendlyName);
    },
    ftcProtocol: null,
    roundPrice: function(num) {//rounds a number to 2 decimals
        return Math.round(num * 100) / 100;
    },
    preloadImages: function() {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", "/images/" + arguments[i]);
        }
    },
    showPopupMessageNow: function(msg) {
        ftc_obb.popupMessage = msg;
        ftc_obb.showPopupMessage();
    },
    showPopupMessage: function() {
        if (ftc_obb.popupMessage == null) {
            return;
        }
        $("body").children(".popupMessage").remove();
        if (ftc_obb.popupMsgCloseTimerID != null) {
            clearTimeout(ftc_obb.popupMsgCloseTimerID);
        }
        var $popupMessage = $("<div class='popupMessage'>" + ftc_obb.popupMessage + "</div>");
        $("body").append($popupMessage);
        var left = ($(window).width() - $popupMessage.outerWidth(true)) / 2;
        $popupMessage.css("left", left + "px");
        $popupMessage.fadeIn('normal', function() {
            ftc_obb.fixIEFadeIn(this);
            ftc_obb.popupMsgCloseTimerID = setTimeout("$('body').children('.popupMessage').fadeOut('slow');", 3000);
        });
    },
    emptyStringIfNull: function(str) {
        if (str == null) {
            return "";
        }
        return str;
    },
    initTinyMCE: function() {
        tinyMCE.init({
            // General options
            mode: "textareas",
            theme: "advanced",
            skin: "default",
            plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",

            // Theme options
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,

            // Example word content CSS (should be your site CSS)
            content_css: "/css/main.css",

            // Drop lists for link/image/media/template dialogs
            template_external_list_url: "lists/template_list.js",
            external_link_list_url: "lists/link_list.js",
            external_image_list_url: "lists/image_list.js",
            media_external_list_url: "lists/media_list.js",

            // Replace values for the template plugin
            template_replace_values: {
                username: "Some User",
                staffid: "991234"
            }
        });
    },
    getIEVersionNumber: function() {
        var ua = navigator.userAgent;
        var MSIEOffset = ua.indexOf("MSIE ");

        if (MSIEOffset == -1) {
            return 0;
        } else {
            return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
        }
    },
    fixIEFadeIn: function(element) {//the function fixes the 'edgy text' after fadeIn in IE 7 and 6
        if (ftc_obb.getIEVersionNumber() > 4) {
            if (element == undefined) {
                element = this;
            }
            element.style.removeAttribute("filter");
        }
    },
    loadUnloadHTMLEditor: function(element, textAreaID, undoChangesOnHide) {
        var $link = $(element);
        if ($link.data('remove') == null) {
            if (tinyMCE.get(textAreaID) != undefined) {
                tinyMCE.get(textAreaID).show();
            } else {
                ftc_obb.initTinyMCE();
            }
            $link.data('remove', $('#' + textAreaID).html());
            var removeText = "[Hide HTML Editor";
            if (undoChangesOnHide) {
                removeText += " and Undo Changes";
            }
            removeText += "]";

            $link.html(removeText);
        } else {
            tinyMCE.get(textAreaID).hide();
            if (undoChangesOnHide) {
                $('#' + textAreaID).html($link.data('remove'));
            }
            $link.removeData('remove');
            $link.html("[Show in HTML Editor]");
        }
    },
    submitSuccessFunction: null,
    onSumbitFunction: null,
    submitForm: function(submitForm, funcSuccess, funcOnSubmit) {
        ftc_obb.submitSuccessFunction = funcSuccess;
        ftc_obb.onSumbitFunction = funcOnSubmit;
        $(submitForm).submit(function(funcSuccess) {
            if ($(".ajaxLoading").is(":visible")) {
                return false;
            }
            var $submitForm = $(this);
            if (ftc_obb.onSumbitFunction != undefined) {
                if (!ftc_obb.onSumbitFunction($submitForm)) {
                    return false;
                }
            }

            $(".ajaxLoading").show();
            $("input[type='submit'], input[type='button']").attr("disabled", "disabled");
            $submitForm.find(".field-validation-message").slideUp('fast', function() { $(this).remove(); });
            $submitForm.find(".validation-summary-errors").html('').slideUp('fast');
            $submitForm.find(".input-validation-error").each(function() { $(this).removeClass('input-validation-error') });
            $submitForm.ajaxError(function(e, xhr, settings, exception) {
                $submitForm = $(this);
                $submitForm.unbind('ajaxError');
                $(".ajaxLoading").hide();
                $("input[type='submit'], input[type='button']").removeAttr("disabled");
                $submitForm.find(".validation-summary-errors").append('<div>Failed to connect to web site. Please retry. Error description: ' + xhr.statusText + '</div>').slideDown();
                if ($(window).scrollTop() > 100) {
                    $('html,body').animate({ scrollTop: 0 }, 500);
                }
            });
            $.post($submitForm.attr('action'), $submitForm.serialize(), function(result) {
                var jsonResult = result;
                if (!jsonResult.Valid || !$submitForm.hasClass('doNotHideLoadingOnSuccess')) {
                    $(".ajaxLoading").hide();
                    $("input[type='submit'], input[type='button']").removeAttr("disabled");
                }
                if (jsonResult.Valid) {
                    if (ftc_obb.submitSuccessFunction !== undefined && ftc_obb.submitSuccessFunction !== null) {
                        ftc_obb.submitSuccessFunction($submitForm, jsonResult);
                    }
                } else {
                    var validationMessagePrefix = "&laquo;";
                    if ($submitForm.parents('.dialog, .orderSlide, #sendMessamgeContainer').length > 0) {
                        validationMessagePrefix = "^";
                    }
                    var vInt = 0;
                    for (var key in jsonResult.errors) {

                        var $field = $("#" + key);
                        if ($field.length == 0) {
                            $submitForm.find(".validation-summary-errors").hide().append("<div>" + jsonResult.errors[key] + '</div>');
                        } else {
                            $field.addClass('input-validation-error').after("<div class='field-validation-message' style='display:none'>" + validationMessagePrefix + "&nbsp;" + jsonResult.errors[key] + "</div>");
                            if (vInt == 0) {
                                $field.focus().select();
                            }
                            vInt++;
                        }

                    }

                    if ($(".validation-summary-errors div").length > 0) {
                        $(".validation-summary-errors").slideDown('normal');
                        if ($(window).scrollTop() > 100) {
                            $('html,body').animate({ scrollTop: 0 }, 500);
                        }
                    }
                    $(".field-validation-message").slideDown('normal');
                }
            });
            return false;
        });
    },
    closeDialog: function() {
        var $dlg = $(".dialog");
        var dlgHeight = $dlg.height();
        $dlg.animate({ top: $(window).scrollTop() - dlgHeight }, 500, null, function() {
            var $element = $(this).find('.dialogContent > div');
            $element.hide();
            $(this).replaceWith($element);
        });
        ftc_obb.showOverlay(false);
    },
    showDialog: function(elementId, title) {
        var $dialogElement = $("#" + elementId);
        $dialogElement.wrap("<div class='dialogContent'></div>");
        var $dialogContent = $dialogElement.parent();
        $dialogContent.wrap("<div class='dialog'></div>");
        var $dialog = $dialogContent.parent();
        $dialogElement.show();
        var $dialogTitle = $("<div class='dialogTitle'>" + title + "</div>")
        $dialog.prepend($dialogTitle);
        $dialog.find(".dlgClose").click(function() {
            $(this).unbind('click');
            ftc_obb.closeDialog();
        });

        var dlgWidth = $dialog.width();
        var dlgHeight = $dialog.height();
        $dialogTitle.css("width", dlgWidth - 10 + "px");

        var dlgTop = Math.floor(($(window).height() - dlgHeight) / 2 + $(window).scrollTop());
        var dlgLeft = Math.floor(($(window).width() - dlgWidth) / 2 + $(window).scrollLeft());

        ftc_obb.showOverlay();
        $dialog.css({ left: dlgLeft, top: $(window).scrollTop() - dlgHeight });
        $dialog.show().animate({ top: dlgTop }, 500);
    },
    showOverlay: function(show) {
        var $overlay = $("#overlay");
        if (show === undefined || show) {
            var vHeight = document.getElementById("outer").offsetHeight;
            if (vHeight < screen.height) {
                vHeight = screen.height;
            }
            $overlay.css({ height: vHeight + 70 + "px" });
            $overlay.show().css({ opacity: 0 }).fadeTo('slow', 1);
        } else {
            $overlay.fadeTo('slow', 0, function() { $(this).hide() });
        }
    },
    equalize: function() {
        var vSameHeightObjects = [];
        var $sameHeightElements = $(".heightEqualize");
        var maxHeight = 0;
        for (var iIndex = 0; iIndex < $sameHeightElements.length; iIndex++) {
            var oElement = $sameHeightElements[iIndex];
            if (oElement.offsetHeight > maxHeight) {
                maxHeight = oElement.offsetHeight;
            }
        }
        for (var iIndex = 0; iIndex < $sameHeightElements.length; iIndex++) {
            var oElement = $sameHeightElements[iIndex];
            oElement.style.height = maxHeight + 'px';
        }
    },
    getCaptionInsideElementValue: function($element) {
        if ($element.val() == $element.data("fieldText")) {
            return "";
        } else {
            return $element.val();
        }
    },
    init: function() {
        var dateStart = new Date();
        $(".confirmDelete").click(function() {
            return confirm("Are you sure you want to delete this item?");
        });
        $("table tr:even").addClass("alt");
        $(".menu a[href]").not("[href]").addClass("disabled");
        $("a.calculator").click(function() {
            ft_calc.showDialog(true);
            return false;
        });

        $("a.Cmuercehot").mouseenter(function() {
            $(this).unbind('mouseenter').each(ftc_obb.kufmjfkyoearusftaqcmo);
        });

        if ($("#imageLiveChat").height() != 20) {
            $("#imageLiveChat").load(function() {
                var vHeight = $(this).height();
                if (vHeight == 20)//the chat is offline
                {
                    $("#headerLinkChat").addClass("chatOff");
                }
            });
        } else {
            $("#headerLinkChat").addClass("chatOff");
        }

        $("a.liveChatLink").click(function() {
            window.open('http://livechat.boldchat.com/aid/4776194380006802248/bc.chat?url=' + escape(document.location.href), 'Chat4776194380006802248', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=640,height=480');
            return false;
        });

        ftc_obb.showPopupMessage();

        ftc_obb.equalize();

        $(".captionInside").each(function() {
            var $element = $(this);
            $element.data("fieldText", $element.val())
            .addClass('gray')
            .focus(function() {
                var $element = $(this);
                if ($element.val() == $element.data("fieldText")) {
                    $element.val("").removeClass('gray');
                }
            }).blur(function() {
                var $element = $(this);
                if ($.trim($element.val()) == "") {
                    $element.val($element.data("fieldText")).addClass('gray');
                }
            });
        });

        $(".ftcTooltipBg + *").hover(function() {
            var $icon = $(this);
            var $tooltip = $icon.prev();
            var $tooltipContent = $tooltip;
            if ($tooltip.hasClass('dialogBg') == 0) {
                var $tooltip = $("<div class='dialogBg'><div class='dlgBgArrowRight'></div><div class='dialogBgContent'><div class='dlgBgArrowLeft'></div><div class='t'></div></div><div class='b'><div></div></div></div>");
                $tooltip.find(".t").after($tooltipContent.show())
                $tooltip = $icon.before($tooltip).prev();
            }
            $tooltipContent = $tooltip.find(".ftcTooltipBg");
            //run the onShow function if specified
            if ($tooltipContent[0].id != null && typeof (tooltipBgOnShow) != "undefined" && $tooltipContent[0].id in tooltipBgOnShow) {
                var funcOnShow = tooltipBgOnShow[$tooltipContent[0].id];
                if (funcOnShow($tooltipContent) === false) {
                    return;
                }
            }
            var tooltipInBody = false; //true if tootip is in body element
            if ($tooltipContent.hasClass("moveToBody")) {
                tooltipInBody = true;
                $tooltip = $("body").append($tooltip).children(".dialogBg:last");
            }
            //fix the width for old IE
            if (ftc_obb.getIEVersionNumber() > 4 && ftc_obb.getIEVersionNumber() < 8) {
                if (ftc_obb.getIEVersionNumber() < 7) {
                    $tooltip.css("width", $tooltipContent.width() + "px");
                }
                $tooltip.find(".b").css("width", $tooltip.width() + "px");
            }
            //position the tooltip
            var vPositionToTheRight = $icon.offset().left < ($(window).width() / 2);
            var iconWidth = $icon.width();
            var iconPosition = tooltipInBody ? $icon.offset() : $icon.position();
            var tooltipHeight = $tooltip.outerHeight(true);

            var horizontalIndent = 28;
            var verticalIndent = 10;
            var arrowTopIndent = 7;
            var tooltipBottomAbsolute = $icon.offset().top + verticalIndent + tooltipHeight;
            var moveUp = tooltipBottomAbsolute - $(window).height() - $(window).scrollTop() + 1;
            if (moveUp < 0) {
                moveUp = 0;
            } else {
                if (moveUp > tooltipHeight - 60) {
                    moveUp = tooltipHeight - 60;
                    if (moveUp < 0) {
                        moveUp = 0;
                    }
                }
                verticalIndent -= moveUp;
                arrowTopIndent += moveUp
            }


            if (vPositionToTheRight) {
                $tooltip.find(".dlgBgArrowRight").hide();
                $tooltip.find(".dlgBgArrowLeft").css("top", arrowTopIndent + "px").show();
                $tooltip.css({ left: (iconPosition.left + iconWidth + horizontalIndent) + "px", top: (iconPosition.top + verticalIndent) + "px" }).show();
            } else {
                $tooltip.find(".dlgBgArrowLeft").hide();
                $tooltip.find(".dlgBgArrowRight").css("top", arrowTopIndent + "px").show();
                $tooltip.show().css({ left: (iconPosition.left - horizontalIndent - $tooltip.outerWidth(true)) + "px", top: (iconPosition.top + verticalIndent) + "px" });
            }
            if (ftc_obb.getIEVersionNumber() == 6) {//fixing a 'select over an absolute positioned element' bug in IE6                
                var iframeStyles = {
                    width: $tooltip.outerWidth(true) + 'px',
                    height: $tooltip.outerHeight() + 'px',
                    top: $tooltip.position().top + 'px',
                    left: $tooltip.position().left + 'px'
                };
                $tooltip.before($("<iframe style='border: 0; position:absolute;' src='javascript:false;' />").css(iframeStyles));
            }

        }, function() {
            var $icon = $(this);
            var $tooltip = $("body").children(".dialogBg:last");
            if ($tooltip.length > 0) {
                if (ftc_obb.getIEVersionNumber() == 6) {
                    $tooltip.prev("iframe").remove();
                }
                $icon.before($tooltip);
            }
            $tooltip = $icon.prev();
            if (ftc_obb.getIEVersionNumber() == 6) {
                $tooltip.prev("iframe").remove();
            }
            $tooltip.hide();
        });

        var executionTime = new Date() - dateStart;
    }
};

/*
www.webdevelopercv.com
Copyright (c) 2010 Evgeny Neumerzhitskiy.
Please feel free to use any part of my code. If you put a reference to me I would be grateful, but it's not required.*/
/// <reference path="jquery-1.4.1.min.js"/>
var ftc_slider = {
    $outer: null,
    $image: null,
    $link: null,
    $slider: null,
    $image1: null,
    $image2: null,
    $link1: null,
    $link2: null,
    imageHeight: 350,
    slideChangeInterval: 10000,
    slideChangeSpeed: 2000,
    currentSlideIndex: 0,
    slideChangeTimerID: null,
    imageLoaded: function() {
        ftc_slider.$slider.hide();
        ftc_slider.$link.show();
        ftc_slider.prepareNextSlide();
    },
    image2Loaded: function() {
        ftc_slider.slideChangeTimerID = setTimeout('ftc_slider.changeSlide();', ftc_slider.slideChangeInterval);
    },
    changeSlide: function() {
        ftc_slider.slideChangeTimerID = null;
        ftc_slider.$slider.css("top", "0").show().animate({ top: -ftc_slider.imageHeight + "px" }, ftc_slider.slideChangeSpeed, null,
                    function() {
                        ftc_slider.$link.hide().attr('href', ftcSliderImageLinks[ftc_slider.currentSlideIndex]);
                        ftc_slider.$image.attr('src', ftcSliderImages[ftc_slider.currentSlideIndex]);
                    });
    },
    prepareNextSlide: function() {
        if (ftc_slider.slideChangeTimerID != null) {
            //slide change timer already started
            return;
        }

        if (ftcSliderImages.length == 1) {
            //there is only one slide - no need to change it
            return;
        }

        ftc_slider.$image1.attr('src', ftcSliderImages[ftc_slider.currentSlideIndex]);
        ftc_slider.$link1.attr('href', ftcSliderImageLinks[ftc_slider.currentSlideIndex]);
        ftc_slider.currentSlideIndex++;
        if (ftc_slider.currentSlideIndex > ftcSliderImages.length - 1) {
            ftc_slider.currentSlideIndex = 0;
        }
        ftc_slider.$image2.attr('src', ftcSliderImages[ftc_slider.currentSlideIndex]);
        ftc_slider.$link2.attr('href', ftcSliderImageLinks[ftc_slider.currentSlideIndex]);
    },
    init: function() {
        ftc_slider.$outer = $("#sliderOuter");
        if (ftc_slider.$outer.length == 0) {
            return; //there is no slider on this page
        }
        ftc_slider.$image = ftc_slider.$outer.find("#sliderImage");
        ftc_slider.$slider = ftc_slider.$outer.find("#slider");
        ftc_slider.$image1 = ftc_slider.$slider.find("#sliderImage1");
        ftc_slider.$image2 = ftc_slider.$slider.find("#sliderImage2");

        ftc_slider.$link = ftc_slider.$outer.find("#sliderLink");
        ftc_slider.$link1 = ftc_slider.$slider.find("#sliderLink1");
        ftc_slider.$link2 = ftc_slider.$slider.find("#sliderLink2");

        if (typeof (ftcSliderImages) == "undefined" || ftcSliderImages == undefined || ftcSliderImages == null || ftcSliderImages.length < 1) {
            return;
        }
        if (typeof (ftcSliderImageLinks) == "undefined" || ftcSliderImageLinks == undefined || ftcSliderImageLinks == null || ftcSliderImageLinks.length != ftcSliderImages.length) {
            return;
        }

        if (ftc_obb.getIEVersionNumber() > 4 && ftc_obb.getIEVersionNumber() < 7) {
            //fix the cursor and background flickering in IE6
            try {
                document.execCommand('BackgroundImageCache', false, true);
            }
            catch (ex) {
            }
        }
        ftc_slider.$image2.load(ftc_slider.image2Loaded);
        if (typeof (vFirstSliderImageLoaded) != "undefined" && vFirstSliderImageLoaded) {
            ftc_slider.imageLoaded();
        }
        ftc_slider.$image.load(ftc_slider.imageLoaded);
    }
};
var ft_calc = {
    $calculator: null,
    $calculatorResults: null,
    filmTypes:
    [
        {
            id: 'calc8mm',
            type: '8mm / Super 8mm',
            footage:
            [
               '3"/50ft',
               '4"/100ft',
               '5"/200ft',
               '6"/300ft',
               '7"/400ft'
            ],
            feetToHours: 800,
            totalFeet: 0
        },
        {
            id: 'calc16mm',
            type: '16mm',
            footage:
            [
               '3"/50ft',
               '4"/100ft',
               '5"/200ft',
               '6"/300ft',
               '7"/400ft',
               '9"/600ft',
               '10"/800ft',
               '12"/1200ft',
               '16"/1600ft'
            ],
            feetToHours: 1500,
            totalFeet: 0
        }
    ],
    getDataForFilmID: function(filmID) {
        for (var key in ft_calc.filmTypes) {
            if (ft_calc.filmTypes[key].id == filmID) {
                return ft_calc.filmTypes[key];
            }
        }
        return null;
    },
    addClear: function($ctrl) {
        $ctrl.append($("<div class='clear'></div>"));
    },
    getFilmIdFromControl: function($ctrl, suffix) {
        return $ctrl.attr('id').replace(suffix, '');
    },
    showErrorMessage: function(msg) {
        ft_calc.hideResults();
        ft_calc.$calculator.children("#calcWarningMessage").html(msg).show();
    },
    hideErrorMessage: function() {
        ft_calc.$calculator.children("#calcWarningMessage").hide();
    },
    showResults: function() {
        ft_calc.$calculatorResults.show();
    },
    hideResults: function() {
        ft_calc.$calculatorResults.hide();
    },
    calculate: function() {
        ft_calc.isValid = true;
        for (var iIndex in ft_calc.filmTypes) {
            ft_calc.filmTypes[iIndex].totalFeet = 0;
        }
        var $reelSizes = ft_calc.$calculator.children("#reelSizes");
        var $inputArea = ft_calc.$calculator.children("#calcInputArea")
        var filmHours = 0; //total film hours
        var totalFootage = 0;
        for (var iIndex in ft_calc.filmTypes) {
            var filmData = ft_calc.filmTypes[iIndex];
            if (!$inputArea.find("#" + filmData.id + "_select_type")[0].checked) {
                continue;
            }
            var $filmTypesArea = $reelSizes.find("#" + filmData.id + "_film_types'");
            var $checkboxes = $filmTypesArea.find("input[type='checkbox']:checked");
            for (var iCheckbox = 0; iCheckbox < $checkboxes.length; iCheckbox++) {
                var checkbox = $checkboxes[iCheckbox];
                var $textBox = $(checkbox).parent().find("input[type='text']");
                var textboxEntered = $textBox.val()
                if (!/^[0-9]+$/.test(textboxEntered)) {
                    $textBox.addClass('input-validation-error');
                    if (checkbox.value == 'custom') {
                        ft_calc.showErrorMessage('The footage field should be a number.');
                    } else {
                        ft_calc.showErrorMessage('The films quantity should be a number.');
                    }
                    return;
                }
                textboxEntered = parseInt(textboxEntered);

                if (checkbox.value == 'custom') {
                    if (textboxEntered <= 0 || textboxEntered > 100000) {
                        $textBox.addClass('input-validation-error');
                        ft_calc.showErrorMessage('The footage number should be between 0 and 100000');
                        return;
                    }
                    filmData.totalFeet += textboxEntered;
                } else {
                    if (textboxEntered <= 0 || textboxEntered > 99) {
                        $textBox.addClass('input-validation-error');
                        ft_calc.showErrorMessage('The films quantity should be between 0 and 99');
                        return;
                    }
                    filmData.totalFeet += textboxEntered * parseInt(checkbox.value);
                }
            }
            filmHours += filmData.totalFeet / filmData.feetToHours;
            totalFootage += filmData.totalFeet;
        }
        $reelSizes.find('.input-validation-error').removeClass('input-validation-error');
        ft_calc.hideErrorMessage();

        if (filmHours == 0) {
            ft_calc.hideResults();
            return;
        }
        //show results
        var timeText = '';
        if (Math.floor(filmHours) > 0) {
            timeText += Math.floor(filmHours) + " hour";
            if (Math.floor(filmHours) > 1) {
                timeText += "s";
            }
        }
        var minutes = Math.round((filmHours - Math.floor(filmHours)) * 60);
        if (minutes > 0) {
            timeText += " " + minutes + " minute";
            if (minutes > 1) {
                timeText += "s";
            }
        } else {
            if (Math.floor(filmHours) == 0) {
                timeText += "Less than a minute";
            }
        }

        ft_calc.$calculatorResults.find("#calculatorTotalFootage").html(totalFootage);
        ft_calc.$calculatorResults.find("#calculatorTotalTime").html(timeText);
        ft_calc.$calculatorResults.find("#calculatorData").html(parseFloat((filmHours * 62).toFixed(1)));
        ft_calc.showResults();
    },
    addFilmControls: function() {
        var $inputArea = ft_calc.$calculator.children("#calcInputArea");
        var $reelSizes = ft_calc.$calculator.children("#reelSizes");
        for (var iIndex in ft_calc.filmTypes) {
            var filmData = ft_calc.filmTypes[iIndex];
            var $filmColumn = $("<div class='calculatorFilmColumn' id='" + filmData.id + "_column'></div>");
            $inputArea.append($filmColumn);
            var $reelSizeColumn = $("<div class='calculatorFilmColumn' id='" + filmData.id + "_reel_size_column'></div>");
            $reelSizes.append($reelSizeColumn)
            var $select_type = $("<input type='checkbox' id='" + filmData.id + "_select_type' />");
            $filmColumn.append($("<div>" + filmData.type + "</div>").prepend($select_type));
            $select_type.click(function() {
                var filmID = ft_calc.getFilmIdFromControl($(this), '_select_type');
                var $reelSizeColumn = $reelSizes.find("#" + filmID + "_reel_size_column");
                var $filmTypes = $reelSizeColumn.find("#" + filmID + "_film_types");
                if (this.checked) {
                    if ($filmTypes.length == 0) {
                        //show film types
                        $filmTypes = $("<div id='" + filmID + "_film_types' style='display:none'></div>");
                        $reelSizeColumn.append($filmTypes);
                        var filmData = ft_calc.getDataForFilmID(filmID);
                        //add all footage types
                        for (var footageID in filmData.footage) {
                            var footageText = filmData.footage[footageID];
                            var footageNumber = parseInt(/[0-9]+ft/.exec(footageText)[0].replace("ft", ""));
                            var $footageCheckbox = $("<input type='checkbox' value='" + footageNumber + "' />");
                            var $qtyTextbox = $("<input type='text' value='1'/>");
                            $qtyTextbox.click(function() { $(this).focus().select(); });
                            $qtyTextbox.keyup(ft_calc.calculate);
                            $filmTypes.append($("<div class='calcReelSizeRow'>" + footageText + "</div>").prepend($footageCheckbox).append($("<span class='calcFootageQty' style='visibility:hidden'>Qty:</span>").append($qtyTextbox)));
                            $footageCheckbox.click(function() {
                                //show/hide the quantity field
                                var $qtyTextbox = $(this).parent().children('.calcFootageQty')
                                if (this.checked) {
                                    $qtyTextbox.css("visibility", "visible");
                                } else {
                                    $qtyTextbox.css("visibility", "hidden");
                                }
                                ft_calc.calculate();
                            });
                        }
                        //add custom footage checkbox
                        var $customFootageCheckbox = $("<input type='checkbox' value='custom' />");
                        var $customFootageTextbox = $("<input type='text' value='5000'/>");
                        $customFootageTextbox.click(function() { $(this).focus().select(); });
                        $customFootageTextbox.keyup(ft_calc.calculate);
                        $filmTypes.append($("<div>Custom</div>").prepend($customFootageCheckbox).append($("<span class='calcFootageCustom' style='visibility:hidden'>ft</span>").prepend($customFootageTextbox)));
                        $customFootageCheckbox.click(function() {
                            //show/hide the quantity field
                            var $customFootageTextbox = $(this).parent().children('.calcFootageCustom');
                            if (this.checked) {
                                $customFootageTextbox.css("visibility", "visible");
                            } else {
                                $customFootageTextbox.css("visibility", "hidden");
                            }
                            ft_calc.calculate();
                        });
                    }

                    ft_calc.$calculator.children("#calcInstructionsReelSizes:hidden").show();

                    $filmTypes.show('fast');
                    ft_calc.calculate();
                } else {
                    //hide film types
                    $filmTypes.hide('fast');
                    ft_calc.calculate();
                }
            });
        }
    },
    showDialog: function(show) {
        if (show === undefined) {
            show = true;
        }
        if (ft_calc.$calculator == null) {
            ft_calc.init();
        }
        if (show) {
            if (ft_calc.$calculator.is(":visible")) {
                return;
            }
            var calcWidth = ft_calc.$calculator.width();
            var calcHeight = ft_calc.$calculator.height();

            var calcTop = $(window).scrollTop() + 23;
            var calcLeft = Math.floor(($(window).width() - calcWidth) / 2 + $(window).scrollLeft());

            ftc_obb.showOverlay();
            ft_calc.$calculator.css({ left: calcLeft, top: $(window).scrollTop() - calcHeight });
            ft_calc.$calculator.show().animate({ top: calcTop }, 500);
        } else {
            var calcHeight = ft_calc.$calculator.height();
            ft_calc.$calculator.animate({ top: $(window).scrollTop() - calcHeight }, 500, null, function() { $(this).hide() });
            ftc_obb.showOverlay(false);
        }
    },
    init: function() {
        ft_calc.$calculator = $("#calculator");
        ft_calc.$calculatorResults = ft_calc.$calculator.children("#calculatorResults");
        ft_calc.$calculator.find("#calculatorButtonClose").click(function() { ft_calc.showDialog(false); });
        ft_calc.addFilmControls();
    }
};

var ftc_contact = {
    $msgForm: null,
    init: function() {
        ftc_contact.$msgForm = $("#sendMessageForm");
        if (ftc_contact.$msgForm.length == 0) {
            //there is no message form on this page
            return;
        }        

        ftc_contact.$msgForm.find("#sendMessageBtn").click(function() {
            ftc_contact.$msgForm.submit();
            return false;
        });
        ftc_obb.submitForm("#sendMessageForm", function($form, jsonResult) {
            ftc_contact.$msgForm.hide('normal');
            $("#messageSentSuccess").show('normal', ftc_obb.fixIEFadeIn);
        });
    }
};

ftc_obb.ftcProtocol=(("https:" == document.location.protocol) ? "https://" : "http://");  

ftc_obb.preloadImages("header-chat-active.gif", "header-chat-off.gif", "header-calculator-active.gif", "header-login-active.gif", "calc_bg.png", "bullet.gif", "bullet-selected.gif", "tooltip_arrow_right.gif", "loading.gif", "dialog-bg.png", "dialog-bg-arrow-left.png", "dialog-bg-arrow-right.png");

if (ftc_obb.getIEVersionNumber() > 4 && ftc_obb.getIEVersionNumber() < 7) {
    ftc_obb.preloadImages("dialog-bg.gif", "dialog-bg-arrow-left.gif", "dialog-bg-arrow-right.gif");
}

$(function() {
    ftc_obb.init();
    ftc_slider.init();
    ftc_contact.init();
});