/*jslint bitwise: true, eqeqeq: true, passfail: false, nomen: false, plusplus: false, undef: true, laxbreak: true */
/*global window, document, jQuery, self, setTimeout, Image, GMap2, GIcon, G_DEFAULT_ICON, GLatLng, GSize, GMarker, */
/**
* @namespace Root namespace for holding all objects created for LBI
*/
var LBI = window.LBI || {};

/**
* Object that stores custom functions throughout the LBI site.
* @namespace Object that stores useful functions throughout the LBI site.
* @member LBI
*/
LBI.custom = {
    /**
    * Public function to hold all functionality associated for show and hide elements
    *
    * @function
    * @memberOf LBI.custom
    */
    toggle: (function () {
        var defaults = {
            controller: '.control',
            controlElem: '.expandContent',
            active: -1,
            animation: false,
            collapsible: false
        };

        function showHide(target, controller, controlElem, settings) {
            var $trigger = jQuery(target),
                tabId = $trigger.attr('href');

            controller.removeClass('selected');
            $trigger.addClass('selected');

            if (settings.animation) {
                if (LBI.custom.toggle.externalControl) {
                    controlElem.removeClass("selected");
                }
                else {
                    controlElem.slideUp(300);
                    // controlElem.hide();
                }
                jQuery(tabId).slideDown('slow');
            }
            else {
                controlElem.removeClass("selected");
                jQuery(tabId).addClass("selected");
            }
        }

        var init = function (target, options) {
            var settings = jQuery.extend({}, defaults, options || {});
            jQuery(target).each(function () {
                var controller = jQuery(this).find(settings.controller),
				    controlElem = jQuery(this).find(settings.controlElem);

                controlElem.removeClass("selected");
                if (settings.active < 0) {
                    jQuery(controlElem[0]).addClass("selected");
                }

                controller.bind('click', function () {
                    showHide(this, controller, controlElem, settings);
                    return false;
                });

            });
        };

        return {
            init: init,
            externalControl: false
        };
    } ()),

    /**
    * Public function to hold all functionality associated for quick links
    *
    * @function
    * @memberOf LBI.custom
    */
    quickLinks: (function () {
        function setupQuickLinks() {
            jQuery('.quick_links a').bind('click', function () {
                var id = jQuery(this).attr("href");
                LBI.custom.toggle.externalControl = true;
                jQuery(id + ' .control').click();
                LBI.custom.toggle.externalControl = false;
            });
        }

        return {
            init: function () { setupQuickLinks(); }
        };
    } ()),

    /**
    * Public function to hold all functionality associated for Google map on Contact page
    *
    * @function
    * @memberOf LBI.custom
    */
    contactMap: (function () {
        var infowindow = null;
        var mark = null;
        var point = null;
        markers = [
	        { "City": "AbuDhabi", "Address": "Hamdan Street<br \/>Abu Dhabi<br \/>P. O. Box 40280", "ID": "gmapid-f4ee60ac-beda-4eff-86d1-b4d98028fff5", "Latitude": "24.492736", "Longitude": "54.36733", "Title": "Abu Dhabi", "Website": "http:\/\/www.lbi.com\/en\/AbuDhabi\/ContactUs_Accessible\/" },
	        { "City": "Amsterdam", "Address": "Joop Geesinkweg, 209<br \/>1096 Amsterdam", "ID": "gmapid-48afc882-6630-49db-ac7f-83da7eee95f4", "Latitude": "52.335437", "Longitude": "4.933818", "Title": "Amsterdam", "Website": "http:\/\/www.lostboys.nl\/" },
	        { "City": "Atlanta", "Address": "1888 Emery St NW<br \/>GA 30318<br \/>Atlanta", "ID": "gmapid-ab1f934f-b372-4dd6-8703-972660536f08", "Latitude": "33.808192", "Longitude": "-84.414356", "Title": "Atlanta", "Website": "http:\/\/www.lbiatlanta.com\/" },
	        { "City": "Berlin-Iven_and_Hillmann", "Address": "Monbijouplatz 10<br \/>10178,Berlin", "ID": "gmapid-ff4ce9c0-3ba9-4f1a-819e-9833549bd291", "Latitude": "52.523221", "Longitude": "13.39905", "Title": "Berlin - Iven and Hillmann", "Website": "http:\/\/www.iven-hillmann.com\/" },
        	{ "City": "Berlin-Metadesign", "Address": "Leibnizstra&#223;e 65<br \/>10625 Berlin", "ID": "gmapid-04c33b1a-870e-429a-850f-0adac97a2e87", "Latitude": "52.504513", "Longitude": "13.313601", "Title": "Berlin - Metadesign", "Website": "http:\/\/www.metadesign.de\/" },
	        { "City": "Brussels", "Address": "Vorstlaan 191 Bd du Souverain<br \/>1160 Brussels", "ID": "gmapid-659d6ba1-3f7b-47e2-84a6-cc21b6710730", "Latitude": "50.81767", "Longitude": "4.427101", "Title": "Brussels", "Website": "http:\/\/www.lbigroup.be" },
	        { "City": "Cologne", "Address": "Hansaring 97<br \/>50670 K&#246;ln", "ID": "gmapid-0f5bde35-c0dc-439b-a740-d197b1147490", "Latitude": "50.948661", "Longitude": "6.950942", "Title": "Cologne", "Website": "http:\/\/www.lbi-germany.de\/" },
	        { "City": "Copenhagen", "Address": "Vermundsgade 40A<br \/>2100 Kobenhavn", "ID": "gmapid-20750ec6-6c60-442f-bd84-c368003664d8", "Latitude": "55.708012", "Longitude": "12.550244", "Title": "Copenhagen", "Website": "http:\/\/www.lbicph.com\/" },
	        { "City": "Exeter", "Address": "Broadwalk House North<br \/>Southernhay West<br \/>Exeter<br \/>EX1 1TS", "ID": "gmapid-34cbb5a3-6a84-48f6-bda1-806de25a99b9", "Latitude": "50.721935", "Longitude": "-3.527588", "Title": "Exeter", "Website": "http:\/\/www.lbi-netrank.co.uk\/" },
	        { "City": "Ghent", "Address": "Kortrijksesteenweg 1144 bus N<br \/>9051 Sint-Denijs-Westrem", "ID": "gmapid-6c037cb0-1b79-470b-ac8d-74156ea6da16", "Latitude": "51.018497", "Longitude": "3.673496", "Title": "Ghent", "Website": "http:\/\/www.lbigroup.be" },
	        { "City": "Gothenburg", "Address": "&#214;stra Larmgatan 16<br \/>411 07 G&#246;teborg", "ID": "gmapid-5e1f37be-c8ad-4779-bd2b-32ea7e93a50f", "Latitude": "57.7052019662899", "Longitude": "11.9712996482849", "Title": "Gothenburg", "Website": "http:\/\/www.lbigot.com\/" },
	        { "City": "Hamburg", "Address": "M&#246;nkedamm 11<br \/>20457 Hamburg", "ID": "gmapid-ace41414-f5fa-40d2-944d-c6da8ee73dff", "Latitude": "53.549013", "Longitude": "9.989206", "Title": "Hamburg", "Website": "http:\/\/www.lbi-germany.de\/" },
	        { "City": "London", "Address": "Atlantis Building<br \/>Truman Brewery<br \/>146 Brick Lane<br \/>London E1 6RU", "ID": "gmapid-c40d9812-c875-4222-8e52-eecc81be1a42", "Latitude": "51.5217218177544", "Longitude": "-0.0715184211730957", "Title": "London", "Website": "http:\/\/www.lbi.co.uk\/" },
	        { "City": "Madrid", "Address": "Jos&#233; Echegaray, 6<br \/>Edificio B, planta 1a<br \/>Parque Empresarial Las Rozas<br \/>28230 - Las Rozas, Madrid", "ID": "gmapid-52980617-6c5b-42f7-a46a-165d9c4427fc", "Latitude": "40.523297", "Longitude": "-3.89029", "Title": "Madrid", "Website": "http:\/\/www.lbigroup.es\/" },
	        { "City": "Malmo", "Address": "Brogatan 10<br \/>211 44 Malm&#246;", "ID": "gmapid-efd76f77-c178-4822-a1f2-0e73a92e8551", "Latitude": "55.5973", "Longitude": "13.002658", "Title": "Malmo", "Website": "http:\/\/www.lbigot.com\/" },
	        { "City": "Milan", "Address": "Via Marghera 43<br \/>20149 Milano", "ID": "gmapid-42e2b9b5-42f8-40cd-9733-ee965e3b0c41", "Latitude": "45.466697", "Longitude": "9.151703", "Title": "Milan", "Website": "http:\/\/www.iconmedialab.it\/" },
	        { "City": "Mumbai", "Address": "126, Mathura Das Mill Compound<br \/>N.M. Joshi Marg,<br \/>Lower Parel,<br \/>Mumbai - 400 013", "ID": "gmapid-288408ab-4c38-4595-bb9f-e538ca1f7395", "Latitude": "19.001358", "Longitude": "72.831392", "Title": "Mumbai", "Website": "http:\/\/www.lbi.co.in\/" },
	        { "City": "Munich", "Address": "Kolosseumstra&#223;e 1<br \/>80469 M&#252;nchen", "ID": "gmapid-508056e3-57e4-4bae-a7f1-10f12d3c6f46", "Latitude": "48.130867", "Longitude": "11.571286", "Title": "Munich", "Website": "http:\/\/www.lbi-germany.de\/" },
	        { "City": "NewYork-IconNicholson", "Address": "295 Lafayette St<br \/>New York<br \/>NY 10012", "ID": "gmapid-1a731a6a-508e-4534-864b-9c33b349d0fa", "Latitude": "40.724706", "Longitude": "-73.995452", "Title": "NY - IconNicholson", "Website": "http:\/\/www.iconnicholson.com\/" },
	        { "City": "NewYork-Special_Ops_Media", "Address": "Park Avenue South 235<br \/>5th floor<br \/>New York, NY 10003", "ID": "gmapid-f7714cf1-88b5-4b27-a117-1d76c44cdaf9", "Latitude": "40.737687", "Longitude": "-73.987659", "Title": "NY - Special Ops Media", "Website": "http:\/\/www.specialopsmedia.com\/" },
	        { "City": "NewYork-Syrup", "Address": "Vestry street 12<br \/>7th floor<br \/>New York, NY 10013", "ID": "gmapid-0c75448c-4bba-4f4f-9530-4559d6b9ba25", "Latitude": "40.722775", "Longitude": "-74.007266", "Title": "NY - Syrup", "Website": "http:\/\/www.syrupnyc.com\/" },
	        { "City": "Paris", "Address": "19,rue de Jussieu<br \/>75005,Paris", "ID": "gmapid-95cab2e0-e3a9-4207-a005-66850ccb9de2", "Latitude": "48.845996", "Longitude": "2.355299", "Title": "Paris", "Website": "http:\/\/www.lbi.com\/" },
	        { "City": "Stockholm", "Address": "Kungsgatan,6<br \/>S-111 43<br \/>Stockholm", "ID": "gmapid-2520bc0c-ba8d-4e7d-bb53-ccd5d0786f19", "Latitude": "59.336194", "Longitude": "18.06999", "Title": "Stockholm", "Website": "http:\/\/www.lbisweden.com\/" },
	        { "City": "Zurich", "Address": "Gerechtigkeitsgasse,6<br \/>8001,Z&#252;rich", "ID": "gmapid-576de780-2cf6-4394-9d86-47db1d629a46", "Latitude": "47.369988", "Longitude": "8.531999", "Title": "Zurich", "Website": "http:\/\/www.lbi-switzerland.com\/"}];

        function findBranch(city) {
            for (var i = 0; i < markers.length; i++) {
                if (markers[i].City == city) {
                    return i;
                }
            }
        }

        function setupAddress(branch) {
            branch = branch || 0;
            var address = jQuery('#address');

            if (address.length > 0) {
                var string = '<p>LBi ';
                string += markers[branch].Title;
                string += '<br />';
                string += markers[branch].Address;
                string += '</p>';
                address.html(string);
            }
        }


        function setupMap(branch) {  //
            branch = branch || 0; // default is Stockholm
            if (jQuery("#contact").length > 0) {

                // create Google Map and marker
                var map = new GMap2(document.getElementById('img-feature')),
					lbiIcon = new GIcon(G_DEFAULT_ICON),
					markerOptions;

                // initialise map
                map.setCenter(new GLatLng(markers[branch].Latitude, markers[branch].Longitude), 15);
                map.setUIToDefault();
                //map.disableScrollWheelZoom();

                // initialise marker
                lbiIcon.image = "/wp-content/themes/lbi/assets/img/map-marker.png";
                lbiIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
                lbiIcon.iconSize = new GSize(33, 41);
                lbiIcon.shadowSize = new GSize(22, 20);

                // set up GMarkerOptions object
                markerOptions = { icon: lbiIcon };

                for (var i = 0; i < markers.length; i++) {

                    point = new GLatLng(markers[i].Latitude, markers[i].Longitude);
                    mark = new GMarker(point, markerOptions);
                    map.addOverlay(mark);
                    //alert(markers[i].City);
                    GEvent.addListener(mark, "click", (function (marker, point) {
                        return function () {
                            //alert('You clicked on ' + marker.City);
                            var myHtml = "<b>#" + marker.Title + "</b><br />" + marker.Address + "<br />" +
                                "<a href=\"" + marker.Website + "\">" + marker.Website + "</a>";
                            map.openInfoWindowHtml(point, myHtml);
                        }
                    })(markers[i], point)
                    )
                }
            }
        }
        return {
            init: function () {
                branch = findBranch(myLBi);
                setupMap(branch);
                setupAddress(branch);
                jQuery('.branchFocus').bind('click', function () {
                    for (var i = 0; i < markers.length; i++) {
                        if ($(this).hasClass(markers[i].City)) {
                            setupMap(i);
                            break; // bind to the first City found only
                        }
                    }
                });
            }
        };
    } ()),

    /**
    * Public function to insert spans to mark the first letter of each word in the LBI Header in red
    *
    * @function
    * @memberOf LBI.custom
    */
    styleTagline: (function () {
        function setupTagline() {
            // get the randomised string (this class is not used on the homepage)
            var $tagline = jQuery('h2.random_tagline');

            if ($tagline.length > 0) {
                var string = $tagline.text(),
					newString = "",
					words = string.split(' '),
					letters;

                jQuery.each(words, function (key, value) {
                    letters = value.split('');
                    // add span aroudn first letter of each word
                    jQuery.each(letters, function (key, value) {
                        if (key === 0) {
                            newString += '<span>' + value + '</span>';
                        } else {
                            newString += value;
                        }
                    });
                    newString += ' ';
                });
                $tagline.html(newString);
            }
        }

        return {
            init: function () { setupTagline(); }
        };
    } ()),

    /**
    * Public function to handle opening links in a new window
    *
    * @function
    * @memberOf LBI.custom
    */
    newWin: (function () {
        return {
            init: function () {
                jQuery(".winnew").click(function () {
                    var w = window.open(jQuery(this).attr("href"), "pop");
                    w.focus();
                    return false;
                });
            }
        };
    } ()),

    /**
    * Public function to handle twitter feed functionality
    *
    * @function
    * @memberOf LBI.custom
    */
    twitterFeed: (function () {
        function definePosition() {
            var $imgFeature = jQuery("#img-feature"),
				$orientation = jQuery("#orientation"),
				maxHight = $imgFeature.offset().top + $imgFeature.height(),
				minHeight = $orientation.offset().top + $orientation.height(),
				marginHeight = (maxHight - minHeight) - 44;

            jQuery("#featured-post").css({ marginTop: -marginHeight });
        }

        function setupTwitterFeed() {
            var $tweet = jQuery("#tweet");
            if ($tweet.length > 0) {
                var host = location.host;
                jQuery.get('http://' + host + '/proxy/proxy.php', { 'city': myLBi }, function (data) {
                    if (typeof data === "string") {
                        $tweet[0].innerHTML = data;
                    }
                }, "html");
            }

            definePosition();
        }

        return {
            init: function () { setupTwitterFeed(); }
        };

    } ()),

    /**
    * Public function to enable territory selection
    *
    * @function
    * @memberOf LBI.custom
    */
    territorySelect: (function () {
        function init() {
            jQuery('.territoryTrigger').bind('click', function () {
                if (jQuery('.territorySelector').width() != 594) {
                    jQuery('.territorySelector').animate({ height: '347', width: '594' }, 500, function () {
                        jQuery('.territoryPanel').fadeIn('fast');
                        jQuery('#tagline').hide();
                        jQuery('#tagline').css('z-index', 150003);
                        jQuery('#tagline').fadeIn('slow');
                    });

                    jQuery('.territoryWrapper').css('z-index', 150002);
                    jQuery('.territorySelector').css('z-index', 150001);
                    jQuery('#cboxOverlay').css({ "opacity": .7 }).show();
                }

                // Close
                jQuery('#cboxOverlay').bind('click', function () {
                    jQuery('.territoryPanel').hide();
                    jQuery('#cboxOverlay').hide();
                    jQuery('.territorySelector').css('height', '20px');
                    jQuery('.territorySelector').css('width', '200px');
                    jQuery('.territoryWrapper').css('z-index', 17);
                    jQuery('.territorySelector').css('z-index', 16);
                    jQuery('#tagline').css('z-index', 1);
                });
            });

            jQuery('.closeCross').bind('click', function () {
                jQuery('#cboxOverlay').click();
            });
        }

        return {
            init: function () { init(); }
        };

    } ()),

    /**
    * Public function to enable ajaxTabs
    *
    * @function
    * @memberOf LBI.custom
    */
    ajaxTabs: (function () {
        function init() {
            jQuery('.ajaxTabs li a').bind('click', function () {
                var indx = jQuery('.ajaxTabs li a').index(this)
                jQuery('.tabLoader').show();
                var target = jQuery(this);
                jQuery('.ajaxContent').eq(indx).load(target.attr('href'), function () {
                    jQuery('.ajaxTabs li a').removeClass('selected');
                    jQuery('.subContent').removeClass('selected')
                    jQuery('.subContent').eq(indx).addClass('selected')
                    $(target).addClass('selected');
                    LBI.custom.toggle.init(jQuery('.expander'), { collapsible: true, animation: true });
                    jQuery('.tabLoader').hide();
                });
                return false;
            });
        }

        return {
            init: function () { init(); }
        };

    } ()),

	/**
	 * Public function to enable Branded Content Salon presenter bio pop-up
	 *
	 * @function
	 * @memberOf LBI.custom 
	 * */
	BCS_bio: (function () {
		function showBio() {
			$(".show-bio").colorbox({width:"50%", inline:true, href: function(){
			   return '#' +  $(this).parent().children('div').attr('id');
			}});
		}

		return {
			init: function() { showBio(); }
		};
	}())
};

jQuery(document).ready(function() {
	LBI.custom.toggle.init(jQuery('.expander'), { collapsible: true, animation: true });
	LBI.custom.toggle.init(jQuery('.tabs'), { controller: '.tabControls a', controlElem: '.content' });
	LBI.custom.quickLinks.init();
	LBI.custom.contactMap.init();
	LBI.custom.styleTagline.init();
	LBI.custom.newWin.init();
	LBI.custom.twitterFeed.init();
	LBI.custom.territorySelect.init();
	LBI.custom.ajaxTabs.init();
	LBI.custom.BCS_bio.init();


});

