﻿/*================================
Common functions
==================================*/
var blank = new Image();

$J(document).ready(function () {
    jQuery.fn.exists = function () { return jQuery(this).length > 0; }
    printButtons();
    //videoThumb();
    scriptedContentStyles();
    runPngFix();
    initAccordion();
    initImgCaption();
    initHeaderSlideshow();
    initSimilarProjectsSlideshow();
    initFontResize();
    initMainNavClass();
    hideInputFieldValues();
    initSlideDown();
    if (!$J('#wrapper').hasClass("investorPageFiveTabs")) {
        tabbedMenuWidth();
    }
    initProjectSlideDown();
    if ($J('.leftNavigation').exists()) {
        firstAndLastClass('.leftNavigation');
    }
    initSearchSlide();
    initCheckboxSelect("regionFilter");
    initCheckboxSelect("capabilityFilter");
    initCheckboxSelect("sectorFilter");
    initCheckboxSelect("completionFilter");
    initCheckboxSelect("rateFilter");
    initRemoveTopBorder();
    initRemoveInputValue();
    initTabChange();
    initSubFeatureSlideDown();
    initSplashClass();

    initIframeContent();

});


/*=========================================
Print Buttons
=========================================*/
function printButtons() {
    $J('.btnPrint').click(function () {
        window.print();
        $J(this).blur();
        return false;
    });
}

/*=========================================
Video Thumbnail
=========================================*/
function videoThumb() {
    $J('.videoThumb').hover(function () {
        $J(this).addClass('hover').find('.btnPlay').stop().show();
    });
    $J('.videoThumb').mouseleave(function () {
        $J(this).removeClass('hover').find('.btnPlay').stop().hide();
    });

}

/*=========================================
Scripted WYSIWYG CSS Styles
=========================================*/
function scriptedContentStyles() {


}


/*=========================================
PNG Fix		
=========================================*/
blank.src = '/Layouts/Property/Lend Lease Website/Assets/Images/blank.gif';

function runPngFix() {
    var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");

    //Find if ie6 and check all images for png's
    if (badBrowser) {
        $J('img.pngFix, .pngFix img, .largeCommIcon img, img[src$=.png]').each(function () {
            if (!this.complete) this.onload = function () { fixPng(this) };
            else fixPng(this);
        });
    }
}


function fixPng(png) {
    var src = png.src;

    //No manual height and width set
    if (!png.style.width && $J(png).css('width') == 'auto') png.style.width = $J(png)[0].offsetWidth + "px";
    if (!png.style.height && $J(png).css('height') == 'auto') png.style.height = $J(png)[0].offsetHeight + "px";

    // replace by blank image
    png.onload = function () { };
    png.src = blank.src;
    png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}



/*=========================================
Common positioning functions 			
=========================================*/
function getAbsoluteLeft(focusObject) {
    // Get an object left position from the upper left viewport corner
    o = $J(focusObject)[0];
    oLeft = o.offsetLeft;
    while (o.offsetParent != null) {
        oParent = o.offsetParent;
        oLeft += oParent.offsetLeft;
        o = oParent;
    }
    return oLeft;
}

function getAbsoluteTop(focusObject) {
    // Get an object top position from the upper left viewport corner
    o = $J(focusObject)[0];
    oTop = o.offsetTop;
    while (o.offsetParent != null) {
        oParent = o.offsetParent;
        oTop += oParent.offsetTop;
        o = oParent;
    }
    return oTop;
}

function getBounds(focusObject) {

    var obj;
    obj.top = getAbsoluteTop(focusObject);
    obj.left = getAbsoluteLeft(focusObject);

    o = $J(focusObject)[0];
    obj.right = obj.left + o.offsetWidth;
    obj.bottom = obj.top + o.offsetHeight;

    return obj;
}


/*=========================================
Background image cache			
=========================================*/
try { document.execCommand("BackgroundImageCache", false, true); } catch (e) { }

/*================================
Accordion functions
==================================*/
var startupAccordItem = false;

function initAccordion() {
    $J(".accordion .item h3 a").each(function () {
        var divContainer = $J(this).parent().parent();
        var divContent = $J(this).parent().parent().find("div.contentContainer");
        $J(this).click(function () {
            $J(divContainer).toggleClass("itemOn");
            $J(divContent).slideToggle("fast");
        });
    })
}

/*================================
Fast facts functions
==================================*/
function initSlideDown() {
    $J(".fastFacts").each(function () {
        var divContainer = $J(this);
        var divContent = $J(this).find("div.slideContent");
        var str = $J(this).find("div.slideContent p").text();
        var pContent = $J.trim(str);
        //alert(pContent);
        if (pContent != 0) {
            $J(this).hover(function () {
                $J(divContainer).toggleClass("itemOn");
                $J(divContent).slideToggle("fast");
            }, function () {
                $J(this).find("div.slideContent").hide(500, function () {
                    $J(this).hide();
                });
            });
        }
    })
}

/*================================
Projects landing functions
==================================*/
function initProjectSlideDown() {
    $J(".projectsOverviewItems .projectsHeader").each(function () {
        var divContainer = $J(this);
        var divContent = $J(this).find("div.slideContent");
        $J(this).hover(function () {
            $J(divContainer).toggleClass("itemOn");
            $J(divContent).slideToggle("fast");
        }, function () {
            $J(this).find("div.slideContent").hide(500, function () {
                $J(this).hide();
                $J(divContainer).toggleClass("itemOn");
            });
        });
    })
}


/*================================
img caption functions
==================================*/
function initImgCaption() {
	$J(".columnContent img").each(function(){
    var attr = $J(this).attr('title');
	//alert(typeof attr);
    if (typeof attr != 'undefined') {
        // ...
        $J(this).jcaption({
            //Element to wrap the image and caption in
            wrapperElement: 'div',

            //Class for wrapper element
            wrapperClass: 'caption',

            //Caption Element
            captionElement: 'div',

            //Attribute of image to use as caption source
            imageAttr: 'title',

            //If true, it checks to make sure there is caption copy before running on each image
            requireText: true,

            //Assign the value of the image's align attribute as a class to the wrapper
            copyAlignmentToClass: true,

            //Assign the value of the image's float value as a class to the wrapper
            copyFloatToClass: true,

            //Assign a width to the wrapper that matches the image
            autoWidth: false
        });
    }

	})
}

/*==================================
services slideshow header
==================================*/
function initHeaderSlideshow() {
    //alert($J(".mainContentHeader .headerSlideShow").html());
    if ($J(".mainContentHeader .headerSlideShow").html() == "") {
        $J(".mainContentHeader .headerSlideShow").remove();
    }

    $J(".mainContentHeader .headerSlideShow").cycle({
        timeout: 5000,
        pager: ".navigationItems",
        pagerAnchorBuilder: function (index, el) {
            return '<div><a href="#"></a></div>'; // whatever markup you want
        }
    });


    if ($J('.mainContentHeader .navigationItems div').length <= 1) $J('.mainContentHeader .slideShowContoller').hide();

    $J(".mainContentHeader .play a").click(function () {
        $J(".mainContentHeader .headerSlideShow").cycle("resume");
        if ($J(".mainContentHeader .play").attr("class") != "active") {
            $J(".mainContentHeader .play").removeClass("active").addClass("hidden");
            $J(".mainContentHeader .pause").addClass("active").removeClass("hidden");
        }
    });

    $J(".mainContentHeader .pause a").click(function () {
        $J(".mainContentHeader .headerSlideShow").cycle("pause");
        if ($J(".mainContentHeader .pause").attr("class") != "active") {
            $J(".mainContentHeader .pause").removeClass("active").addClass("hidden");
            $J(".mainContentHeader .play").addClass("active").removeClass("hidden");
        }
    });
}



/*==================================
popup gallery
==================================*/
function popupGallery() {
    $J('.popupGalleryWrapper .popupGalleryList').cycle({
        fx: 'fade',
        timeout: 0,
        prev: '.popupGalleryWrapper .navigationPrev a',
        next: '.popupGalleryWrapper .navigationNext a',
        pager: '.popupGalleryWrapper .navigationList'

    });
}

function manipulationNumAndPosition() {
    var n_LG = $J('.popupGalleryWrapper .navigationList a');
    var img_cnt = $J('ul.popupGalleryList li');
    $J('.popupGalleryWrapper .navigationList a:last').addClass("last");
    for (i = 0; i < n_LG.length; i++) {
        var L_cnt = $J(n_LG[i]).html();
        var img_h;
        var img_w;
        var f_h = 556; // frame hight
        var f_w = 556; // frame width

        // put zero at front of text if lenght < 2
        if (L_cnt.length == 1) { $J(n_LG[i]).text("0" + L_cnt); }
    }
}

/*==================================
similar projects slideshow
==================================*/

function initSimilarProjectsSlideshow() {
    $J(".similarProjectModules .slideShowContainer").cycle({
        timeout: 5000,
        pager: ".navigationList",
        prev: ".navigationPrev a",
        next: ".navigationNext a",
        pagerAnchorBuilder: function (index, el) {
            return '<div><a href="#"></a></div>'; // whatever markup you want
        }
    });
}

/*==================================
font resizer
==================================*/
function initFontResize() {
    // Increase Font Size
    $J(".increaseFont").click(function () {
        var $Jbtn = $J(this);
        var count = ($Jbtn.data("click_count") || 0) + 1;
        $Jbtn.data("click_count", count);
        var currentFontSize = $J('div.columnContent').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 1.2;
        if (count < 3) {
            $J('div.columnContent').css('font-size', newFontSize);
        }
        return false;
    });
    // Decrease Font Size
    $J(".decreaseFont").click(function () {
        var currentFontSize = $J('div.columnContent').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 0.8;
        $J('div.columnContent').css('font-size', newFontSize);
        return false;
    });
    // Reset Font Size
    var originalFontSize = $J('div.columnContent').css('font-size');
    $J(".resetFont").click(function () {
        var $Jbtn = $J(".increaseFont");
        var count = 0;
        $Jbtn.data("click_count", count);
        $J('div.columnContent').css('font-size', originalFontSize);
    });
}

/*============================================
function Auto Hide Text Field Values
============================================*/
function hideInputFieldValues() {
    $J('.autoHideThisValue').focus(function () {
        $J(this).addClass("focusField");
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });
    $J('.autoHideThisValue').blur(function () {
        $J(this).removeClass("focusField");
        if (this.value == '') {
            this.value = (this.defaultValue ? this.defaultValue : this.defaultValue);
        }
    });
}

/*============================================
add first and last class for each items content
============================================*/
function firstAndLastClass(itmContainer) {
    $J(itmContainer)
    .children(':first').addClass("first")
    .end()
    .children(':last').addClass('last');
}

/*============================================
tabbed menu width
============================================*/
function tabbedMenuWidth() {
    if ($J(".tabNavigation li").exists()) {
        var n = $J(".tabNavigation li").length;
        var m = 467 / n - 1;
        $J(".tabNavigation li").css({ "width": +m + "px" });
    }
}

/*================================
Search slidedown functions
==================================*/
function initSearchSlide() {
    $J(".dropdownList li a:not(.clearAll)").each(function () {

        var divContainer = $J(this).parent();
        var divContent = $J(this).parent().parent();
        var clearAll = $J(this).next();
        var listPadding = $J(this).parent().find("a:first");

        $J(this).click(function () {

            var alreadyOpen = $J(divContainer).hasClass("itemOn");

            //alert(alreadyOpen);

            // Close all of these dropdown lists first
            $J('.dropdownList li').removeClass('itemOn');
            $J('.dropdownList li a').removeClass('linkOn').removeClass('allSelected');
            $J('.dropdownList li a').blur();

            // Open the clicked item only if it wasn't already open
            if (alreadyOpen == false) {

                // Show stuff
                $J(divContainer).toggleClass("itemOn");
                $J(clearAll).toggleClass("linkOn");
                $J(listPadding).toggleClass("allSelected");
                $J(".dropdownWrapper").jScrollPane({
                    showArrows: true,
                    autoReinitialise: true
                });
            }

        })

    })

}

/*================================
Search checkbox functions
==================================*/
function initCheckboxSelect(className) {

    //    alert($J("." + className + " .dropdownItems :checkbox:checked").length);

    $J("." + className + " .dropdownItems :checkbox").live('change', function () {
        var valueTxt = $J("." + className + " span.selectedValue");
        var str = "All";
        $J("." + className + " .dropdownItems :checkbox:checked").each(function () {

            if ($J("." + className + " .dropdownItems :checkbox:checked").length < 2) {
                str = $J(this).attr("rel");
            } else {
                if ($J("." + className + " .dropdownItems :checkbox:checked").length < 1) {
                    $J("." + className + " .dropdownItems input.selectAll").attr("checked", "checked");
                } else {
                    str = "Multiple";
                }
            }


        })
        valueTxt.text(str);
    })

    $J("." + className + " .dropdownItems .selectAll").live('change', function () {
        var $memberCheckbox = $J(this).parent().parent().find("input[type='checkbox']");
        $J("." + className + " .dropdownItems .selectAll:checked").each(function () {
            //alert($memberCheckbox.length);
            if ($memberCheckbox != null) {
                $memberCheckbox.attr('checked', true);
            }
        })
    })

    $J("." + className + " a.clearAll").live('click', function () {
        var $memberCheckbox = $J(this).parent().parent().find("input[type='checkbox']");
        if ($memberCheckbox != null) {
            $memberCheckbox.not(".selectAll").attr('checked', false);
            $J("." + className + " span.selectedValue").text("All");
        }
        switch (className) {
            case "capabilityFilter":
                $J('#' + hfCapabillityFilter).val("");
                break;
            case "regionFilter":
                $J('#' + hfRegionFilter).val("");
                break;
            case "sectorFilter":
                $J('#' + hfSectorFilter).val("");
                break;
            case "completionFilter":
                $J('#' + hfCompletionDate).val("");
                break;
            case "rateFilter":
                $J('#' + hfGreenFilter).val("");
                break;
            default:
                break;
        }
    });

}

/*================================
Cookies Function
==================================*/
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);
        }
    }
}

/*================================
Left nav active
==================================*/
function initRemoveTopBorder() {
    if ($J(".leftNavigationPlain li:first").hasClass("selected")) {
        $J(".leftNavigationPlain").css({ "border-top": "none" });
    }
    $J(".leftNavigationPlain li:first").hover(function () {
        //alert($J(this).parent().parent().html());
        $J(this).parent().parent().css({ "border-color": "#FFFFFF" });
    }, function () {
        //alert($J(this).parent().parent().html());
        $J(this).parent().parent().css({ "border-color": "#4D85C5" });
    });
}

/*================================
remove the input value
==================================*/

function initRemoveInputValue() {
    $J("input").each(function () {
        var default_value = $J(this).val();
        $J(this).focus(function () {
            if ($J(this).val() == default_value) $J(this).val("");
        });
        $J(this).blur(function () {
            if ($J(this).val() == "") $J(this).val(default_value);
        });
    });
}

/*================================
tabs
==================================*/

function initTabChange() {
    $J(".tab2").hide();
    $J(".tabChange").live("click", function () {
        var tabsId = $J(this).attr("rel");
        switch (tabsId) {
            case ".tab1":
                $J(".tab2").hide();
                $J(".filterBlock").show();
                $J(this).closest("li").addClass("selected");
                $J(this).closest("li").next().removeClass("selected");
                $J(this).closest("li").next().addClass("noSelect");
                $J(this).closest("li").removeClass("noSelect");
                break;
            case ".tab2":
                $J(".tab1").hide();
                $J(".filterBlock").hide();
                $J(this).closest("li").addClass("selected");
                $J(this).closest("li").prev().removeClass("selected");
                $J(this).closest("li").prev().addClass("noSelect");
                $J(this).closest("li").removeClass("noSelect");
                break;
            default:
        }
        $J(tabsId).show();
    });

    // Properties deeplinking
    var url = "" + window.location;

    if (url.indexOf('tab=properties') >= 0 && $J('.tab2').length > 0) {

        // Show properties tab
        $J(".tabChange").eq(1).trigger('click');

    }

}

/*================================
clean empty <p> tags
==================================*/

function initCleanTags() {
    $J(".columnContent p").each(function () {
        var pContent = $J(this).text().length;
        if (pContent <= 0) {
            $J(this).remove();
        }
    })
}



/*===============================
Function hover class
===============================*/

function initSplashClass() {
    $J(".splashContent>ul>li").hover(function () {
        $J(this).addClass("mainHover");
    }, function () {
        $J(this).removeClass("mainHover");
    });
}

/*================================
homepage sub feature functions
==================================*/
function initSubFeatureSlideDown() {
    $J(".homePage .column .columnHeader").each(function () {
        var divContainer = $J(this);
        var divContent = $J(this).find("div.slideContent");
        $J(this).hover(function () {
            $J(divContainer).toggleClass("itemOn");
            $J(divContent).slideToggle("fast");
        }, function () {
            $J(this).find("div.slideContent").hide(500, function () {
                $J(this).hide();
                $J(divContainer).toggleClass("itemOn");
            });
        });
    })
}


/*================================
Iframe content
==================================*/
function initIframeContent() {

    // get window height, minus header height, set iframe height
    var temp = $J(window).height() - 130;
    $J('.trIframeContent').attr('height', temp);
    //$J('#wrapper iframe').attr('height', temp);
    //$J('#wrapper iframe').attr('width', '973');

}

