'use strict';



// Helper Functions
var calcOffset = (/*@cc_on!@*/false && !document.querySelectorAll) ?
    (function () {
        function getParent(elem) {
            var style;
            do {
                style = elem.currentStyle || getComputedStyle(elem, null);
                style = style.position;
                if (style === 'relative') {
                    return elem;
                }
                elem = elem.offsetParent;
            } while (elem);
        }

        return function (elem) {
            var parent = getParent(elem),
                top = 0,
                left = 0;

            do {
                top += elem.offsetTop;
                left += elem.offsetLeft;
                elem = elem.offsetParent;
            } while (elem !== parent)

            return [left, top];
        };
    }()) : function (elem) {
        return [elem.offsetLeft, elem.offsetTop];
    };



var getWindowHeight = window.innerHeight ? function () {
    return window.innerHeight;
} : function () {
    return document.documentElement.clientHeight;
};



function setOpacity(elem, percent) {
    elem.style.opacity = percent;
    elem.style.filter = 'alpha(opacity=' + percent * 100 + ')';
}



var surefireAddDOM = (function () {
    var script = document.getElementsByTagName('script')[0],
        parent = script.parentNode;
    
    return function (elem) {
        parent.insertBefore(elem, script);
    };
}());



var rot13Email = (function () {
    function rotate(a) {
        var x = a <= 'Z' ? 90 : 122,
            y = a.charCodeAt(0) + 13;
        
        a = x >= y ? y : y - 26;
        return String.fromCharCode(a);
    }

    return function (elem, rot13, label) {
        var a = document.createElement('a');
        rot13 = rot13.replace(/[a-zA-Z]/g, rotate);

        a.href = 'mailto:' + rot13;
        a.innerHTML = label || rot13;
        elem.innerHTML = '';
        elem.appendChild(a);
    };
}());



var addCSSRule = (function () {
    var sheet = document.styleSheets;
    if (sheet.length) {
        sheet = sheet[0];
    } else {
        sheet = document.createElement('style');
        surefireAddDOM(sheet);
    }

    return sheet.addRule ? function (selector, declarations) {
        sheet.addRule(selector, declarations);
    } : function (selector, declarations) {
        selector += '{' + declarations + '}';
        sheet.insertRule(selector, sheet.cssRules.length);
    }
}());



// Events
var moira = window.addEventListener ? {
    add: function (elem, type, method) {
        elem.addEventListener(type, method, false);
    },
    remove: function (elem, type, method) {
        elem.removeEventListener(type, method, false);
    }
} : (function () {
    var cache = [],
        purge = function () {
            var i = cache.length,
                current;
            window.detachEvent('onunload', purge);
            while (i) {
                i -= 1;
                current = cache[i];
                current[0].detachEvent(current[1], current[2]);
            }
        };
    
    window.attachEvent('onunload', purge);
    return {
        add: function (elem, type, method) {
            type = 'on' + type;
            cache[cache.length] = [elem, type, method];
            elem.attachEvent(type, method);
        },
        remove: function (elem, type, method) {
            elem.detachEvent('on' + type, method);
        }
    }
}());



// Classes
var eidos = {
    has: function (elem, classy) {
        classy = new RegExp('\\b' + classy + '\\b');
        return classy.test(elem.className);
    },
    get: document.getElementsByClassName ? function (classy) {
        return document.getElementsByClassName(classy);
    } : function (classy) {
        var elems = document.getElementsByTagName('*'),
            i = elems.length,
            matched = [],
            current;
        
        while (i) {
            i -= 1;
            current = elems[i];
            if (eidos.has(current, classy)) {
                matched[matched.length] = current;
            }
        }

        return matched;
    },
    add: function (elem, classy) {
        if (elem.className) {
            if (!eidos.has(elem, classy)) {
                elem.className += ' ' + classy;
            }
        } else {
            elem.className = classy;
        }
    },
    remove: function (elem, classy) {
        classy = new RegExp('(^| )' + classy + '( |$)');
        elem.className = elem.className.replace(classy, '$1');
        elem.className = elem.className.replace(/ $/, '');
    }
};



// Animation
var dunamis = (function (Math) {
    var PI = Math.PI,
        cos = Math.cos;
    
    return function (total_time, update, after) {
        var start_time = +new Date(),
            end_time = start_time + total_time,
            timer = setInterval(function () {
                var current_time = +new Date(),
                    current_distance;
                
                current_time = current_time > end_time ? 1 :
                    (current_time - start_time) / total_time;
                
                current_distance = (1 - cos(current_time * PI)) / 2;
                update(current_distance);

                if (current_time === 1) {
                    clearInterval(timer);
                    if (after) {
                        after();
                    }
                }
            }, 40);
        
        return timer;
    }
}(Math));



// Cookie Functions
var cookies = (function (document) {
    function dateString(days) {
        var now = +new Date();
        days *= 24 * 60 * 60 * 1000;
        now = new Date(now + days);
        return now.toGMTString();
    }

    return {
        bake: function (name, value, days) {
            var expires = days ? '; expires=' + dateString(days) : '';
            document.cookie = name + '=' + value + expires + '; path=/';
        },
        serve: function (name) {
            var cookies = document.cookie.split('; '),
                i = cookies.length,
                current;
            name += '=';

            while (i) {
                i -= 1;
                current = cookies[i];
                if (current.indexOf(name) === 0) {
                    return current.substring(name.length, current.length);
                }
            }
        },
        toss: function (name) {
            var expires = dateString(-1);
            document.cookie = name + '=; expires=' + expires + '; path=/';
        }
    }
}(document));



/* -------------------------------------------------------------------------- */



// IE6 PNG Fix
if (window.DD_belatedPNG) {
    DD_belatedPNG.fix('.hdr_a, .main_nav_a');
}



// Auto-Expanding Body
var autoexpandstuff = (function () {
    var hdr = eidos.get('hdr')[0],
        ftr = eidos.get('ftr')[0],
        body = eidos.get('body_offset')[0],
        offsetter = document.createElement('div');
    
    offsetter.className = 'offset_equalizer';
    addCSSRule('.' + offsetter.className, 'background-color:white;' +
        'width:990px; margin:0 auto');
    document.body.appendChild(offsetter);
    
    return function () {
        var w = window.innerHeight ||
                document.documentElement.clientHeight,
            a = hdr.offsetHeight + ftr.offsetHeight,
            h = body.offsetHeight,
            x = w - a - h;
        
        offsetter.style.height = x > 0 ? x + 'px' : 'auto';
    };
}());
moira.add(window, 'load',   autoexpandstuff);
moira.add(window, 'resize', autoexpandstuff);



// Search Text stuff
(function (eidos) {
    var input = eidos.get('search_input')[0],
        default_class = 'default',
        default_value = input.value,
        value_changer = function (current) {
            var focus = current.type === 'focus';
            current = input.value;
            
            if (focus && current === default_value) {
                input.value = '';
                eidos.remove(input, default_class);
            } else if (!focus && !current) {
                input.value = default_value;
                eidos.add(input, default_class);
            }
        };
    
    moira.add(input, 'focus', value_changer);
    moira.add(input, 'blur', value_changer);
    eidos.add(input, default_class);
}(eidos));



// Footer E-Mail Address
(function () {
    var span = eidos.get('footer_email')[0],
        email = 'qrnap@zhygvsno-vap.pbz';
    rot13Email(span, email);

    span = eidos.get('other_email');
    if (span.length) {
        rot13Email(span[0], email);
    }
}());



// Industry Home Page Animations
var as = (function (document) {
    var get = function (id) {
            return document.getElementById('qapla-' + id);
        },
        test = get('engineering');
    return test ? [
        test,
        get('tooling'),
        get('plastic'),
        get('cnc-trimming'),
        get('assembly'),
        get('sewing'),
        get('quality')
    ] : [];
}(document));
var shablagoo = (function () {
    function initImgList(styles, list) {
        var src = styles.backgroundImage,
            beginning = src.indexOf('h'),
            ending = beginning === 5 ? -2 : -1;
        
        ending += src.length;
        src = src.substring(beginning, ending);
        list.unshift(src);
        list.push(src);
        return list;
    }
    function initWordList(words, x, y, multiplier) {
        var list = [],
            flying_class = 'flying_word',
            i = words.length,
            str_x = x + 'px',
            str_y = y + 'px',
            current,
            offsets,
            styles;

        addCSSRule('.' + flying_class, 'position:absolute');
        while (i) {
            i -= 1;
            current = words[i];
            offsets = calcOffset(current);
            styles = current.currentStyle || getComputedStyle(current, null);
            styles = styles.fontSize;
            styles = {
                size: parseFloat(styles),
                unit: styles.replace(/^[-\d\.]+/, '')
            };
            styles.new_size = styles.size * multiplier;

            list[i] = {
                elem: current,
                total_x: x - offsets[0],
                total_y: y - offsets[1],
                start_font: styles.new_size,
                total_font: styles.size - styles.new_size,
                font_unit: styles.unit
            };

            eidos.add(current, 'hidden');
            setOpacity(current, 1);
            eidos.add(current, flying_class);
            current.style.fontSize = styles.new_size + styles.unit;
            current.style.left = str_x;
            current.style.top = str_y;
        }

        return list;
    }
    function initSpans(elem, count, width) {
        var elem_height = elem.clientHeight + 'px',
            classy = 'blind_span',
            spans = [],
            span;

        addCSSRule('.' + classy, 'position:absolute; top:0;' +
            'background-repeat:no-repeat; height:' + elem_height);
        while (count) {
            count -= 1;
            spans[count] = span = document.createElement('span');
            span.className = classy;
            span.style.left = width * count + 'px';
            span.style.backgroundPosition = '-' + span.style.left + ' top';
            elem.appendChild(span);
        }

        return spans;
    }

    function setSpanBackgrounds(current, imgs, spans) {
        var src = 'url(' + imgs[current + 1] + ')',
            i = spans.length,
            current;
        
        while (i) {
            i -= 1;
            current = spans[i].style;
            current.width = 0;
            current.backgroundImage = src;
        }
    }

    function updateSpans(distance, spans, width) {
        var i = spans.length;
        width = Math.ceil(distance * width) + 'px';
        while (i) {
            i -= 1;
            spans[i].style.width = width;
        }
    }
    function updateWord(distance, data, x, y) {
        var styles = data.elem.style;
        styles.left = (x - data.total_x * distance) + 'px';
        styles.top = (y - data.total_y * distance) + 'px';
        styles.fontSize = (data.start_font + data.total_font * distance) +
            data.font_unit;
    }

    function removeSpans(elem, spans) {
        var i = spans.length;
        while (i) {
            i -= 1;
            elem.removeChild(spans[i]);
        }
    }
    
    return function (elem, other_imgs, words) {
        var spans_count = 15,
            font_multiplier = 5,
            transition = 1400,
            chill = 1000,
            start_x = 650,
            start_y = 200,

            elem_styles = elem.currentStyle || getComputedStyle(elem, null),
            imgs = initImgList(elem_styles, other_imgs),
            word_data = initWordList(words, start_x, start_y, font_multiplier),

            span_width = elem.clientWidth / spans_count,
            spans = initSpans(elem, spans_count, span_width),

            current_img = 0,
            current_word = 0,
            imgs_count = imgs.length,
            words_count = word_data.length,
            last_img = imgs_count - 1,

            update = function () {
                var word_datum = word_data[current_word],
                    word = word_datum ? word_datum.elem : false,
                    method = word_datum ? function (distance) {
                        updateSpans(distance, spans, span_width);
                        updateWord(distance, word_datum, start_x, start_y);
                    } : function (distance) {
                        updateSpans(distance, spans, span_width);
                    },
                    after = word ? function () {
                        eidos.remove(word, 'flying_word');
                        word.style.left = word.style.top = 0;
                        reset();
                    } : reset;
                if (word) {
                    eidos.remove(word, 'hidden');
                    dunamis(transition, method, after);
                }
            },

            wait = function () {
                setSpanBackgrounds(current_img, imgs, spans);
                setTimeout(update, chill);
            },

            reset = function () {
                current_img += 1;
                current_word += 1;

                if (current_img < imgs_count) {
                    elem.style.backgroundImage = 'url(' +
                        imgs[current_img] + ')';
                    
                    if (current_img < last_img) {
                        wait();
                    } else {
                        removeSpans(elem, spans);
                    }
                }
            };
        
        wait();
    }
}());

function industrysetupstuff(percent) {
    var i = as.length;
    percent = 1 - percent;
    while (i) {
        i -= 1;
        setOpacity(as[i], percent);
    }
}

function industryanimatestuff() {
    var img_lists = {
            aviation: [ '../../images/photos/industry/Design.gif',
                          '../../images/photos/industry/Tooling.jpg',
                          '../../images/photos/industry/Plastic.jpg',
                          '../../images/photos/industry/Trimwork.jpg',
                          '../../images/photos/industry/Assembly.jpg',
                          '../../images/photos/industry/Sewing.jpg',
                          '../../images/photos/industry/Quality.jpg' ],
            medical: [ '../../images/photos/industry/Design.gif',
                          '../../images/photos/industry/Tooling.jpg',
                          '../../images/photos/industry/Plastic.jpg',
                          '../../images/photos/industry/Trimwork.jpg',
                          '../../images/photos/industry/Assembly.jpg',
                          '../../images/photos/industry/Sewing.jpg',
                          '../../images/photos/industry/Quality.jpg' ],
            commercial: [ '../../images/photos/industry/Design.gif',
                          '../../images/photos/industry/Tooling.jpg',
                          '../../images/photos/industry/Plastic.jpg',
                          '../../images/photos/industry/Trimwork.jpg',
                          '../../images/photos/industry/Assembly.jpg',
                          '../../images/photos/industry/Sewing.jpg',
                          '../../images/photos/industry/Quality.jpg' ]
        },
        theater = eidos.get('industry_filmstrip')[0],
        img_list = eidos.has(theater, 'industry_aviation') ? 'aviation' :
                   eidos.has(theater, 'industry_commercial') ? 'commercial' :
                   'medical';
        
    shablagoo(theater, img_lists[img_list], as);
}

if (as.length) {
    (function () {
        var path = location.pathname.split('/'),
            i = path.length - 1;
        path = path[i] ? path[i] : path[i - 1];

        if (!cookies.serve(path)) {
            //cookies.bake(path, '1', 7);
            dunamis(3000, industrysetupstuff, industryanimatestuff);
        }
    }());
}
