var count = 0;

/* GURHAN */

var SCROLL_MULTIPLIER = 4;

$(function() {
	$('#main_nav ul').dropdownMenu();
	
	initialize();

	initializeCelebs();
	
	var current = 'a_' + $('input[name=subcategory]').val();
	
	$('a#'+current).addClass('select');
	
	// Browse navigation
	$('ul#jewels').browseMenu();
	
});

function initialize() {
	// var self = $('body');
	// 
	// if (self.attr('load') != undefined) {
	// 	self.optPopup(self.attr('load'), $(this).metadata());		
	// }
	
	// Initialize popup
	$('a[rel^=popup]').map(function() {
		$(this).optPopup($(this).attr('href'), $(this).metadata());
	});
				
	$('a[rel=ajax]').map(function() {
		$(this).ajaxLoad($(this).metadata());
	});
	
	$('div[id^=matchAssocProdDiv]').addClass('similar_products_tooltip').hide().append('<img src="http://optcentral.info/cssopt/styles/arrow.gif" width="15" height="8" class="arrow"/>');

	$('.m_thumb_con a').click(function() {
		$('div[id^=matchAssocProdDiv]').hide();
	});
	
	$('a.similar').mouseover(function() {
		$('div[id^=matchAssocProdDiv]:hidden').show().css('opacity', 0).animate({ bottom: 40, opacity: 1}, 500);
	})
	
	$('div.upperDiv').hover(function() {}, function() {
		$('div[id^=matchAssocProdDiv]:visible').animate({ bottom: 20, opacity: 0}, 200, function() { $(this).hide() });
	});
	
	$('.m_thumb_con a').each(function() {
		$(this).click(function() {
			prodId = $(this).attr('title');
			swapProd('prod' + prodId);
			
			var imageLink = "/popup.jsp?content=cat1Dim&comp=33&product=" + prodId;
			var printLink = "/print.jsp?content=print&product=" + prodId + "&login=gurhanwebsite&comp=33";
			
			$('a.image_link').each(function() {
				$(this).attr('href', imageLink).optPopup(imageLink, $(this).metadata());
			})
						
			$('a.print_link').attr('href', printLink).optPopup(printLink, $(this).metadata());
			
			return false;
		})
	});
		
	$('#new_this_season_thum').scroller($('#scrollerId'), $('#new_this_season_thum_right'), $('#new_this_season_thum_left'), { scrollMultiplier: 4 });	

	// CSS STYLING
	$('#new_this_season_content_right_nav li:last').css('background-image', 'none');
	
	if ($.browser.msie) {
		$('#main_nav ul li ul li:last-child').css('border-bottom', 'none');
	}
	
	// IE CSS STYLES
	if ($.browser.msie && $.browser.version.substr(0,1) < 7) {	
		$('div.formbox input[type=text]').css('margin', '.6em 0 1em 0').width(370).css('display', 'block');
	}
}


function initializeCelebs() {
	window.currentItem = $('#celebs_thumb_con a[title]:first').attr('title');
	
	$('#celebs .left_col div[id^=article]').each(function() {
		// alert($(this).attr('id').substr(7, 4));
		if ($(this).attr('id').substr(7, 4) != window.currentItem) {
			$(this).hide();
		};
	});
	
	$('#celebs .right_col div[id^=otherarticle]').each(function() {
		if ($(this).attr('id').substr(12, 4) != window.currentItem) {
			$(this).hide();
		};
	});
	
	$('#celebs .right_col div[id^=productarticle]').each(function() {
		if ($(this).attr('id').substr(14, 4) != window.currentItem) {
			$(this).hide();
		};
	});
	
	$('#celebs_thumb_con a[title]').each(function() {	
		$(this).click(function() {
			window.currentItem = $(this).attr('title');
			articleId = $(this).attr('title');

			$('#celebs .left_col div[id^=article]:visible').hide();
			$('#celebs .left_col div#article' + articleId).show();

			$('#celebs .right_col div[id^=otherarticle]:visible').hide();
			$('#celebs .right_col div#otherarticle' + articleId).show();
			
			$('#celebs .right_col div[id^=productarticle]:visible').hide();
			$('#celebs .right_col div#productarticle' + articleId).show();			
						
			return false;
		})
	});
	
	// Swap function
	$('#celebs_right_col_top img').click(function() {
		var thumbnail = $(this);
		var center = $('#celebs .left_col div[id^=article]:visible img');
		
		var temp = thumbnail.attr('src');
		
		thumbnail.attr('src', center.attr('src'));
		center.attr('src', temp)
	});
}

/* Plugin for the drop-down page menus */

(function($) {
	$.fn.dropdownMenu = function() {
		var menu = this;
		
		menu.find('li').mouseover(function() {
			// menu.children('li').find('ul').hid();
			$(this).children('ul').show();
			$(this).siblings().children('ul').hide();
		});
		
		menu.find('ul').mouseout(function() {
			$(this).hide();
		});
		
		// Fixed problem with z-index on dropdown
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			$('ul#navigation ul li a').each(function() {
				$(this).prepend('<span></span>').css('float', 'left');
			});
		}
		
		return this;
	};
})(jQuery);


/* A scroller plugin which is used on the New This Season Page */

(function($) {
	$.fn.tagName = function() {
	    return this.get(0).tagName;
	}
	
	
	$.fn.scroller = function(content, right_arrow, left_arrow, options) {
		var container = this;
		
		options = jQuery.extend({
			scrollMultiplier: 4			
		}, options || {});
		
		var width = 0;

		content.children('a').each(function() {
			width += $(this).outerWidth({ margin: true });
		});

		content.width(width);

		// Scroller on New This Season Page	
		right_arrow.hover(function() {
			scrollRight(container);
		}, function() {
			container.stop();
		});

		left_arrow.hover(function() {
			scrollLeft(container);
		}, function() {
			container.stop();
		});
		
		$(right_arrow).prepend('<span></span>').css('float', 'left');
		$(left_arrow).prepend('<span></span>').css('float', 'left');
		
		function scrollLeft(container) {
			container.animate( { scrollLeft: 0 }, (container.scrollLeft()) * options.scrollMultiplier, "", "");
		}

		function scrollRight(container) {
			container.animate( { scrollLeft: content.width() }, (content.width() - container.scrollLeft()) * options.scrollMultiplier, "", "");
		}
		
		return this;
	};
})(jQuery);




/* Dropdown for browse menu */

(function($) {
	$.fn.browseMenu = function() {
		$(this).find('ul').hide();
		// $('ul#jewels > li ul').hide();
		$(this).find('a.select').parent('li').show().parent('ul').show().parent('li').show().parent('ul').show();
		
		this.find('a').click(function() {
			$(this).parent().siblings().children('ul').hide();
		
			var child = $(this).parent().children('ul');
		
			if (child.is(':hidden')) {
				child.slideDown('slow');
			}
			else child.slideUp('slow');
					
			if ($(this).attr('href') == "#") {
				return false;
			}			
		})
		
		return this;
	};
})(jQuery);



/*  Ajax Load function  */

(function($) {

	$.fn.ajaxLoad = function(settings) {			
		settings = jQuery.extend({
			url: $(this).attr('href'),
			selection: '',
			container: ''
		}, settings || {});
		
		if (settings.container == '') {
			settings.container = settings.selection;
		}
						
		function loadSelection() {
			$(settings.container).css('position', 'relative');
			
			// var loading = $('<div class="loadig"></div>').width($(settings.container).outerWidth()).height($(settings.container).outerHeight());
			
			$(settings.container).addClass('loadig').find('*').css('opacity', 0);
			
			// loading.prependTo(settings.container).css('opacity', 1).fadeIn('slow');
			
			var temp = $('<div/>');

			temp.load(settings.url + " " + settings.selection, function() {
				$(settings.container).replaceWith(temp);

				initialize();
				initializeCelebs();				
			});
			
			// $(settings.container).load(settings.url + " " + settings.selection + " > *", function() {
			// 	initialize();
			// 	initializeCelebs();
			// });
			
			return false;
		}

		return this.unbind('click').click(loadSelection);
	};
})(jQuery);



/*  Popup function  */

var MAX_WIDTH = 600;
var MAX_HEIGHT = 600;
var OPACITY = .8;
var container = $('<div id="popup_container"></div>');
var dimmer = $('<div id="dimmer"></div>');
var positioner = $('<div id="positioner"></div>');
var closeButton = $('<div id="close_button">&#x2297; <a href="#">Close</a></div>');

/* Popup plugin used across the website */

(function($) {
	$(function() {
		positioner.prependTo('body').click(function() {
			if (container.is(':visible')) {
				close();				
			}
		});
		closeButton.prependTo(positioner).css('opacity', .85).click(function() {
			close();
			return false;
		});
		container.prependTo(positioner);
		dimmer.prependTo('body').css('opacity', .85).click(function() {
			if (container.is(':visible')) {
				close();				
			}
		});
		
		// Mimicking fixed positining for IE6
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {	
			dimmer.height($(document).height());
			positioner.height($(window).height());
			
			$(window).resize(function() {
				positioner.height($(window).height());				
			});
					
			$(window).scroll(function() {
				positioner.css('top', $(window).scrollTop() + 'px');
			});
		}

		// Hide the container and the dimmer
		positioner.hide();
		dimmer.hide();
		
		container.hover(function() {
			positioner.unbind('click');
		}, function() {
			positioner.click(function() {
				close();				
			});
		});
	});
	
	// function initializeLinks() {
	// 	$('a[rel^=popup]').each(function() {
	// 		$(this).optPopup($(this).attr('href'), $(this).metadata());
	// 	});		
	// }
	
	function close() {
		positioner.fadeOut(800, function() {
			container.html('');
			container.hide();
		}).hide();
		dimmer.fadeOut(800);
	}
	
	$.fn.optPopup = function(url, options) {		
		options = jQuery.extend({
			width: 'auto',
			height: 'auto',
			draggable: false,
			iframe: false,
			closeButton: true,
			animateIn: 'fadeIn',
			animateOut: 'fadeOut',
			parameters: {}	
		}, options || {});
		
		function _initialize() {
			count++;
			
			container.animate({ opacity: 0 }, 200).show();
			dimmer.fadeIn('fast');
			positioner.fadeIn('fast');
			
			if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
				positioner.css('top', $(window).scrollTop() + 'px');
			}
			// loader.fadeIn('fast');
			
			if (options.closeButton == true || options.iframe == true ) {
				closeButton.fadeIn('fast');				
			}
			
			container.width(options.width).height(options.height);

			if (options.iframe == true) {
				container.html('<iframe src="' + url + '" width="' + options.width + '" height="' + options.height + '" scrolling="auto" frameborder="0"></iframe>').css('overflow', 'hidden');

				container.css('margin-left', options.width / -2);
				container.css('margin-top', options.height / -2);

				container.css('opacity', 0).show();
				container.animate({ opacity: 1 }, 500);
			}
			else {
				$.get(url, function(data) {
					container.html(data);

					container.css('margin-left', container.width() / -2);
					container.css('margin-top', container.height() / -2);
					
					initialize();
					
					$('#print_block a').click(function() {
						window.print();
					});
					
					if (options.width == 'auto' || options.height == 'auto') {
						var popup = container.find('div');
						
						var contentWidth = popup.outerWidth({ margin: true });
						var contentHeight = popup.outerHeight({ margin: true });

						var popWidth = contentWidth < MAX_WIDTH ? contentWidth : MAX_WIDTH;
						var popHeight = contentHeight < MAX_HEIGHT ? contentHeight : MAX_HEIGHT;

						if (options.width == 'auto')
							container.width(popup.outerWidth({ margin: true }));
						if (options.height == 'auto')
							container.height(popup.outerHeight({ margin: true }));				
					}
					
					// alert(container.find('div:first').outerHeight({ }) + ', ' + container.height());
					container.css('opacity', 0).show();
					container.animate({ opacity: 1 }, 500);
				});
			}
			
			return false;
		}
		
		if (this.tagName() == "BODY") {
			this.one('click', _initialize);
		}
		else return this.unbind('click').click(_initialize);
	};
})(jQuery);





/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();