/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

$(function() {

	if($.fn.tinymce) $('textarea.tinymce').tinymce({
		script_url : config.base_url + 'assets/tiny_mce/tiny_mce.js',

		language:	'ro',
		theme:		"advanced",
		plugins:	"safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

		plugin_insertdate_dateFormat:	"%d-%m-%Y",
		plugin_insertdate_timeFormat:	"%H:%M:%S",
		extended_valid_elements:		"a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",

		theme_advanced_buttons1:			"save,newdocument,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|pasteword",
		theme_advanced_buttons2:			"bullist,numlist,link,unlink,anchor,image,cleanup,help,code,insertdate,inserttime,preview,|,bold,italic,underline,strikethrough,|",
		theme_advanced_buttons3:			"forecolor,backcolor,tablecontrols,|,hr,removeformat,visualai,",
		theme_advanced_buttons4:			"sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen|,outdent,indent,blockquote,|,undo,redo,|",
		theme_advanced_buttons5:			"insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
		theme_advanced_toolbar_location:	"top",
		theme_advanced_toolbar_align:		"left",
		theme_advanced_statusbar_location:	"bottom",
		theme_advanced_resizing:			true,

		relative_urls:			false,
		remove_script_host:		false,
		document_base_url:		'http://brandsaddict.ro', 

		file_browser_callback : "openSwampyBrowser"
	});

	$('.tabs').each(function(){
		var tabWrap = $(this);
		tabWrap.find('ul li a').click(function(){
			if($(this).attr('href').indexOf('#') != -1) {
				var t=$(this);
				t.parent().siblings().removeClass('s').end().addClass('s');
				tabWrap.find('.tab').eq(t.parent().index()).show().siblings('.tab').hide();
				return false;
			}
		});
		tabWrap.find('ul li.s a').click();
	});

	$('#nav a, #cart, #content .campaign .discount, #products .product .status, #products .product .strike, #sidebar-left .campaign-info .remain, #single-product #info2 .price2 .strike, #single-product #info2 .remain, #single-product #related .content .price2 .strike, #content .campaign .round').addClass('png');

	var time = $('.remain .time');
	if(time.length && time.attr('rel')) {
		var time_left = time.attr('rel');
		time_left = parseInt(time_left, 10);
		setInterval(function () {
			time_left--;
			var prt = pretty_date(time_left);
			time.html(prt);
		}, 1000);
	}

	if($('#z_judet').length && $('#z_oras').length) {
		$('#z_judet').change(function() {
			var orase = $('#z_oras').empty();
			$.getJSON($(this).attr('rel') + '/' + $(this).val(), function(data) {
				$.each(data, function(i, oras) {
					//$('<option/>').attr({
					//	text:		oras.oras + '',
					//	selected:	(oras.resedinta == 'y' ? true: false)
					//}).appendTo(orase);
					var slctd = oras.resedinta == 'y' ? 'selected' : '';
					orase.append('<option ' + slctd + '>' + oras.oras + '</option>');
				});
			});
		});
	}

	if($.fn.datepicker) $(".datepicker").datepicker({
		dateFormat:	'yy-mm-dd'
	});

	if($('#comenzi_status').length) {
		$('#comenzi_status').change(function() {
			window.location = $(this).attr('rel').replace('status', $(this).val());
		});
	}

	if($('#admin_comenzi_table')) {
		$('.admin_orders_status').change(function() {
			var el = $(this);

			$.getJSON($(this).attr('rel') + '/' + $(this).val(), function(response){
			    if(response.type == 'success') {
			    	var img = $('<img />').attr('src', config.base_url + 'assets/icon/success.gif');
			    	el.after(img);
			    	setTimeout(function() {
			    		img.fadeOut();
			    		setTimeout(function() {
			    			img.remove();
			    		}, 500);
			    	}, 1000);
			    } else {
			    	alert('A aparut o eroare si statusul comenzii nu a putut fi modificat. Mai incercati odata.');
			    }
			});
		});
	}

	if ($('#product_photos_upload').length) {
		var box = $('#product_photos_upload');
		$('#product_photos_upload_add').click(function() {
			$('<p/>').html('<input type="file" name="photo[]" />').appendTo(box);
			return false;
		});
	}
	
	if ($('#box-sizes').length) {
		var box2 = $('#box-sizes');
		box2.find('p > a').click(function() {
			if(box2.find('p').length > 1) $(this).parent().remove();
			return false;
		});
		$('#product-size-add').click(function() {
			box2.find('p').eq(0).clone(true).appendTo(box2).find('input').val('');
			return false;
		});
	}

	if($('#single-product').length)
	$('#thumbs a').click(function() {
		$('#photos #big').find('a').attr('href', $(this).attr('rel'));
		$('#photos #big').find('img').attr('src', $(this).attr('href')).attr('alt', $(this).attr('rel'));
		return false;
	});

	if($.fn.jqueryzoom) $('.jqzoom').jqueryzoom({
		xzoom: 350,
		yzoom: 320
	});

	$('#invite-add-contacts').click(function() {
		$('#dialog-form').dialog('open');
		return false;
	});

	$('#open_inv_select_all').click(function() {
		$('#open_inv_table').find('tbody input').attr('checked', $(this).attr('checked'));
	});

	if($.fn.dialog) $("#dialog-form").dialog({
		autoOpen: false,
		height: 430,
		width: 350,
		modal: true,
		buttons: {
			'Continua': function() {
				$('#inv-loader').fadeIn();
				var plugin = $('#dialog-form').find('input[type="radio"]:checked').val();
				var user = $('#dialog-form').find('input[name="user"]').val();
				var pass = $('#dialog-form').find('input[name="pass"]').val();
				var el = $(this);
				$.ajax({
					url:		$('#dialog-form').attr('rel'),
					dataType:	'json',
					type:		'post',
					data:		{
						plugin:	plugin,
						user:	user,
						pass:	pass
					},
					success:	function(response) {
						$('#inv-loader').fadeOut();
						if(response.type && response.type == 'success') {
							var box = $('#open_inv_table').show().find('tbody');
							$.each(response.contacts, function(i, contact) {
								$('<tr />').html('<td><input type="checkbox" checked name="contacts[]" value="' + contact.id + '" /></td><td>' + contact.name + '</td><td>' + (contact.email && (''+contact.email).indexOf('#') != -1 ? contact.email : '&nbsp;') + '</td><td><img src="' + config.base_url + '/assets/invite/' + contact.network + '_icon.png" /></td>').appendTo(box);
							});
							el.dialog('close');
						} else {
							alert('Contul sau parola nu sunt corecte. Te rugam sa mai incerci odata.');
						}
					}
				});
			},
			'Anuleaza': function() {
				$(this).dialog('close');
			}
		}
	});

	if($.fn.dialog) $("#dialog-email").dialog({
		autoOpen: false,
		height: 250,
		width: 350,
		modal: true,
		buttons: {
			Trimite: function() {
				var el = $(this);
				$.ajax({
					url:		$('#dialog-email').attr('rel'),
					dataType:	'json',
					type:		'post',
					data:		$('#dialog-email input[type="text"], #dialog-email input[type="hidden"]').serialize(),
					success:	function(response) {
						if(response.type && response.type == 'success') {
							el.dialog('close');
							alert('Mesajul a fost trimis.');
						} else {
							alert('Mesajul nu a putut fi trimis. Te rugam sa mai incerci odata.');
						}
					}
				});
			},
			Anuleaza: function() {
				$(this).dialog('close');
			}
		}
	});

	$('#single-product .tell_friend .email').click(function() {
		$('#dialog-email').dialog('open');
		return false;
	});

	if($.fn.dialog) $("#dialog-sizes").dialog({
		autoOpen: false,
		height: 250,
		width: 350,
		modal: true,
		buttons: {
			Inchide: function() {
				$(this).dialog('close');
			}
		}
	});

	$('#sizes-help').click(function() {
		$('#dialog-sizes').dialog('open');
		return false;
	});

	$('#address_same').click(function() {
		$('#delivery_address').toggle(!$(this).attr('checked'));
	});

	if($('#related').length) $('#related .title a').click(function() {
		var prods = $('#related .content .rel_product');
		var current = parseInt($('#related .content').attr('rel'), 10);
		var next = current + 1 * ($(this).hasClass('alignLeft') ? -1 : 1);

		if(next > prods.length - 1) next = 0;
		if(next < 0) next = prods.length - 1;

		$('#related .content').attr('rel', next);

		prods.eq(next).show().siblings().hide();

		return false;
	});

	$('.faq-item a.question').click(function() {
		$(this).parent().parent().find('.answer').slideToggle();
		return false;
	});

	$(window).scroll(function() {
	    var bottom = $(document.body).height() - $(window).height() - $(window).scrollTop();
	    $('#bg').animate({top: (bottom < 100 && $(window).height() < 550 ? - 120 : 0)}, 'fast');
	});

	if($.fn.tooltip) $('.tooltip').tooltip('#demotip');
	
	if($('#table-stocuri').length) {
		$('#table-stocuri').dataTable({
			bJQueryUI:	true,
			bFilter:	false,
			oLanguage:	{
				sLengthMenu:"_MENU_ produse pe pagina",
				sInfo:		"Produsele _START_ - _END_ din _TOTAL_"
			},
			sPaginationType:	"full_numbers",
			bInfo:		false,
			aaSorting:	[[1, "asc"]]
		});
	}
	
	if($('#delivery_price').length) {
		$('input[name="transport"]').change(function() {
			var sum = parseInt($(this).val(), 10);
			$('#delivery_price').text(sum);
			$('#the_total').text(parseInt($('#the_total').attr('rel'), 10) + sum);
			$.ajax({
				url:		config.base_url + 'cos/change_delivery',
				dataType:	'json',
				type:		'post',
				data:		{delivery: $('input[name="transport"]:checked').attr('rel')}
			});
		});
	}
	$('#back-to-top a').click(function() {
		$(window).scrollTo(0, 0, {duration: 1000});
	});
});

function pretty_date(time) {
	time = parseInt(time, 10);
	var week = 3600 * 24 * 7;
	var day = 3600 * 24;
	var hour = 3600;
	var minute = 60;
	var pretty_date = '';

	if(time > week) {
		weeks = Math.floor(time / week);
		pretty_date += weeks + ' ' + (weeks > 1 ? 'saptamani' : 'saptamana') + ', ';
		time = time - weeks * week;
	}
	if(time > day) {
		days = Math.floor(time / day);
		pretty_date += days + ' ' + (days > 1 ? 'zile' : 'zi') + ', ';
		time = time - days * day;
	}
	if(time > hour) {
		hours = Math.floor(time / hour);
		pretty_date += hours + ' ' + (hours > 1 ? 'ore' : 'ora') + ', ';
		time = time - hours * hour;
	}
	if(time > minute) {
		minutes = Math.floor(time / minute);
		pretty_date += minutes + ' ' + (minutes > 1 ? 'minute' : 'minut') + '  ';
		time = time - minutes * minute;
	}

	//pretty_date += time + ' secunde.';
	return pretty_date;
}

if(typeof sIFR == "function"){
	var font_myriad = config.base_url + 'assets/myriad-pro-cond.swf';
	
	//, #cart .title
	sIFR.replaceElement("h2.fancy", named({sFlashSrc: font_myriad, sColor: "#ffffff", sWmode: 'transparent'}));
	
	sIFR.replaceElement("#sidebar h3, #single-product #info h2", named({sFlashSrc: font_myriad, sColor: "#000000", sWmode: 'transparent'}));
	//sIFR.replaceElement("#cart .content", named({sFlashSrc: font_myriad, sColor: "#00b3ff", sWmode: 'transparent'}));
	sIFR.replaceElement("#products .product .price, #single-product #info2 .price", named({sFlashSrc: font_myriad, sColor: "#0082b9", sWmode: 'transparent'}));
	sIFR.replaceElement("#products .product .price2", named({sFlashSrc: font_myriad, sColor: "#484848", sWmode: 'transparent'}));
};

