/*
* Background fading and other functions used with the business section
*/
$(document).ready(function($) {
    var hoverConfig = {
        over: function () {
            if ($(this).find('ul').length > 0) {
                //$(this).find('ul:first').css('visibility','visible');
                $(this).find('ul:first').fadeIn(400);
            }
        },
        timeout: 200, // number = milliseconds delay before onMouseOut
        out: function () {
            if ($(this).find('ul').length > 0) {
                //$(this).find('ul:first').css('visibility','hidden');
                $(this).find('ul:first').fadeOut(600);
            }
        }
    };

    $('div.top-nav-inner li.nav').hoverIntent(hoverConfig);

    // Setup background images
    var dir = '/assets/templates/rce_business/images/backgrounds/';
    var imgs = new Array('Plants_II_062.jpg','Plants_II_064.jpg','Plants_II_065.jpg','Plants_II_067.jpg','Plants_II_095.jpg','Plants_III_041.jpg','Plants_III_051.jpg');
    var bgindex = 0;

    // Get and set bgindex cookie
    if (jQuery.cookie('bgindex')) {
        bgindex = jQuery.cookie('bgindex');
    } else {
        jQuery.cookie('bgindex', bgindex);
    }

    // Setup original bg image
    $('#section-bg').css('background-image',"url('"+dir+imgs[bgindex]+"')");
    var new_bgindex = getNewBgIndex(bgindex,imgs); // hack 20090403
    if (!isIE6()) {
        setTimeout("doFade('section-bg','"+dir+imgs[new_bgindex]+"')",500);
    }

    // Setup lightbox for client resource center login
    $('a.iframe').fancybox({
        'hideOnContentClick': false,
        'padding': 0,
        'width': 440,
        'height': 325,
        'overlayShow': true,
        'overlayOpacity': 0.4,
        'overlayColor': '#333'
    });

	// Lightbox for client success stories
	$('a.inline').fancybox({
		'padding':5,
		'hideOnContentClick': true,
		'autoDimensions': false,
		'width': 650,
		'height': 'auto',
		'overlayShow': true,
		'overlayOpacity': 0.4,
		'overlayColor': '#5e7135',
		'onComplete': function() {jQuery.fancybox.resize();}
	});

	$('a.inline').hover(function() {
		//alert($(this).children(':first-child').attr('src'));

		$(this).children(':first-child').animate({
			top: -10,
			left: 75
		}, 200);
	}, function() {
		$(this).children(':first-child').animate({
			top: -5,
			left: 65
		}, 200);
	});
});

/*
 * Not only when the DOM is ready, but when the images have finished loading,
 * important, but subtle difference to $(document).ready()
 */
$(window).bind('load', function() {
    // Run the cross fade plugin against selector
    $('img.fade').crossfade();
});

function isIE6() {
    if (jQuery.browser.msie == true && jQuery.browser.version < 7) {
        return true;
    }
    return false;
}

function isIE() {
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function getNewBgIndex(current_index,arr) {
    var i;
    current_index = parseInt(current_index);

    if (current_index == 0) {
        i = 1;
    } else if (current_index < (arr.length - 1)) {
        i = current_index+1;
    } else {
        i = 0;
    }

    jQuery.cookie('bgindex', i);
    return i;
}

function doFade(layer,newImg) {
    var new_layer = $('#'+layer).clone();

    $(new_layer).css('opacity','0');
    $(new_layer).css('background-image',"url('"+newImg+"')");
    $('#'+layer).after( new_layer );

    $('#'+layer).animate({
        opacity: 0.0
    }, 1500);

    $(new_layer).animate({
        opacity: 1.0
    }, 1500);
}

// Client page logo rollover effect
function doLogoRollOver(ele) {
	ele.style.backgroundPosition = 'bottom';
}
function doLogoRollOut(ele) {
	ele.style.backgroundPosition = 'top';
}

/*
 * Rollover crossfade functions
 */

// Create our transition as a plugin
jQuery.fn.crossfade = function () {
    return this.each(function () {
        // Cache the copy of jQuery(this) - the start image
        var el = $(this);

        // Get the target from the backgroundImage + regexp
        var target = el.css('backgroundImage').replace(/^url|[\(\)]/g, '');

        // Nice long chain: wrap img element in span
        el.wrap('<span style="position: relative;"></span>')
           // Change selector to parent - i.e. newly created span
           .parent()
           // Prepend a new image inside the span
           .prepend('<img>')
           // Change the selector to the newly created image
           .find(':first-child')
           // Set the image to the target
           .attr('src', target);

        // Position the original image
        el.css({
          'position' : 'absolute',
          'left' : 0,
          // this.offsetTop aligns the image correctly inside the span
          'top' : this.offsetTop
        });

        // Note: the above CSS change requires different handling for Opera and Safari,
        // <a href="http://jqueryfordesigners.com/downloads/jquery.crossfade.js">see the full plugin for this</a>.

        // Similar effect as single image technique, except using .animate
        // which will handle the fading up from the right opacity for us
        el.hover(function () {
            el.stop().animate({
                opacity: 0
            }, 100);
        }, function () {
            el.stop().animate({
                opacity: 1
            }, 100);
        });
    });
};

/*
 * Footer image swaps
 */
var footer_img_vert = new Array('001_business_Leaf&Building.jpg','002_misc_3486244.jpg','002_pol_3151289.jpg','002_travel_851916.jpg','003_nature_3725739.jpg','003_wind_trimont1.jpg','004_nature_3629418.jpg','004_wind_tractor.jpg','005_nature_3227626.jpg','006_nature_3126685.jpg','007_wind_2106344.jpg','009_nature214381.jpg','012_wind_dv2012023.jpg');
var footer_img_horz = new Array('001_misc_4821375.jpg','001_nature_4608687.jpg','001_pol_8276806.jpg','001_solar_2241111.jpg','001_travel_3939776.jpg','001_wind_WNDF-0145.jpg','002_business_4664572.jpg','002_nature_3726308.jpg','002_wind_WNDF-0136.jpg','003_business_ForBusinessImage.jpg','003_pol_595921.jpg','003_travel_571898.jpg','004_travel_265313.jpg','005_wind_3694914.jpg','005_wind_topscreen.jpg','006_wind_3668880.jpg','007_nature_2658795.jpg','008_nature_1921014.jpg','008_wind_1540317.jpg','009_nature_276309.jpg','009_wind_1521469.jpg','010_wind_622709.jpg','011_wind_482016.jpg','013_wind_Corn&Turbine.jpg','014_wind_barn.jpg');

function doFooterImage(targ,arr,override) {
    if (override == 'blank.gif') {
        var dir = '/assets/templates/rce_business/images/footer_images/';
        var img = arr[ Math.floor(Math.random()*arr.length) ];
        $('#'+targ).attr('src',dir+img);
    }
}

/*
 * Slide toggles a definition list, such as success stories
 */
function slideToggleDl(l) {
    $('#dl_container dl').each( function(i) {
        if (l == $(this).find('dd:first').attr('id')) {
            // turn on
            if ($(this).find('a:first').attr('class') != 'on') {
                $(this).find('a:first').attr('class','on');
                $('#'+l).slideDown();
            } else {
                $(this).find('a:first').attr('class','');
                $('#'+l).slideUp();
            }
        } else {
            // turn off
            $(this).find('a:first').attr('class','');
            $(this).find('dd:first').slideUp();
        }
    });
}

function slideToggleDd(l) {
    $('#dl_container dt').each( function(i) {
        if (l == $(this).next().attr('id')) {
            // turn on
            $(this).find('a:first').attr('class','on');

            $('#'+l).slideDown('normal', function() {
               $('#dl_container').height($(this).height());
            });
        } else {
            // turn off
            $(this).find('a:first').attr('class','');
            $(this).next().slideUp();
        }
    });
}

/*
 * Lookup form handler
 */
function doZipcodeLookup(frm) {
    // hide form if it's been previously shown
    $('#contact_rep_info').css('display','none');
    $('#rep_form').css('display','none');

    // Test values
    if (frm.country.value == '' || frm.country.value == '--') {
        alert('Please select a Country');
        frm.country.focus();
        return false;
    }
    if ((frm.country.value == 'United States' ||
         frm.country.value == 'Canada') && (frm.state.value == '' || frm.state.value == '--')) {
        alert('Please select a State/Province');
        frm.state.focus();
        return false;
    }

    //if (frm.zip.value != '' && !frm.zip.value.match(/^[0-9A-Za-z ]{5,16}$/gi)) {
    //    alert('Please enter a valid Zip/Postal Code');
    //    frm.zip.focus();
    //    return false;
    //}

    // Do ajax call
    $('#rep_info').html('<p><img src="assets/templates/rce_business/images/ajax-loader.gif"> Searching....</p>');
    $('#contact_rep_info').css('display','block');
    var url = '/sf-zipcode-lookup';
    var type = '';
    for (i = 0; i < frm.type.length; i++) {
        if (frm.type[i].checked) {
            type = frm.type[i].value
        }
    }
    //var data = {country: frm.country.value, zip: frm.zip.value, state: frm.state.value, type: type};
    var data = {country: frm.country.value, state: frm.state.value, type: type};

    $.get(url,data,function(returnData,textStatus) {
        if (textStatus == 'success') {
            $('#rep_info').html(returnData);
        } else {
            $('#contact_rep_info').html('<p>An error occurred returning the information. Please try again.</p>');
        }
        return false;
    });
    return false;
}

/*
 * Read a page's GET URL variables and return them as an associative array.
 */
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*
 * Team page JSON and rollover functions
 */
function buildTeam(data,divID,n) {
    if (divID != 'consultants') {
        for (person in data) {
            var img = '/assets/templates/rce_business/images/team_photos/new/' + data[person].name.replace(/[ ,.]/g,"") + '.jpg';
            var cls = ((Number(person)+1)%5 == 0) ? "team_pic lastCol" : "team_pic";
            $('#' + divID).append('<div class="' + cls + '" id="' + person + '"><img src="' + img + '" /><br /><span>' + data[person].name + '</span></div>');
        }

        $('#' + divID + ' img').hover(
            function(e) {
                var newX = (157*(Math.floor((e.pageX-62)/157)))+129;
                var newY = (230*(Math.floor((e.pageY-332-(n*61))/230)))+(170+(n*61));

                $('#toolBox').css('left', newX + 'px');
                $('#toolBox').css('top', newY + 'px');

                var id = $(this).parent().get(0).id;
                var name = data[id].name;
                var position = (data[id].region != undefined) ? data[id].position + '<br />' + data[id].region : data[id].position;
                var description = data[id].description;

                $("#toolBox").html('<div id="tick"></div><h2>' + name + '</h2><p class="position">' + position + '</p><p class="desc">' + description + '</p>');
                $("#toolBox").css("visibility","visible");
            }, function(){
                $("#toolBox").css("visibility","hidden");
            }
        );
	} else {
        // Special handling for consultants (no images)
        $('#' + divID).append('<ul id="consultant_list"></ul>');

        for (person in data) {
            // var img = 'assets/templates/rce_business/images/team_photos/new/' + data[person].name.replace(/[ ,.]/g,"") + '.jpg';
            // var cls = ((Number(person)+1)%5 == 0) ? "team_pic lastCol" : "team_pic";
            $('#consultant_list').append('<li id="' + person + '"><strong>' + data[person].name + '</strong></li>');
        }

        $("#consultant_list").find('strong').hover(
            function(e) {
                var newX = Math.floor(e.pageX-30);
                var newY = Math.floor(e.pageY-225);

                $('#toolBox').css('left', newX + 'px');
                $('#toolBox').css('top', newY + 'px');

                var id = $(this).parent().attr('id');
                var name = data[id].name;
                var position = (data[id].region != undefined) ? data[id].position + '<br />' + data[id].region : data[id].position;
                var description = data[id].description;

                $('#toolBox').html('<div id="tick"></div><h2>' + name + '</h2>');
                if (position != '') {
                    $('#toolBox').append('<p class="position">' + position + '</p><p class="desc">' + description + '</p>');
                } else {
                    $('#toolBox').append('<p class="desc">' + description + '</p>');
                }
                $('#toolBox').css('visibility', 'visible');
    		}, function() {
	    		$('#toolBox').css('visibility', 'hidden');
            }
        );
    }
};

function popRolloverText(tgt,e) {
    var yInterval;

	if (tgt.attr('class') == 'sprite popup_text') {
		yInterval = 170;
	} else {
		yInterval = 230
	}

    var newX = (200*(Math.floor((e.pageX-62)/200)))+129;
    var newY = (yInterval*(Math.floor((e.pageY-332-(61))/yInterval)))+(170+(61));

    $('#toolBox').css('left', newX + 'px');
    $('#toolBox').css('top', newY + 'px');
    $('#toolBox').html('<div id="tick"></div>' + tgt.find('span').html());
    $('#toolBox').css('visibility', 'visible');
    tgt.css('background-position', 'bottom');
};

