// sets link/logo visibility for a toggler row and attaches appropriate shadow for row
function set_links(row) {
    $('h3.toggler').each(function (index, element) {
        // shadowing (use shadow gif swapping on IE, otherwise keep regular transparent png)
		/*
        if ($.browser.msie) { // IE
            var shad_el = $(element).prev()[0];
            var parts = shad_el.className.replace(/btn_shadow_/, '').split('_');
            if (parts[0] != 'blank') { // non-about section
                var swap = (element == row) ? 'sel' : 'nosel';
                shad_el.className = "btn_shadow_" + parts[0] + "_" + (window.floral ? 'fl_' : '') + swap;
            }
        }
		*/

        if (element == row) {
            $('a[rel="ajax"]', element).addClass('second_nav_show');
            $(element).find('.arrow_up').css('visibility', 'visible');
        } else {
            $('a[rel="ajax"]', element).removeClass('second_nav_show').removeClass('active').removeClass('active_sn');
            $(element).find('.arrow_up').css('visibility', 'hidden');
        }
    });
}

// overrides search form submission through ajax
function setup_search() {
    $('.frmsearch').unbind('submit').submit(function() {
        //var row_el = $('#btn_help' + (window.floral ? '_fl' : '') + ' h3.toggler')[0];
        //var cont = $('#btn_help' + (window.floral ? '_fl' : '') + ' .accordion');
        var row_el = $('#btn_about' + (window.floral ? '_fl' : '') + ' h3.toggler')[0];
        var cont = $('#btn_about' + (window.floral ? '_fl' : '') + ' .accordion');

        if (row_el) {
            show_row(row_el);
            var path = this.action + this.q.value;
            return run_ajax_link({pathname: path, href: path}, null, cont);
        }
        return false;
    });
}

// overrides video, legal, and floral links to show content in appropriate lightbox container
function setup_popups() {
    $('#legallnk, .video, .videolk, #floral_link').unbind('click').click(function(e) {
        e.preventDefault();

        // directly linked to video page
        if ($(this).hasClass('video') && $(this).parents('#modalContainer').length == 0) {
            handle_link(this);
            return;
        } else {
            var cont = $('#misc_cont');
            cont.html('<div id="lb_loading"><img src="'+window.siteroot+'img/loading.gif" alt="loading" /> loading...</div>');
            run_ajax_link(this, null, cont, false, false);
        }

        // determine window dimensions based on type of link
        var dim = {};
        switch (this.id) {
            case 'legallnk': // legal
                dim = {
                    left: '56%',
                    top: '35%',
                    width: '462px',
                    height: '195px'
                };
                break;
            case 'floral_link': // industries -> floral link
                dim = {
                    left: '56%',
                    top: '35%',
                    width: '410px',
                    height: '145px'
                };
                break;
            default: // video
                dim = {
                    left: '43%',
                    top: '25%',
                    width: '760px',
                    height: '346px'
                };
        }

        cont.modal({
            containerCss: dim,
            onShow: function(dialog) {
                dialog.overlay.click(function() {
                    cont.html(''); // clear content in lightbox first
                    $.modal.close();
                });
            },
            onClose: function() {
                cont.html(''); // clear content in lightbox first
                $.modal.close();
            }
        });
    });
}

// manages deep-linking across pages
function poll_location() {
    var curloc = window.location.hash;

    if (curloc && curloc != '#/' && window.oldloc != curloc) {
        var loc = curloc.substr(2); // strip off #/

        var rowlink = $("h3.toggler a[href$='" + loc + "']:eq(0)"); // match link in one of the rows
        if (rowlink.length) { // exists, just click it
            rowlink.click();
        } else { // was a link within content, need to emulate to restore former state
            var parts = loc.split(/\//);
            var row_el = $('#btn_' + parts[0] + (window.floral ? '_fl' : '') + ' h3.toggler')[0];

            if (row_el) {
                var path = window.siteroot + loc;
                show_row(row_el);
                run_ajax_link({pathname: path, href: path});
            } else { // invalid hash, reset page
                show_row(null);
            }
        }
    }
}

// returns relative path to controller / action
function rel_path(path) {
    // strip off protocol
    var proto = path.indexOf('://');
    if (proto != -1) path = path.substr(proto+3);

    var sr = window.siteroot;
    var index = path.indexOf(sr);
    if (index != -1) {
        path = path.substr(index+sr.length).replace(/#.*$/, '');
    }
    return path;
};

// toggles row selection
function show_row(row_el) {
    // set row tracking
    if (window.selrow != row_el) {
        $("#content").show_row(row_el); // show appropriate accordion row
        set_links(row_el);
    }
    window.selrow = row_el;
}

// link handling through ajax
function run_ajax_link(target, data, altcont, update_path, show_load_txt) {
    if (update_path == null) update_path = true; // update url path after loading content
    if (show_load_txt == null) show_load_txt = true; // update loading message before loading content
    var rp = target.pathname ? target.pathname : '';
    if (rp.substr(0,1) != '/') rp = '/'+rp;
    rp = rel_path(rp);
    var parts = rp.split(/\//);
    var controller = parts[0];
    var action = parts[1];
    var container = altcont ? altcont : $('#btn_' + controller + (window.floral ? '_fl' : '') + ' .accordion');
    var cur_hash = '#/' + rp;

    if (altcont || cur_hash != window.oldhash) {
        if (show_load_txt) container.html('<div class="ajax-load">loading...</div>');
        window.oldhash = cur_hash;
        window.curajaxtarget = target.href;

        // handle setting active arrow for associated menu bar link
        container.parent().find('a[rel="ajax"]').each(function(index, element) {
            var regex = "/" + controller + "/";
            if (action) regex += action + "/";
            regex += "$";

            if (element.href.match(regex)) {
                if (element.className.match(/\bmain_link\b/)) {
                    $(element).addClass('active').css('padding-bottom','5px');
                } else {
                    $(element).addClass('active_sn');
                }
            } else if (!altcont) {
                $(element).removeClass('active').removeClass('active_sn');
            }
        });

        var completeFunc = function(ajax) {
            if (window.curajaxtarget == target.href) {
                // fill container and eval() any scripts
                container[0].innerHTML = ajax.responseText;
                $('script', container).each(function (index, element) {
                    $(element).appendTo('<div>'); // evaluate inline javascript
                });

                if (cur_hash) {
                    if (update_path) {
                        oldloc = cur_hash;
                        window.location.hash = cur_hash; // update hash path for selected target

                        // provide special handling for IE utilizing iframe so deep-linking works properly
                        if ($.browser.msie) {
                            var form = $('#iefrm')[0];
                            form.path.value = cur_hash.substr(1);
                            form.submit();
                        }
                    }
                    
                    // google analytics tracking
                    if (window.pageTracker) window.pageTracker._trackPageview(cur_hash.substr(1));
                }

                // override new links so they run through ajax
                override_links(container);
                window.curajaxtarget = null;
            }
        }

        if (!data) { // run ajax request
            $.ajax({
                url: target.href,
                type: 'GET',
                cache: false,
                complete: completeFunc 
            });
        } else { // data provided
            completeFunc({responseText: data});
        }
    }
    return false;
}

// handles the necessary action for ajax linking
function handle_link(element) {
    var relpath = rel_path(element.href);
    var parts = relpath.split(/\//);
    if (parts[0]) {
        window.scrollTo(0,0); // jump to top of window for every click, in hopes of helping users with lower resolutions

        var row = $('#btn_' + parts[0] + (window.floral ? '_fl' : '') +' h3.toggler');
        if (row.length) show_row(row[0]);
    }

    return run_ajax_link(element, null, null, true, true);
}

// overrides links to load via ajax into appropriate container
function override_links(container) {
    // if container is null, then it's page_load and we are overriding all links on rows and any items of week (bottom) links
    var parent = !container ? $("h3.toggler, .short_middle, #contactlnk") : container;
    parent.each(function (index, element) {
        $("a[rel='ajax']", element).not('#floral_link').click(function (e) { // you'll notice here we ignore industries->floral link as it has a special use elsewhere
            return handle_link(this);
        });
    });

    // overwrite cross_domain links so google analytics can track between floral and industrial site
    if (typeof set_cdtrack == 'function') set_cdtrack();
}

var top_image_links = new Array();
var top_image_images = new Array();
var top_image_widths = new Array();
var top_image_heights = new Array();
var top_image_background_images = new Array();
var current_image_number = 1;

function update_top_image(image_number) {
	$("#top_image").css("background-image", "url(" + top_image_background_images[image_number] + ")");
	$("#top_image_tag").attr("src", top_image_images[image_number]);
	$("#top_image_tag").attr("width", top_image_widths[image_number]);
	$("#top_image_tag").attr("height", top_image_heights[image_number]);
	$("#top_image_link").attr("href", top_image_links[image_number]);

	var num_images = top_image_images.length;
	for (var i = 1; i <= num_images; i++) {
		$("#top_image_link_" + i).removeClass("top_image_number_active");
		$("#top_image_link_" + i).addClass("top_image_number");
	}

	//$("#top_image_link_" + current_image_number).removeClass("top_image_number_active");
	//$("#top_image_link_" + current_image_number).addClass("top_image_number");

	$("#top_image_link_" + image_number).removeClass("top_image_number");
	$("#top_image_link_" + image_number).addClass("top_image_number_active");

	current_image_number = image_number;
}

var top_image_rotation_delay = 7000;
function auto_rotate_top_image() {
	
	current_image_number++;

	if (current_image_number >= top_image_images.length)
		current_image_number = 1;

	//alert(top_image_images.length);

	//alert(current_image_number);

	update_top_image(current_image_number);

	setTimeout("auto_rotate_top_image();", top_image_rotation_delay);
}

var current_product_id = null;
var product_image_rotation_timer = null;
var product_images = new Array();
function rotate_product_image(product_id) {
	clearTimeout(product_image_rotation_timer);

	if (!product_images || typeof(product_images[product_id]) == "undefined")
		return false;

	if (product_images[product_id].length <= 1)
		return false;

	// prevent image from fading out permanently
	if (current_product_id && product_id != current_product_id)
		$('#product_' + current_product_id).fadeIn(500);

	current_product_id = product_id;

	if (!current_image_index_for_product_id[current_product_id])
		current_image_index_for_product_id[current_product_id] = 0;

	current_image_index_for_product_id[current_product_id]++;

	if (current_image_index_for_product_id[current_product_id] >= product_images[current_product_id].length)
		current_image_index_for_product_id[current_product_id] = 0;

	var product_opacity = $("#product_" + current_product_id).css("opacity");
	// fade out product, fade in alternate product
	if (product_opacity > 0.9 || ($("#product_" + current_product_id).css("display") == null && product_opacity == null)) {
		$("#product_" + current_product_id).fadeTo(1000, 0.01);

		$('#alternate_product_' + current_product_id).attr('src',product_images[current_product_id][current_image_index_for_product_id[current_product_id]]);
		$('#alternate_product_' + current_product_id).fadeTo(1000, 1);

	}
	// fade out alternate product, fade in product
	else {
		$("#alternate_product_" + current_product_id).fadeTo(1000, 0.01);

		$('#product_' + current_product_id).attr('src',product_images[current_product_id][current_image_index_for_product_id[current_product_id]]);
		$('#product_' + current_product_id).fadeTo(1000, 1);

	}

	//setTimeout("$(\'#product_' + current_product_id).attr('src',product_images[current_product_id][current_image_index_for_product_id[current_product_id]]); $(\'#product_' + current_product_id).fadeIn(500);", 500);


	product_image_rotation_timer = setTimeout("rotate_product_image(current_product_id);", 1500);
}

function stop_rotate_product_image(product_id) {
	clearTimeout(product_image_rotation_timer);
}

$(document).ready(function(){
    // redirect to siteroot if landing page isn't that
    // we will apply hash ajax tracking accordingly
    var rp = rel_path(window.location.pathname);
    if (rp.replace(/(\s)+/g, '') != '' || window.location.search.match(/&__ut*/gi)) {
        var cur_hash = window.location.hash;
        if (!cur_hash) cur_hash = '#';
        if (cur_hash == '#') {
            window.location = window.siteroot + '?index#/' + rp;
        }
    }

    // define sitewide constant
    floral = $('#btn_about_fl').length > 0;

    // activate accordion
    $('#content').Accordion({
		active: false,
		header: 'h3.toggler',
        selectedClass: '',
		alwaysOpen: false,
		animated: true,
		showSpeed: 400,
		hideSpeed: 400
	})

    // handle when row is clicked
    .bind("beforeclick", function(event, clicked, active, toShow, toHide) {
        if (toShow[0] != toHide[0]) { // row expanding for first time
            // set visibility on row links / logo
            window.selrow = clicked[0];
            set_links(window.selrow);
        } else { // row selected again, collapse
            set_links(null);
            selrow = null;
            oldhash = '#/';
            oldloc = null;
            window.location.hash = '#/';
            document.title = 'Temkin: ' + (window.floral ? 'Floral Packaging' : 'Flexible Film Packaging');

            // provide special handling for IE utilizing iframe so deep-linking works properly
            if ($.browser.msie) {
                var form = $('#iefrm')[0];
                form.path.value = '';
                form.submit();
            }
        }

        // always clear content of collapsing div to help rendering performance
        toHide.html('');
    })

    // handle when row is selected (not just clicked)
    .bind("rowselect", function(clicked, active, toShow, toHide) {
        // execute main link on active row
        if (window.selrow && active.length) {
            run_ajax_link($("a[rel='ajax']:eq(0)", active[0])[0]);
        }
    });

    // set toggler section rows as a pointer mouse style
    // we do this in javascript because we must default to normal mouse cursor when javascript is disabled;
    // the rows are not clickable at that time
    $('div.main_nav').each(function(index, element) {
        $(element).css('cursor', 'pointer');
        $(element).parent().css('cursor', 'pointer'); // .toggler
    });

    // override menus for ajax
    set_links(null); // clear all link/logo visibility
    override_links();

    // override legal info, video, and floral links to show in lightbox
    setup_popups();

    // override search form handler for ajax
    setup_search();

    // handle focus events for search box
    $('.search_val').focus(function() {
        if (this.value.replace(/\s+/g,'').toLowerCase() == 'search') this.value = '';
    }).blur(function() {
        if (this.value.replace(/\s+/g,'') == '') this.value = 'Search';
    });


    // setup iframe for use in deep-linking method on IE
    if ($.browser.msie) {
        $('BODY').append('<iframe id="ieifrm" name="ieifrm" src="about:blank" style="height: 0; width: 0; display: none" />' +
            '<form id="iefrm" action="' + window.siteroot + 'js/blank.htm" target="ieifrm"><input type="hidden" name="path" /></form>');
    }

    // enable ajax deep-linking monitor
    setInterval('poll_location()', 200);
});

