/**
 *  USE:        Forevermark Consumer Site
 *  AUTHOR:     Syzygy UK Limited
 */


setJsStyles();
initBackgroundFix();

$(document).ready(function() {
	// Dropdown Menu
	initMenu('#nav > ul > li');
	initMenu('#sub-nav > ul > li');

	contentToggle();
	jewellerLookup.init();
	// searchToggle.init();

	// Help Overlay
	imageOverlay.init('help-overlay');

	baseOverlay.init('#jeweller-images a.image-overlay');
	carousel.init('#carousel', '#carousel-panel', '#carousel-content', 'xml/editorial.xml');

	initJewellerFlash('flashvideo', '/swf/fm_video.swf');

	// Remove default value from input field when blurred
	clearInputText();

	// New Jeweller Homepage function
	$('a.view-jeweller').click(function(e) {
		e.preventDefault();
		openDetailForm(this);
	})


	// Faq
	faqLookUp.init();

	// T & C's, Privacy Policy
	popup.init('body');
	initWindowButtons();
	$('#close-send-friend').click(function(e) { window.close(); });

	// Faq expanding sections
	expandingSections.init('.col-1b #faq-results', 'div.section');

	// Thumb viewer
	swapmedia.init('#viewer', '#col-image .thumbs', 2000);

	// Calender
	checkDaysInMonth(); // Check initial month in a day
	$("#date .month, #date .year").change(checkDaysInMonth); // Change when the month or year changes

	// Show Menu over Form Fields
	$('#nav > ul > li > ul').bgiframe();
	$('#sub-nav > ul > li > ul').bgiframe();

	// IE 6 PNG Fix
	if (typeof $.ifixpng === 'function') {
		$.ifixpng('/images/pixel.gif');
		$('span.wet-floor, span.fade-bg').ifixpng();
		$('.overlay-edge img').ifixpng();
	}

	if ($('#pagination .pages').length > 0) {
		jQuery.each(jQuery.browser, function(i, val) {
			if (i == "mozilla" && jQuery.browser.version.substr(0, 3) < "1.9")
				$('#pagination .pages').css('display', 'table').css('margin', 'auto');
		});
	}

	// Jeweller Homepage Image Rollover
	hoverJeweller('#jeweller-top-scroller > li > a');
	hoverJeweller('#jeweller-bottom-scroller > li > a');

	var hearAboutUs = $('#hear-about select');
	setOtherFieldDisplay(hearAboutUs, true);
	hearAboutUs.change(function() { setOtherFieldDisplay(hearAboutUs, false); });

	function setOtherFieldDisplay(elem, dontRefresh) {
		var selectedOpt = elem.find('option:selected');
		var specifyOtherParagraph = $('#otherSection');

		if (!dontRefresh) selectedOpt.val();
		if (selectedOpt.val() == 'other') {
			var field = specifyOtherParagraph.css('display', 'block').find('input').focus();
			if (!dontRefresh) field.val('');
		}
		else {
			specifyOtherParagraph.css('display', 'none');
		}
	}
	
	if (jewellerLookup.isManualSubmit)
		$('#jeweller-lookup select').change(showButton);
});

function showButton() {
	if (this.value != '') {
		$('.manual-submit').show();
	} else {
		$('.manual-submit').hide();
	}
}

// Jeweller Homepage Image Rollover
function hoverJeweller(element) {
	$(element).mouseout(function() {
		$(this).find('span').hide();
	}).mouseover(function() {
		$(this).find('span').show();
	});
}

// openTab
function openTab() {
	$('#form-holder').fadeIn("slow");
}


// closeTab
function closeTab() {
	$('#form-holder').fadeOut("fast");
}


function openDetailForm(link) {
	var that = $(link),
			bottomCarousel = $('#bottom-scroller'),
			detailForm = $('#form-holder'),
			linkOpen, linkClose;

	if (Object.isEmpty(that.data("linkText"))) {
		that.data("linkText", {open: that.text(), close: that.attr('rel')});
	}
	
	if (that.hasClass('close-jeweller')) {
		detailForm.fadeOut("slow", function() {
			bottomCarousel.animate({ top: 0 }, 1000);
			that.removeClass('close-jeweller').css('margin-top', '0').text(that.data("linkText").open);
		});
	} else {
		bottomCarousel.animate({ top: 155 }, 1000, function() {
			detailForm.fadeIn();
			that.addClass('close-jeweller').css('margin-top', '156px').text(that.data("linkText").close);
		});
	}
}

Object.isEmpty = function(obj) {
	for (var i in obj) {
		if (obj.hasOwnProperty(i)) return false;
	}
	return true;
};

// getter / setter for flash display
var shouldDisplayFlash = function(state) {
	// store flash option in a cookie
	var expires = new Date(new Date().getTime() + 6 * 30 * 24 * 3600000); // 6 months

	if (typeof state === 'undefined') {
		return (document.cookie.indexOf('flash=false') === -1);
	}
	else {
		state = (state != false);
		document.cookie = 'flash=' + state + '; expires=' + expires + '; path=/';
		return state;
	}

};

function disableLine() {
	selectItems = $("p#countryDDL select option");
	selectItems.each(function() {
		if (this.value == -1) {
			$(this).attr("disabled", true);
		}
	});
}

function checkDaysInMonth() {
	var daysInMonth = 32 - new Date($("#date .year").val(), $("#date .month").val() - 1, 32).getDate();
	$('#date .day option').attr('disabled', '');
	$('#date .day option:gt(' + (daysInMonth - 1) + ')').attr('disabled', 'disabled');
	if ($("#date .day").val() > daysInMonth) {
		$("#date .day").val(daysInMonth);
	}
}

// Hide the value of text search field on focus
function clearInputText() {
	var focusField = $('.hasPlaceholder');

	focusField.focus(function() {
		var el = $(this);
		var val = el.val();
		if (!el.data('placeholder')) {
			el.data('placeholder', val);
		}
		
		if (val === el.data('placeholder')) {
			el.val('');
		}
	});

	focusField.blur(function() {
		var el = $(this);
		if (el.val() === '') {
			el.val(el.data('placeholder') || '');
		}
	});
}

// Field Check
function validateInputField(fieldName) {

	// Check when a user leaved an input field
	$('input.' + fieldName).blur(function() {
		checkIfValid($(this));
	});

	// Check what value is city when it is changed.
	$('p.submit-holder input.submit-button').click(function(e) {
		var focusField = $('input.' + fieldName);
		if (!focusField.parent().hasClass('js-hide')) {
			if (!checkIfValid(focusField)) {
				e.preventDefault();
			}
		}
	});

	function checkIfValid(el) {
		if (el.val() === '') {
			el.next().show();
			return false;
		}
		else {
			el.next().hide();
			return true;
		}
	}
}

function getSiteRoot() {
	var l = location;
	return l.protocol + '//' + l.host + '/';
}

// mod JH: 08-11-14 12:45
function initJewellerFlash(targetElementId, swfPath) {
	if ($('#' + targetElementId && window.swfobject)) {
		var vars = { url: $('#' + targetElementId + ' .video').attr('href'), autoplay: true, autohidecontrols: true };
		var params = { bgcolor: '#f1f1f1', menu: 'false', allowfullscreen: 'true', wmode: 'opaque', autohidecontrols: 'true' };
		var attributes = { id: targetElementId, name: targetElementId };

		swfobject.embedSWF(swfPath, targetElementId, '558', '327', '9.0.45', '/swf/expressInstall.swf', vars, params, attributes);
	}

	// rollover close button
	var overlay = $('#overlay-holder');
	var close = overlay.find('div.close.js-hide');
	close.hide().removeClass('js-hide');
	$('#overlay-holder').hover(
		function(e) { close.show(); },
		function(e) { close.hide(); }
	);
}

// Flash for magazine editorial page
function initEditorialFlash(targetElementId, swfPath) {
	if ($('#' + targetElementId && window.swfobject)) {
		var flashvars = { lang: 'en', pageid: '/The-World-of-Forevermark-/Forevermark-in-the-Press' };
		var params = { bgcolor: '#ffffff', menu: 'false', allowfullscreen: "true", wmode: "opaque" };
		var attributes = { id: 'fm_main', name: 'fm_main' };

		swfobject.embedSWF(swfPath, targetElementId, '100%', '100%', '9.0.45', 'js/org/swffix/expressInstall.swf', flashvars, params, attributes);
	}
}

// Close popup window
function initWindowButtons() {
	var elem = $('#close');
	if (elem.hasClass('hide')) { elem.removeClass('hide'); }
	$('a.window-close').click(function(e) { window.close(); });
	$('a.window-print').click(function(e) { window.print(); });
}

// Popup: help/faq/hint
var popup = {
	instances: {},
	options: {
		print: 'height=500,width=657,resizable,scrollbars',
		help: 'height=500,width=657,toolbar,location,resizable,scrollbars',
		terms: 'height=500,width=657,toolbar,location,resizable,scrollbars',
		sendfriend: 'height=675,width=480,resizable,scrollbars',
		sendfriendsmall: 'height=500,width=480,resizable,scrollbars',
		staf: 'height=560,width=760,resizable,scrollbars',
		exclusive: 'height=622,width=760,resizable,scrollbars',
		personalMsgPreview: 'height=636,width=760,resizable,scrollbars',
		signupexclusiveupdate: 'height=675,width=800,resizable,scrollbars'
	},

	init: function(cssScope) {
		cssScope = cssScope || '#container';
		$(cssScope + ' a.popup').click(function(e) {
			var elem = $(this);
			popup.open(elem.attr('href'), elem.attr('target'));
			elem.blur();
			e.preventDefault();
		});
	},

	open: function(url, name, options) {
		if (name === 'sendfriend') {
			name = screen.height < 620 ? 'sendfriendsmall' : name;
		}
		options = options || popup.options[name] || popup.options['help'];

		var win = window.open(url, name, options);
		if (window.focus) win.focus();
		popup.instances[name] = win;
	}
};

var faqLookUp = {
	init: function() {
		var form = $('#faq-form');
		
		// Hide button
		form.find('p.submit-holder').hide();
		
		// Change
		$('select#category').change(function() {
			form.submit();
		});
	}
};

function initBackgroundFix() {
	var ie_ver = parseInt($.browser.version, 10);
	if ($.browser.msie && ie_ver == 6) {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch (err) { }
	}
}

function contentToggle(selector, onstateClass) {
	selector = selector || 'a.js-toggle';
	onstateClass = onstateClass || 'expanded';
	$(selector).click(function(e) {
		var el = $(this);
		var target = $(el.parents('div').get(0)).find('.' + el.attr('href').substring(1));

		e.preventDefault();
		this.blur();
		target.removeClass('js-hide');

		if (el.hasClass(onstateClass)) {
			target.hide();
			el.removeClass(onstateClass);
		}
		else {
			target.show();
			el.addClass(onstateClass);
		}
	});
};

var jewellerLookup = {
	parent: [],
	scrollPane: null,
	finalSelectListName: '',
	service: '',
	isAutoRedirect: null,
	isManualSubmit: null,
	isButtonAction: null,
	redirectUniqueId: null,
	redirectMethod: function() {
		var obj = this;
		setTimeout(
			function() {
				obj.name = jewellerLookup.redirectUniqueId;
				$('#jeweller-form').hide();
				__doPostBack(jewellerLookup.redirectUniqueId, obj.value);
			}, 1);
	},
	init: function() {
		var that = this;
		that.finalSelectListName = 'ddlJeweller';
		that.scrollPane = $('#forevermark-main div.col-2 div.col-scroll')[0] || null;

		that.parent = $('#jeweller-lookup');
		if ($('#change_jeweller').length === 0) {
			that.service = 'locator';
		}
		else {
			that.service = 'register';

			// Validate the other input field
			validateInputField('other-field');
		}
		that.parent.removeClass('js-hide');
		var selectName = that.parent.find('select').attr('name');
		if (selectName && (!new RegExp(that.finalSelectListName + '$').test(selectName))) {
			that.parent.find('select').change(this.onChange);
		}

		var field = that.parent.find('select');
		field.val($('option:first', field).val());
	},
	onChange: function(e) {
		var that = jewellerLookup;
		var elem = $(this);
		var value = elem.val();
		if (value == false) {
			elem.nextAll('select').remove(); // dont lookup for first option
			elem.nextAll('button').remove();
		}
		else {
			that.loadData($(this));
		}

		if (elem.hasClass('jeweller-select') && value === '-1') {
			$("#change_jeweller").removeClass('js-hide').addClass('active').find('span').hide();
		}
		else {
			$("#change_jeweller").addClass('js-hide').removeClass('active').find('input.other-field').val('');
		}
	},
	loadData: function(elem, value) {
		if (elem.jquery) {
			var el = elem;
			value = elem.val();
			elem = elem.blur().attr('name');
		}

		var that = this;
		var jsonDataUrl = '/util/DealerLocatorHandler/DealerLocatorHandler.ashx';
		var request = { 'service': that.service };
		request[elem] = value;
		if (elem != that.parent.find('select').attr('name')) {
			request[that.parent.find('select').attr('name')] = that.parent.find('select').val();
		}
		// for local testing...
		//jsonDataUrl = '/json/json_test_'+ elem +'.js';

		var test = $.getJSON(jsonDataUrl, request, function(result, textStatus) {
			if (textStatus != 'success' || !result || !result.name || !result.values || result.values === []) {
				log('Unable to retrieve results, status is: ' + textStatus); // handle error
			}
			else {
				if (el.hasClass('jeweller-select')) {
					if (!el.next('button').length) that.makeButtonHtml(result.name, result.cssclass, result.values);
					$('#jewellerButton').click(function() {
						$(this).prev('select').change(that.redirectMethod).change();
					});
				}
				else that.makeSelectHtml(result.name, result.cssclass, result.values);
			}
		});
		return true;
	},
	makeButtonHtml: function(name, cssclass, data) {
		var that = this;
		var buttonHtml = '<button id="jewellerButton" name="' + name + '" class="jeweller_button" type="button">' + findDetailsText + '</button>';

		this.parent.append(buttonHtml);
	},
	makeSelectHtml: function(name, cssclass, data) {
		var that = this;
		var cssclassValue = cssclass ? 'size selectFix ' + cssclass : 'size selectFix';
		var id = name.replace(/\$/gi, '_'); // clean .net generated element id
		if (jewellerLookup.isManualSubmit) idManual = that.redirectUniqueId;
		var selectHtml = '<select id="' + id + '" name="' + name + '" class="' + cssclassValue + '"></select>';
		var select = $('#' + id);

		if (!select.length) {
			this.parent.append(selectHtml);
		}
		else {
			select.replaceWith(selectHtml);
		}

		select = this.parent.find('#' + id);
		if (that.scrollPane) {
			that.scrollPane.scrollTop += select.height() + 5;
		}

		// remove dependent fields
		select.nextAll('select').remove();

		if (!id.endsWith(that.finalSelectListName)) {
			select.change(that.onChange);
		}
		if (this.isAutoRedirect) {
			select[0].onchange = that.redirectMethod;
		}
		if (this.isManualSubmit) {
			select.change(that.onChange);
		}

		var item, dataLen, i, optionHtml;

		for (i = 0, dataLen = data.length; i < dataLen; i++) {
			item = data[i];
			optionHtml = '<option';
			if (item && item.length === 2) {
				optionHtml += ' value="' + item.shift() + '"';
			}
			optionHtml += '>' + item.shift() + '</option>';
			select.append(optionHtml);
		}
	}
};

var swapmedia = {
	init: function (containerId, control, transitionTime) {
		var that = this;
		that.list = $(control);
		that.container = $(containerId);
		that.speed = transitionTime;
		that.id = 0;
		
		// List of items
		var items = that.list.find('li a');
		
		// Run function when clicked
		items.click(that.change);
	},
	change: function (e) {
		var that = swapmedia;
		var el = $(this);
		
		e.preventDefault();
		el.blur();
		
		if (!el.hasClass('active')) {
			var imageId = 'image' + that.id++;
			var href = el.attr('href');

			// display image in page
			var imgHtml = '<img id="' + imageId + '" src="' + href + '" alt="" style="display: none" class="dynamic" />';

			// Reset active
			that.list.find('a.active').removeClass('active');
			
			el.addClass('active');
			that.container.append(imgHtml);
			$('#' + imageId).fadeIn(that.speed, function() {
				$(this).prev('.dynamic').remove();
			});
		}
	}
};

// media carousel module (singleton)
var carousel = {
	container: [],
	list: [],
	controller: [],
	content: [],
	controllerOffset: 0,
	hasLightbox: false,
	lightboxLinkTransitionDuration: 300,
	flashVersion: '9.0.45',


	init: function(listSelector, containerSelector, contentSelector) {
		var speed = 300; //ms
		var videoIconPath = '/images/video_icon.png';
		var that = this;
		var canFlash = window.swfobject && swfobject.hasFlashPlayerVersion(that.flashVersion);
		
		that.list = $(listSelector);
		if (that.list.length == 0) return false;

		var items = that.list.find('li a');
		var videoItems = items.filter('.video'); // "[href$='.flv']"
		
		that.container = $(containerSelector).append('<div id="carousel-skin-fm-border"></div>');
		
		if (!canFlash) {
			videoItems.each(function() { $(this).parent('li').remove(); });
		}
		that.list.jcarousel();
		if (videoIconPath) {
			videoItems.each(function() {
				$.ifixpng('/images/pixel.gif');
				$(this).append('<img src="' + videoIconPath + '" class="icon" />').find('img.icon').ifixpng();
			});
		}
		items.click(that.showMedia);
		
		var controller = $('div.jcarousel-container', this.container).hover(
			function() {
				$(this).queue([]).animate({ 'top': '0' }, speed);
			},
			function() {
				$(this).queue([]).animate({ 'top': that.controllerOffset }, speed);
			}
		);
		that.controllerOffset = parseInt(controller.css('top'));
		that.content = $(contentSelector);
		that.mediaElemId = 'carousel-view';
		that.controller = controller;
		
		// show the default flash movie if exists
		var videoHref = that.content.find('span.video-placeholder').attr('title');
		if (canFlash && videoHref) {
			that.renderFlash(videoHref);
		}
		
		// enable lightbox
		if ($('#generic-two-main.lightbox-container').length === 1) {
			that.hasLightbox = true;
			$('#carousel-panel a.lightbox').lightbox()
				.hover(
					function() {
						$(this).find('span.lightbox-enlarge').fadeTo(that.lightboxLinkTransitionDuration, 0.5);
					},
					function() {
						$(this).find('span.lightbox-enlarge').fadeTo(that.lightboxLinkTransitionDuration, 0);
					}
				).click(function() { this.blur(); }).
					find('span.lightbox-enlarge').css({ display: 'block', opacity: 0 });

			$('#lightbox-enlarge-link').click(function(e) {
				$('#carousel-content a.lightbox:visible').triggerHandler('click');
				e.preventDefault();
				this.blur();
			});
		}

		return true;
	},

	showMedia: function(e) {
		var that = carousel;

		var el = $(this);

		e.preventDefault();
		el.blur();

		var href = el.attr('href');
		that.removeMedia();

		if (el.hasClass('video')) {
			// display video in flash player
			that.renderFlash(href);
		}
		else {
			// display image in page
			var imgHtml = '<img id="' + that.mediaElemId + '" src="' + href + '" alt="" />';

			// setup lightbox link
			var altHref = $.trim(el.find('var.lightbox-href').html()) || '';
			if (that.hasLightbox && altHref) {
				that.content.find('a.lightbox').show().attr('href', altHref).append(imgHtml);
			}
			else {
				that.content.find('a.lightbox').hide();
				that.content.append(imgHtml);
			}
		}
	},

	renderFlash: function(href) {
		var that = this;
		var vars = { url: href, autoplay: true, autohidecontrols: true };
		var params = { bgcolor: '#f1f1f1', menu: 'false', allowfullscreen: 'true', wmode: 'opaque', autohidecontrols: 'true' };
		var attributes = { id: that.mediaElemId, name: that.mediaElemId };

		that.content.append('<div id="' + that.mediaElemId + '"></div>');
		swfobject.embedSWF('/swf/fm_video.swf', that.mediaElemId, '605', '340', that.flashVersion, '/swf/expressInstall.swf', vars, params, attributes);
	},

	removeMedia: function() {
		var that = carousel;
		$('img#' + that.mediaElemId, that.content).remove();
		if ($('#' + that.mediaElemId, that.content).length == 1) swfobject.removeSWF(that.mediaElemId);
	}
};


function initMenu(cssSelector) {
	$(cssSelector).hover(
		function() {
			var el = $(this);
			var submenu = el.addClass('sfhover').find('ul').hide();
			var offset = parseInt((el.width() - submenu.width()) / 2);
			offset += 10;
			submenu.css('left', offset).show();
		},
		function() {
			$(this).removeClass('sfhover').find('ul').css('left', '');
		}
	);
}



function setJsStyles() {
	if (location.host.indexOf('localhost') !== -1 || location.host.indexOf('192.168.') !== -1) {
		document.writeln('\n\t<link rel="stylesheet" href="/css/js_main.css" type="text/css" media="all" />');
	}
	else {
		document.writeln('\n\t<link rel="stylesheet" href="/css/js_main.css" type="text/css" media="all" />');
	}
}


// please create a base class for the overlays and then subclass from it for imageOverlay - overriding methods
// JH: 08-11-14 12:43
var baseOverlay = {
	init: function(cssSelector) {
		var that = this;
		var el = $(cssSelector);
		el.click(function(e) {
			e.preventDefault();
			this.blur();

			that.show($(this));
		});
	},
	show: function(el) {
		var name = $('#' + el.attr('class'));
		name.show();
		name.find('.image').attr('src', el.attr('href'));
		name.find('#right-panel h2').text(el.find('.h2-title').html());
		name.find('#right-panel p').text(el.find('.hidden').html());
		this.close(name);
	},
	setOffset: function() {},
	close: function(el) {
		el.find('.close a').click(function() {
			el.hide();
		});
	}
};


var imageOverlay = {
	init: function(cssSelector) {
		var elem = $('#' + cssSelector);
		var that = this;
		elem.hide();
		$('a.' + cssSelector).click(function(e) {
			e.preventDefault();
			this.blur();
			var el = $(this);
			that.show(el.attr('class'), e.target.src);
		});
	},
	show: function(link, imgSrc) {
		var that = this;
		var overlay = $('#' + link);
		if (imgSrc) overlay.find('.image').attr('src', imgSrc);
		overlay.css('left', imageOverlay.setOffset());

		overlay.fadeIn('slow');
		overlay.find('.close a').click(function(e) {
			e.preventDefault();
			this.blur();
			that.close(overlay);
		});

		imageOverlay.initButtons();
	},

	setOffset: function() {
		expwidth = $('#ext-container').css('width');
		width = (parseInt(expwidth) - 903) / 2;
		return width;
	},

	initButtons: function() {
		var linkSelector = "#left-panel a";

		$(linkSelector).click(function(e) {
			e.preventDefault();

			// turn off current
			var img = $(linkSelector + '.on').removeClass('on').find('img');
			img.attr('src', img.attr('src').slice(0, -4) + "_off.jpg");

			// turn on this one
			img = $(this).addClass('on').find('img');
			img.attr('src', img.attr('src').slice(0, -8) + ".jpg");

			// load main image
			$('#img img').attr('src', this.href);
		});
	},

	close: function(link) {
		link.hide();
	}
};

// provides accordian style sections for profile pages
var expandingSections = {
	sectionSelctr: '',
	container: [],
	currentExpanded: null,
	buttonText: '',
	transition: { collapse: 'hide', expand: 'show' },

	init: function(containerSelctr, sectionSelctr) {
		var container = $(containerSelctr);
		if (container.length <= 0) return false;

		this.sectionSelctr = sectionSelctr;
		this.container = container;
		this.render();
		return true;
	},
	render: function() {
		var that = expandingSections;
		that.container.find(that.sectionSelctr).each(function() {
			var el = $(this);
			if (el.hasClass('expanded')) that.setExpanded(el);
			else that.setCollapsed(el);
		});
	},
	setCollapsed: function(section) {
		var that = expandingSections;
		section.find('h3').addClass('clickable');
		section.find('h3').click(function(e) { that.expand(e, section); });
		section.removeClass('expanded').find('.body')[that.transition.collapse]();
	},
	setExpanded: function(section) {
		var that = expandingSections;
		that.currentExpanded = section;
		section.find('h3').removeClass('clickable');
		section.addClass('expanded').find('.body')[that.transition.expand]();
	},
	expand: function(e, section) {
		var that = expandingSections;
		that.setCollapsed(that.currentExpanded);
		that.setExpanded(section);
		e.preventDefault();
	},
	expandAll: function() {
		var that = expandingSections;
		that.container.find(that.sectionSelctr).each(function()
		{
			that.setExpanded($(this));
		});
		that.currentExpanded = null;
		$('input.submit-button').removeAttr('disabled');
	}
};

var searchToggle = {
	swap: function(e) {
		var elem = $(this);
		elem.addClass('active');
		e.preventDefault();
		var searchWrapper = $('#siteSearch');
		var siteSearchInput = $('#siteSearch input.siteSearchInput');
		if (searchWrapper.hasClass('elem-hide')) {
			siteSearchInput.get(0).blur();
			searchWrapper.fadeIn(200, function() {
				siteSearchInput.get(0).focus();
			}).removeClass('elem-hide');
		}
		else {
			searchWrapper.fadeOut(400).addClass('elem-hide');
			siteSearchInput.get(0).blur();
			elem.removeClass('active');
		}
	},
	init: function() {
		$('label.showSearch').click(this.swap);
	}
};

// for debugging:
var log;
if (window.console && console.log) log = console.log;
else log = function() { };

function ChangeCityLabel(cityTextLang, prefectureTextLang, labelID, selectID, JPlang) {
	var labelCity = document.getElementById(labelID);
	var selectCountry = document.getElementById(selectID);
	if (labelCity && selectCountry) {
		labelCity.innerHTML = selectCountry.value != JPlang ?
           cityTextLang : prefectureTextLang;
	}
};

function ValidateJeweller() {
	var res = false;
	var selects = document.getElementsByTagName("select");
	for (var i = 0; i < selects.length; i++) {
		if (selects[i].id && selects[i].id.indexOf("ddlJeweller") != -1) {
			res = true;
			break;
		}
	}
	return res;
};
