var whitespace = " \t\n\r";

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i=0; i < this.length; i++) {
            if (this[i] == obj) return i;
        }
        return -1;
    }
}

jQuery.exists = function(selector) {
	return (jQuery(selector).length > 0);
}

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
    random: function(a, i, m, r) {
        if (i == 0) jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        return i == jQuery.jQueryRandom;
    }
});

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};

jQuery(document).ready(function(){	
	/* MainMenu  */
	jQuery('#menu li').hover( function () {
		jQuery(this).addClass('hover'); 
	}, function () {
		jQuery(this).removeClass('hover');
	});	

	/* Plural */
	jQuery('#users').change(function () {
		if(jQuery('#users option:selected').val()!=='1') {jQuery('#plural').html('s');} else {jQuery('#plural').html('');}
	});	
	
	/* CollapsibleBoxes */
	jQuery('.collapsible .content').hide();
	jQuery('.collapsible .title').click(function()
	{
		jQuery(this).toggleClass('active');
		jQuery(this).children('.content').slideToggle(100);
	});	
	
	/* FontCollection */
	jQuery('.tooltip').hide();
	jQuery('#collection li').hover( function () {
		jQuery(this).children('.tooltip').css('top', jQuery('#collection').offset().top - jQuery(this).children('.tooltip').height() - 5).show();
	}, function () {
		jQuery(this).children('.tooltip').hide();
	});
	jQuery('#collection li').mousemove(function(e){
		var pos = jQuery(this).offset();
		var pos = pos.left;
		var width = jQuery(this).children('.tooltip').width();
		var x = e.pageX - width/2;
		jQuery('.tooltip').css({left: x + 'px'});		
	});	

	/* WaterfallSamples */
	jQuery('#font-samples .image div span').hide();
	jQuery('#font-samples .image div').hover( function () {
		jQuery(this).children('span').fadeIn(100);
	}, function () {
		jQuery(this).children('span').fadeOut(100);
	});	
	jQuery('#font-samples .text-sample div span').hide();
	jQuery('#font-samples .text-sample div').hover( function () {
		jQuery(this).children('span').fadeIn(100);
	}, function () {
		jQuery(this).children('span').fadeOut(100);
	});	
	
	/* BuyingOptions */
	jQuery('tr.sample div').hide();
	jQuery('#bo .items .title').click( function () {
		jQuery(this).toggleClass('active');
		jQuery(this).parent('td').parent('tr').toggleClass('active').next('tr.sample').find('div').slideToggle(100);
	});	
	
	/* Products */
	productsLoad();

	jQuery('.floater .close').click(function() {jQuery('.floater').fadeOut(100);return false;});
	
	jQuery('.floater .close').hover(function () {
		floaterTitle = jQuery(this).text();
		jQuery(this).css({width: jQuery(this).width()});
		jQuery(this).html('Cancel');
	}, function () {
		jQuery(this).html(floaterTitle);
	});
	
	/* StudioWork */
	jQuery('#sw .project').hover( function () {
		jQuery(this).find('img').animate({opacity:0.5},100);
	}, function () {
		jQuery(this).find('img').animate({opacity:1},100);
	});

	/* Tip */
	makeTip();
	
	/* Favs */
	jQuery('#favs1').hide();
	jQuery('#favs h3 span#favs-hide').hide();
	jQuery('#favs0').click(function(){
		jQuery('#favs1').slideToggle(100);
		jQuery('#favs h3 span#favs-hide').toggle();
	});
	jQuery('#favs1 li:nth-child(2n) a').addClass('even');
	
	/* GlobalExpander {[<ext><exc>] [<ext><exc>] [<ext><exc>]} */
	if (jQuery('.no_change').length == 0)
	{
		jQuery('.exc:not(.expand)').hide();
		jQuery('.show_first *:first-child .exc').show();
		jQuery('.show_first *:first-child .ext').addClass('active');
		jQuery('.show_all .exc').show();
		jQuery('.show_all .ext').addClass('active');
	}
	jQuery('.ext').click(function(){
		if(jQuery(this).hasClass('active')==false && jQuery(this).parent().parent().hasClass('show_all')==false) {
			jQuery(this).parent().parent().find('.ext').removeClass('active');
			jQuery(this).parent().parent().find('.exc').slideUp(200);
		}
		jQuery(this).toggleClass('active');
		jQuery(this).next('.exc').slideToggle(200);
	});
	
	jQuery('.form-return').keypress(function(e) {if (e.which == 13) jQuery(this).parents('form').submit();});
	
	jQuery('#toolbar #options').live('mouseover mouseout', function (event) {
		if (event.type == 'mouseover') {
			jQuery('ul', this).show();
		}
		else {
			jQuery('ul', this).hide();
		}
	});
	
	jQuery('#toolbar #options a#filter-permalink').live('click', function() {
		jQuery.ajax({
			type: 'POST',
			dataType: 'json',
			url: '/ajax/action.php',
			data: ({
				a: 'permalink',
				id: jQuery(this).attr('rel'),
				url: (typeof getSelectionParams == 'function')  ? getSelectionParams() : getGenericSelectionParams(),
				text: jQuery('#my_text').val()
			}),
			success: function(json) {
				if (!json) return false;

				jQuery('#permalink-floater textarea[name="param[url]"]').val(json.permalink);
				jQuery('#permalink-floater').fadeIn(100);
				jQuery.scrollTo('#header', 500);
				return false;
			}
		});
	});

	jQuery('#toolbar #options a#filter-reset').live('click', function() {
		jQuery(this).parents('form').attr('method', 'post').prepend('<input type="hidden" name="reset" value="1"\/>').submit();
	});
	
	jQuery('#switch').click( function () {
		
		$(this).toggleClass('active');
		$(this).find('span').toggleClass('active');				
		if( typeof getSelectionParams == 'function' )
		{				
			url = getSelectionParams();
			DS = url.indexOf('?') > -1 ? "&" : "?";
			DS = url.indexOf('?s=') > -1 ? "?" : DS;			
			// serach for s=
			if( (pos = url.indexOf('s=')) > -1 )
			{			
				url = url.substr(0,pos-1);
				url += $(this).find('span.active').attr('id') == 'span-webfonts' ? DS+'s=webfonts':DS+'s=images';		
			}
			else
			{
				url += $(this).find('span.active').attr('id') == 'span-webfonts' ? DS+'s=webfonts':DS+'s=images';		
			}								
			window.location.href = url;
		}
		else
		{
			pos1 = url.indexOf("&s=");
			pos2 = url.indexOf("&", pos1+4);			
			if( pos2 > -1 )
			{
				s = url.substr(pos1+3, pos2-pos1-3);
			}
			else
			{
				s = url.substr(0,pos1);
			}			
			$('input[name="s"]').val( s=='' || s=='images' ? 'webfonts' : 'images' ); 
			$('form#toolbar').submit();
		}
		
		
	});
	
});

function isEmpty(s){
	return ((s == null) || (s.length == 0));
}

function isWhitespace (s){
	var i;
	// Is s empty?
	if (isEmpty(s)) return true;
	// Search through string's characters one by one
	// until we find a non-whitespace character.
	// When we do, return false; if we don't, return true.
	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);

		if (whitespace.indexOf(c) == -1) return false;
	}

	// All characters are whitespace.
	return true;
}

function isEmail (s){
	if (isEmpty(s))
	true

	// is s whitespace?
	if (isWhitespace(s)) return false;

	// there must be >= 1 character before @, so we
	// start looking at character position 1
	// (i.e. second character)
	var i = 1;
	var sLength = s.length;

	// look for @
	while ((i < sLength) && (s.charAt(i) != "@")) i++;

	if ((i >= sLength) || (s.charAt(i) != "@")) return false;
	else i += 2;

	// look for .
	while ((i < sLength) && (s.charAt(i) != ".")) i++;

	// there must be at least one character after the .
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
	else return true;
}

function checkEmail(value){
	if (isEmpty(value)) return false;
	if (!isEmail(value, false)) return false;
	return true;
}

function checkString (value, s){   // Next line is needed on NN3 to avoid "undefined is not a number" error
	// in equality comparison below.
	if (isEmpty(value)) return false;
	if (isWhitespace(value)) return false;
	return true;
}

function makeTip(container) {
	if (container == undefined) container = 'html';

	jQuery('.tip', container).each(function(){
		content = jQuery(this).html();
		if ($(this).hasClass('blue')) {
			jQuery(this).html('<img src="/images/_design/tip-blue.png" width="15" height="15" border="0" alt="Tip"/><span>' + content + '</span>').width();
		} else {
			jQuery(this).html('<img src="/images/_design/tip.png" width="15" height="15" border="0" alt="Tip"/><span>' + content + '</span>').width();
		}
	});
	jQuery('.tip, .tipword', container).children('span').hide();
	jQuery('.tip, .tipword', container).children('span').prepend('<img src="/images/_design/tip-arrow.png" width="5" height="9" border="0" alt="Tip" class="tip-arrow"/>');
	jQuery('.tip img', container).hover(function () {
		tipWidth = jQuery(this).next('span').width();
		parentWidth = jQuery(this).parent().width();
		max = 250;
		if (tipWidth > max) {jQuery(this).next('span').css({width: max + 'px', whiteSpace: 'normal'});}
		jQuery(this).next('span').css({left: parentWidth + 10 + 'px'});
		jQuery(this).next('span').fadeIn(100);
	}, function () {
		jQuery(this).next('span').fadeOut(200);
	});
	jQuery('.tipword', container).hover(function () {
		tipWidth = jQuery(this).children('span').width();
		parentWidth = jQuery(this).width();
		max = 250;
		if(tipWidth > max) {jQuery(this).children('span').css({width: max + 'px', whiteSpace: 'normal'});}
		jQuery(this).children('span').css({left: parentWidth + 10 + 'px'});
		jQuery(this).children('span').fadeIn(100);
	}, function () {
		jQuery(this).children('span').fadeOut(200);
	});
}

function writeTo(u, d) {
	var l="\x6D\x61\x69";
	l+="\x6C\x74\x6F\x3A"+u;
	window.location=l+"\x40"+d;
}

function like(elm, stuff_type, item_id) {
	jQuery.ajax({
		type: 'POST',
		dataType: 'json',
		url: '/ajax/like.php',
		data: '&t=' + stuff_type + '&id=' + item_id,
		success: function(json) {
			jQuery(elm).hide();
			jQuery(elm).siblings(0).show();
			jQuery('#favs span#favs-count').html(json.count);
			
			(json.count > 0) ? jQuery('#favs').fadeIn('fast') : jQuery('#favs').fadeOut('fast');
			
			if (json.add) {
				if (jQuery('#favs1 ul').length == 0) jQuery('#favs1').append('<ul></ul>');
				jQuery('#favs1 ul').append('<li id="favs-' + stuff_type + '-' + item_id + '">' + json.add + '</li>')
			} else {
				jQuery('#favs1 li#favs-' + stuff_type + '-' + item_id).fadeOut('fast').remove();
			}
			
			jQuery('#favs1 li a').removeClass('even');
			jQuery('#favs1 li:nth-child(2n) a').addClass('even');
		}
	});
}

function delay(millis) {
	var date = new Date();
	var curDate = null;

	do {curDate = new Date();} 
	while(curDate-date < millis);
}

function countryChange(elm, prefix) {
	var country = jQuery(elm).val();
	var speed = 100;
	if (prefix == undefined) prefix = '';
	
	// state / province select
	/*
	for (i in states) jQuery('#states-' + prefix + states[i]).hide(100);
	if (jQuery.inArray(country, states) >- 1) jQuery('#states-' + prefix + country).show();
	*/
	for (i in states) if (country == states[i]) {jQuery('#states-' + prefix + states[i]).fadeIn(100);} else {jQuery('#states-' + prefix + states[i]).fadeOut(100);}
	//if (jQuery.inArray(country, states) >- 1) jQuery('#states-' + prefix + country).show();

	// zip input
	if (jQuery.inArray(country, nozip) >- 1) {
		jQuery('#' + prefix + 'zip').fadeOut(speed).next('.warning').fadeOut(speed);
	} else {
		jQuery('#' + prefix + 'zip').fadeIn(speed);
	}
	
	// vat input
	if (prefix == '') {
		if (jQuery.inArray(country, vat) >- 1) {
			jQuery('#vat').fadeIn(speed);
			jQuery('#vat_country_code').html(transformVAT(country).toUpperCase());
			writeVATExample(country);
		} else {
			jQuery('#vat-invalid').fadeOut();
			jQuery('#vat label.warning img').remove();
			jQuery('#vat').fadeOut(speed);
		}
	}
}

function productsLoad() {
	//jQuery('.rows li ul').each(function(){ jQuery('li', this).css({height: (jQuery(this).height()) + "px"}); });
	
	jQuery('#content').find('img').batchImageLoad({
		loadingCompleteCallback: function() {
			jQuery('.rows li ul').each(function() {
				max = 0;
				jQuery('li', this).each(function() {
					if (jQuery(this).height() > max) max = jQuery(this).height();
				});
				jQuery('li', this).each(function () {jQuery(this).height(max);});
			});

			jQuery('#products a.button').hide();
			jQuery('#products li').hover( function () {
				jQuery(this).children('span').find('a.button').show();
			}, function () {
				jQuery(this).children('span').find('a.button').hide();
			});
			jQuery('a.notify').click(function() {
				a = jQuery(this).attr('name').split('-');
				idd = a[0];
				ttype = a[1];
		
				jQuery.ajax({
					type: 'POST',
					dataType: 'json',
					url: '/ajax/notification.php',
					data: ({
						'id': idd,
						'type': ttype,
						'p': 'getname'
					}),
					success: function(json) {
						if (!json) return false;
		
						jQuery('.floater input[name="id"]').val(idd);
						jQuery('.floater input[name="type"]').val(ttype);
						var arrPageSizes = ___getPageSize();
						var arrPageScroll = ___getPageScroll();
						jQuery('#notification').css({top:arrPageScroll[1] + (arrPageSizes[3]/10)}).fadeIn(100);
						jQuery('#notification #notification-title').html(json.name);
					}
				});
				
				return false;
			});
		}
	});
}

function writeVATExample(country) {
	text = '';
	
	switch (country) {
		case 'at':text += '<b>Example: ATU99999999</b>  	1 block of 9 characters';break;
		case 'be':text += '<b>Example: BE999999999</b> or <b>BE09999999992</b> 	1 block of 9 digits or 1 block of 10 digits 3';break;
		case 'cy':text += '<b>Example: CY99999999L</b> 	1 block of 9 characters';break;
		case 'cz':text += '<b>Example: CZ99999999</b> or <b>CZ999999999</b> or <b>CZ9999999999</b>	1 block of either 8, 9 or 10 digits';break;
		case 'de':text += '<b>Example: DE999999999</b> 	1 block of 9 digits';break;
		case 'dk':text += '<b>Example: DK99 99 99 99<b/> 	4 blocks of 2 digits';break;
		case 'ee':text += '<b>Example: EE999999999</b> 	1 block of 9 digits';break;
		case 'gr':text += '<b>Example: EL999999999</b> 	1 block of 9 digits';break;
		case 'es':text += '<b>Example: ESX9999999X4</b> 	1 block of 9 characters';break;
		case 'fi':text += '<b>Example: FI99999999</b> 	1 block of 8 digits';break;
		case 'fr':text += '<b>Example: FRXX 999999999</b> 	1 block of 2 characters, 1 block of 9 digits';break;
		case 'gb':text += '<b>Example: GB999 9999 99</b> or <b>GB999 9999 99 9995</b> or <b>GBGD9996</b> or <b>GBHA9997</b> 	1 block of 3 digits, 1 block of 4 digits and 1 block of 2 digits; or the above followed by a block of 3 digits; or 1 block of 5 characters';break;
		case 'hu':text += '<b>Example: HU99999999</b> 	1 block of 8 digits';break;
		case 'hu':text += '<b>Example: HU99999999</b> 	1 block of 8 digits';break;
		case 'ie':text += '<b>Example: IE9S99999L</b> 	1 block of 8 characters';break;
		case 'it':text += '<b>Example: IT99999999999</b> 	1 block of 11 digits';break;
		case 'lt':text += '<b>Example: LT999999999</b> or <b>LT999999999999</b> 	1 block of 9 digits, or 1 block of 12 digits';break;
		case 'lu':text += '<b>Example: LU99999999</b> 	1 block of 8 digits';break;
		case 'lv':text += '<b>Example: LV99999999999</b> 	1 block of 11 digits';break;
		case 'mt':text += '<b>Example: MT99999999</b> 	1 block of 8 digits';break;
		case 'nl':text += '<b>Example: NL999999999B998</b> 	1 block of 12 characters';break;
		case 'pl':text += '<b>Example: PL9999999999</b> 	1 block of 10 digits';break;
		case 'pt':text += '<b>Example: PT999999999</b> 	1 block of 9 digits';break;
		case 'se':text += '<b>Example: SE999999999999</b> 	1 block of 12 digits';break;
		case 'si':text += '<b>Example: SI99999999</b> 	1 block of 8 digits';break;
		case 'sk':text += '<b>Example: SK9999999999</b> 	1 block of 10 digits';break;
	}

	jQuery('#example').html(text);
}

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) tallest = thisHeight;
	});
	group.height(tallest);
}

function urlencode (str) {
	str = escape(str);
	return str.replace(/[*+\/@]|%20/g, function (s) {
			switch (s) {
				case "*":s = "%2A";break;
				case "+":s = "%2B";break;
				case "/":s = "%2F";break;
				case "@":s = "%40";break;
				case "%20":s = "+";break;
			}
			return s;
		}
	);
}

function cmyk2rgb(c, m, y, k) {
	c = c / 100;
	m = m / 100;
	y = y / 100;
	k = k / 100;
	r = 1 - (c * (1 - k)) - k;
	g = 1 - (m * (1 - k)) - k;
	b = 1 - (y * (1 - k)) - k;

	return new Array(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function getGenericSelectionParams() {
	params = '';

	jQuery('#toolbar select.f').each(function (i) {
		params += ((param == '') ? '?' : '&') + jQuery(this).attr('name') + '=' + jQuery(this).val();
	});

	return params;
}
