
/**
 *
 * @desc        GW Lib + FX (Opacity)
 * @author      Christopher Sanford
 * @version     1.0.0
 * @copyright   (cc) 2006 Christopher Sanford
 * @url         http://www.christophersanford.com/
 * @url         http://www.lethal-labs.com/
 * 
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General 
 * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) 
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to 
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

if (!Object.clone) {
    Object.prototype.clone = function()
    {
	   var clone = new Object();
	   if (typeof arguments.length != 'undefined') {
	       var args = arguments;
	       for (var t in this) {
	           for (var a = 0, ac = args.length; a < ac; a++) {
	               if (typeof args[a] != 'string') continue;
	               if (t.toLowerCase() != args[a].toLowerCase()) {
	                   clone[t] = this[t];
	               }
	           }
	       }
	   } else {
	       for (var t in this) {
	           clone[t] = this[t];
	       }
	   }
	   return clone;
    };
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/, '');
};
String.prototype.rtrim = function()
{
    return this.replace(/\s+$/, '');
};
String.prototype.ltrim = function()
{
    return this.replace(/^\s+/, '');
};

var GW = Class.create();
GW.prototype = {
	initialize: function() { return true; }
};

GW.url = 'http://www.precision-autosports.com/site/template/';
GW.self = 'index';

GW.Event = function() { return true; };
GW.Event.prototype = {
	initialize: function() { return true; },
	setEvent: function(obj, event, func)
	{
		var ref = null;
		if (typeof obj == 'string') {
			try {
				ref = eval(obj) ? obj+'.'+event : '$("'+ obj +'").'+event;
			} catch(e) {
				ref = '$("'+ obj +'").'+event;
			}
		} else if (typeof obj == 'object') {
			if (obj.id) {
				return this.setEvent(obj.id, event, func);
			} else {
				var id = this.getRandomId();
				while ($(id)) id = this.getRandomId();
				obj.id = id;
				return this.setEvent(id, event, func);
			}
		}
		try {
			var event = eval(ref);
			if (typeof event == 'function') {
				ref += ' = function(e) { event(e); func(e); }';
			} else {
				ref += ' = func;';
			}
			ref = eval(ref);
		} catch (e) { return null; }

		return (ref);
	},
	getRandomId: function()
	{
		return 'obj-'+Math.floor(Math.random()*1000);
	},
	getTarget: function(event)
	{
		event = (typeof event == 'undefined') ? window.event : event;
		var target = (event && typeof event.target == 'undefined') ? event.srcElement : event.target;
		if (target && target.nodeType == 3) target = target.parentNode;
		return (target) ? target : null;
	}
};

var FX = function() { return true; };
FX.prototype = {
	combo: false,
	timer: null,
	interval: 10,
	tween: 7,
	value: 0,
	sized: false,
	initialize: function(props) {
		this.extend(props || {});
		this.targ = (props.targ) ? $(props.targ) : $(props.trig);
		this.setValue(this.min);
		var obj = this;
		if (props.evt) {
			(new GW.Event()).setEvent(props.trig, props.evt, function(e) {
	           obj.toggle();
	           return false;
			});
		}
	},
    toggle: function()
    {
	   if (this.timer) return false;
	   if (this.combo) {
		    if (this.timers()) return false;
			this.iterate();
	   }
		this.sized = (this.sized) ? false : true;
		this.animate();
    },
	animate: function()
	{
		var value = this.getValue();
		if (this.timer) {
			if (value < this.value) {
			   value = Math.ceil(value+((this.value-value)/this.tween));
				this.setValue((value<this.value) ? value : this.value);
			} else if (value > this.value) {
				value = Math.floor(value-((value-this.value)/this.tween));
				this.setValue((value>this.value) ? value : this.value);
			} else {
				this.timer = clearInterval(this.timer);
				return;
			}
		} else {
			var value = this.getValue();
			this.value = (value < this.max) ?
						((this.max-this.min)+value) :
						((0-(this.max-this.min))+value);
			if (this.value < this.min) this.value = this.min;
			this.timer = setInterval(this.animate.bind(this), this.interval);
		}
	}
};

FX.Opacity = Class.create();
FX.Opacity.prototype = (new FX()).extend({
	attrib: 'opacity',
	initialize: function(props)
	{
		this.extend(props || {});
		this.targ = (props.targ) ? $(props.targ) : $(props.trig);
		this.tween /= .5;
		this.max = ((this.combo) ? 99 : (this.max >= 99 ? 99 : this.max));
		this.min = ((this.combo) ? 0 : (this.min <= 0 ? 0 : this.min));
		this.setValue(this.min);
		var obj = this;
		if (props.evt) {
			(new GW.Event()).setEvent(props.trig, props.evt, function(e) {
	           obj.toggle();
	           return false;
			});
		}
	},
	getValue: function()
	{
		if (window.ActiveXObject) {
			return parseInt(this.targ.style.filter.replace(/\D+/, ''));
		} else {
			return this.targ.style.opacity*100;
		}
	},
	setValue: function(value)
	{
		if (window.ActiveXObject) {
			this.targ.style.filter = "alpha(opacity=" + value + ")";
		} else {
			this.targ.style.opacity = value/100;
		}
	}	
});

/**
 *  GW Flash Object
 *
 *  Info:
 *      -Dynamically writes in Flash    
 *
 */

GW.Flash = {

    setObject: function(element, params)
    {
	   if (document.getElementById) {
	       var flash = '';
	       element = document.getElementById(element);
	       GW.Params.setParams(params);
	       params = GW.Params.getParams();
	       params['movie'] = params['src'];
	       flash += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ params['width'] +'" height="'+ params['height'] +'">';
	       for (var p in params) { if (p.match(/name|swliveconnect/i) || typeof params[p] != 'string') continue; flash += '<param name="'+ p +'" value="'+ params[p] +'" />'; }
	       flash += '<embed type="application/x-shockwave-flash" src="'+ params['src'] +'" width="'+ params['width'] +'" height="'+ params['height'] +'" name="'+ params['name'] +'" wmode="'+ params['wmode'] +'"';
	       flash += '></embed>';
	       flash += '</object>';
	       element.innerHTML = flash;
	       flash = null;
	   }
	   return;
    }
};

/**
 *  GW Window Object
 *
 *  Info:
 *      -Creates / Maintains Popups
 *      -Centers Window
 *      -Maintains Focus
 *
 */

GW.Window = {
    win: null,
    height: 0,
    width: 0,
    target: '',
    modal: false,
    image: false,
    interval: 5,
    timer: 0,
    setWinByElement: function(id, params)
    {
        var evt = new GW.Event();
        evt.setEventById(id, 'onclick', function (e) {
            GW.Params.setParams(params);
            GW.Window.target = GW.Params.getParam('src');
            this.image = GW.Params.getParam('image');
            if (!this.image) {
                this.image = GW.Params.getParam('src').match(/\.jpg$|\.jpeg$|\.gif$|\.png$/i) ? true : false;
            }
            GW.Window.modal = (GW.Params.getParam('modal')) ? true : false;
            GW.Window.setCenter();
            GW.Window.openWindow();
            return false;
        });
    },
    popupWindow: function(params)
    {
        GW.Params.setParams(params);
        this.target = GW.Params.getParam('src');
        this.image = GW.Params.getParam('image');
        if (!this.image) {
            this.image = GW.Params.getParam('src').match(/\.jpg$|\.jpeg$|\.gif$|\.png$/i) ? true : false;
        }
        this.modal = parseInt(GW.Params.getParam('modal')) ? true : false;
        GW.Window.setCenter();
        GW.Window.openWindow();
    },
    openWindow: function()
    {
        if (this.image) {
            if (this.win != null && !this.win.closed) {
                if (this.win.document &&
                    this.win.document.images &&
                    this.win.document.images.length) {
                    var image = this.win.document.images[0];
                    image.src = this.target;
                    image.height = GW.Params.getParam('height');
                    image.width = GW.Params.getParam('width');
                    setTimeout('GW.Window.sizeWindow()', 200);
                } else {
                    this.win.close();
                    this.win = window.open('', 'GW', GW.Params.getParams(true));
                    setTimeout('GW.Window.writeWindow()', 200);
                }                 
            } else {
                this.win = window.open('', 'GW', GW.Params.getParams(true));
                setTimeout('GW.Window.writeWindow()', 200);
                this.centerWindow();
            }
        } else {
            if (this.win != null && !this.win.closed) {
                 this.win.location = this.target;
                 this.win.resizeTo(GW.Params.getParam('width'), GW.Params.getParam('height'));
            } else {
                this.win = window.open(this.target, 'GW', GW.Params.getParams(true));
                this.centerWindow();
            }
        }
        if (this.modal) {
            this.timer = setInterval('GW.Window.focusWindow()', 50);
        } else {
            this.win.focus();
        }
        return;
    },
    writeWindow: function()
    {
        try {
            var html = '';
            this.win.document.open();
            html += '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">';
            html += '<html>';
            html += '<head>';
            html += '<title></title>';
            html += '<style type="text/css">';
            html += 'html, body { margin: 0; padding: 0; }';
            html += '</style>';
            html += '</head>';
            html += '<body>';
            html += '<img src="'+this.target+'" height="'+GW.Params.getParam('height')+'" width="'+GW.Params.getParam('width')+'" />';
            html += '</body>';
            html += '</html>';
            this.win.document.write(html);
            this.win.document.close();
            setTimeout('GW.Window.sizeWindow()', 200);
            return;
        } catch(e) { return false; }
    },
    sizeWindow: function()
    {
        try {
            var width = GW.Params.getParam('width');
            var height = GW.Params.getParam('height');
            var div = this.win.document.createElement('div');
            div.appendChild(this.win.document.createTextNode(' '));
            div.style.position = 'absolute';
            div.style.width = '0px';
            div.style.height = '0px';
            div.style.right = '0px';
            div.style.bottom = '0px';
            this.win.document.body.appendChild(div);
            width -= parseInt(div.offsetLeft);
            height -= parseInt(div.offsetTop);
            this.win.resizeBy(width,height);
            this.win.document.body.removeChild(div);
            this.win.focus();
            return;
        } catch(e) { return false; }
    },
    setCenter: function()
    {
        var height = parseInt(GW.Params.getParam('height'));
        var width = parseInt(GW.Params.getParam('width'));
        GW.Params.setParam('left', ((screen.width-width)/2));
        GW.Params.setParam('top', ((screen.height-height)/2));
        return;
    },
    centerWindow: function()
    {
        this.setCenter();
        this.win.moveTo(GW.Params.getParam('left'), GW.Params.getParam('top'));
        return;
    },
    focusWindow: function()
    {
        if (this.win.closed || this.win == null) {
            clearInterval(this.timer);
        } else {
            if (this.win.focus) {
                this.win.focus();
            }
        }
        return;
    }
};

/**
 *  GW Params Object
 *
 *  Info:
 *      Takes a param / list of params: "height=50, width=50"
 *      Standardizes params (trims & strtolower)
 *      Returns single param / formatted list
 */

GW.Params = {
    params: {},
    setParams: function(params)
    {
        this.params = {};
        var temp = [];
        temp = params.split(/\s*,\s*/);
        for (var t = 0, c = temp.length; t < c; t++) {
            temp[t] = temp[t].split(/\s*=\s*/);
            if (temp[t].length == 2) {
                temp[t][0] = temp[t][0].trim();
                temp[t][1] = temp[t][1].trim();
                temp[t][0] = temp[t][0].toString().toLowerCase();
                this.params[temp[t][0]] = temp[t][1];
            } else if (temp[t].length > 2) {
                var key = temp[t].shift();
                key = key.trim();
                temp[t] = temp[t].join('=');
                this.params[key] = temp[t];
            }
        }
        temp = null;
    },
    setParam: function(key, value)
    {
        this.params[key] = value;
        return;
    },
    getParams: function(format)
    {
        if (typeof format != 'undefined' && format) {
            var params = [];
            for (var p in this.params) {
                if (params.push) {
                    params.push(p+"="+this.params[p]);
                } else {
                    params[params.length] = p+"="+this.params[p];
                }
            }
            params = params.join(', ');
            return params;
        } else {
            return this.params;
        }
    },
    getParam: function(key)
    {
        return (typeof this.params[key] != 'undefined') ? this.params[key] : null;
    }
};

var thumb_div = document.createElement('div');
var thumb_img = document.createElement('img');
var thumb_pre = [];
var thumb_timer = 0;

function load_hovers()
{
    var div = document.getElementById('thumbs-wrap');
    if (!div || typeof div == 'undefined') return;
    thumb_div.id = 'div-hover';
    thumb_img.id = 'img-hover';
    thumb_div.appendChild(thumb_img);
    document.body.appendChild(thumb_div);
    thumb_img.onload = function()
    {
        thumb_timer = setTimeout(function() {
            thumb_div.style.visibility = 'visible';
            this.style.visibility = 'visible';
        }.bind(this), 50);
    };
    thumb_img.onerror = function()
    {
        thumb_div.style.visibility = 'hidden';
        this.style.visibility = 'hidden';
    };
    var kids = div.childNodes;
    for (var k = 0, c = kids.length; k < c; k++) {
        if (kids[k].tagName &&
            kids[k].tagName.toUpperCase()=='A') {
            var first = kids[k].firstChild;
            if (first.tagName &&
                first.tagName.toUpperCase()=='IMG') {
                var img = new Image();
                var id = first.src.replace(/\S*s=(\d+)\S*/, '$1');
                img.src = first.src.replace('s='+id, 's=3');
                thumb_pre.push(img);
                first.onmouseover = function()
                {
                    var id = this.src.replace(/\S*s=(\d+)\S*/, '$1');
                    thumb_img.src = this.src.replace('s='+id, 's=3');
                    if (this.captureEvents) this.captureEvents(Event.MOUSEMOVE);
                    this.onmousemove = hover_event;
                };
                first.onmouseout = function()
                {
                    clearTimeout(thumb_timer);
                    thumb_div.style.visibility = 'hidden';
                    thumb_img.style.visibility = 'hidden';
                    if (this.releaseEvents) this.releaseEvents(Event.MOUSEMOVE);
                    this.onmousemove = null;
                };
            }
        }
    }
}

function hover_event(e)
{
    var pos_x = (e) ? e.pageX : window.event.clientX + document.body.scrollLeft;
    var pos_y = (e) ? e.pageY : window.event.clientY + document.body.scrollTop;
    thumb_div.style.left = (pos_x+15)+'px';
    thumb_div.style.top = (pos_y-150)+'px';
}

var evt = new GW.Event();
evt.setEvent('window', 'onload', function()
{

    // set min height
    var span = document.createElement('span');
    span.className = 'ot';
    var obj = document.getElementById('wrap-b');
    obj.appendChild(span);
    var offset = parseInt(span.offsetTop);
    var min = 380;
    if (offset < min) obj.style.height = min+'px';
    document.getElementById('body').style.visibility = 'visible';

    // top right curve
    var img = document.createElement('img');
    img.id = 'trc';
    img.src = GW.url+'/images/gen/trc.gif';
    img.style.height = '5px';
    img.style.width = '5px';
    document.getElementById('body').appendChild(img);
    
    // sifr
    if (sIFR) {
        sIFR.replaceElement(named({sSelector:".box h1", sFlashSrc: GW.url+"/swf/sifr/HelvNeue67.swf", sColor:"#FFFFFF", sWmode:"transparent"}));
        sIFR.replaceElement(named({sSelector:"h1", sFlashSrc: GW.url+"/swf/sifr/HelvNeue67.swf", sColor:"#000000", sWmode:"transparent"}));
        sIFR.replaceElement(named({sSelector:".box h2", sFlashSrc: GW.url+"/swf/sifr/HelvNeue67.swf", sColor:"#FFFFFF", sWmode:"transparent"}));
        sIFR.replaceElement(named({sSelector:"h2", sFlashSrc: GW.url+"/swf/sifr/HelvNeue67.swf", sColor:"#2F3236", sWmode:"transparent"}));
        sIFR.replaceElement(named({sSelector:"h3", sFlashSrc: GW.url+"/swf/sifr/Helv57Cond.swf", sColor:"#222428", sWmode:"transparent"}));
    }
    
    // curves
    var boxes = document.getElementsByClassName('box');
    for (var b = 0, c = boxes.length; b < c; b++) {
        var tl = document.createElement('div');
        var tr = document.createElement('div');
        var bl = document.createElement('div');
        var br = document.createElement('div');
        tl.className = 'tl';
        tr.className = 'tr';
        bl.className = 'bl';
        br.className = 'br';
        var height = boxes[b].offsetHeight;
        var width = boxes[b].offsetWidth;
        if (height % 2 != 0) {
            height++;
            boxes[b].style.height = height+'px';
        }
        if (width % 2 != 0) {
            width++;
            boxes[b].style.width = width+'px';
        }
        boxes[b].appendChild(tl);
        boxes[b].appendChild(tr);
        boxes[b].appendChild(bl);
        boxes[b].appendChild(br);
        
        boxes[b].onmouseover = function()
        {
            Element.addClassName(this, 'hover');
        };

        boxes[b].onmouseout = function()
        {
            Element.removeClassName(this, 'hover');
        };
    }
    
    evt.setEvent('window', 'onunload', function() {
        if (document.forms['search']) {
            var value = document.forms['search'].q.value;
            if (value.match(/Enter Query/i)) {
                document.forms['search'].q.value = '';
            }
        }
    });

    load_hovers();
    GW.Flash.setObject('flash', 'src=http://www.precision-autosports.com/site/template/swf/hdr/header.swf?mov=./site/template/swf/hdr/index1.swf, name=flash_hdr, height=154, width=503, quality=high, wmode=transparent');

    // external links
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName('a');
	for (var a=0, c = anchors.length; a < c; a++) {
		if (anchors[a].href && anchors[a].rel && anchors[a].rel == 'external')
		anchors[a].target = '_blank';
	}

});
