/**
 * A Siten Eventek
 *
 * @package    mvo
 * @subpackage site
 * @author     Szijártó Tamás ( szicsu ) <szicsu@jquery.hu>
 * @version    SVN: $Id: $
 */
Site.Events.weeklyMenu = function(){
	
	weeklyMenuManager.init();

}


Site.Events.passwordMatch = function(){
	//TODO: ezt általáosabbra kell megcsinálni :)
	
	$('form.jsPasswordMatch input:password').bind('blur, keyup',function( e ){
	
		var masterPsw = false;
		var matched = true;
		
		var matchObj = $('#jsPasswordMatch');
		var notMatchObj = $('#jsPasswordNotMatch');
		
		matchObj.hide();
		notMatchObj.hide();
		
		
		$('form.jsPasswordMatch input:password').each(function(){
			
			if( masterPsw === false ){
				masterPsw = this.value;
			}
			else if( masterPsw != this.value ){
				matched = false;
				return false;
			}
		});
		
		if( matched ){
			matchObj.show();
		}
		else{
			notMatchObj.show();
		}
		
	});
}

/**
 * Regisztrációs hosszú kérdőív
 */
Site.Events.registration_questionnaireIndex = function(){

	questionnaireManager
		.init( $("#jsQuestionnaireContainer") )
		.initDependency();
	
}

/**
 * billboard
 */
 Site.Events.billboard = function(){
	
	billboardManager.init( $('#jsBillboardConatiner') );
	billboardManager.initTimer( 3000 );

	/* scroller */
	$('.jsScrollPrev').bind('click', function(){
		listPosition = $('.bbUL_list ul').css('left');
		listPositionFloat = parseFloat(listPosition);
		if ( listPositionFloat >= 0 ) {
			return false;
		} else {
			listPositionAdded = listPositionFloat + 51;
			$('.bbUL_list ul').animate({'left': listPositionAdded+'px'}, 100);
			return false;
		}
	});

	$('.jsScrollNext').bind('click', function(){
		listPosition = $('.bbUL_list ul').css('left');
		listPositionFloat = parseFloat(listPosition);
		listItemsNum = $('.bbUL_list ul li').size();
		listItemsWidth = listItemsNum * 51;
		listItemsLimit = -(listItemsWidth - 306);
		if ( listPositionFloat <= listItemsLimit ) {
			return false;
		} else {
			listPositionAdded = listPositionFloat - 51;
			$('.bbUL_list ul').animate({'left': listPositionAdded+'px'}, 100);
			return false;
		}
	});
 }
 
 /**
 * Webshop
 */
 Site.Events.webshopIndex = function(){
 
	$('.jsWebshopViewLink').bind( 'click', function(event){ 
		$.ajax({ 
			url: $(this).attr('href'),
			dataType: 'html', 
			success: function( ret ){ 
				dialogManager.open({
					title: __('My World') +' - '+ __('Webshop'),
					height: 500,
					text: ret
				}, function( dialogObj ){
					dialogObj.find('.jsWebshopDialogOrderLink').bind('click',function(){
						$('#jsOrderLink_' + this.id ).trigger('click');
						return false;
					});
				});
			} 
		});    
		return false;
	});

	$('.jsWebshopOrderLink').bind( 'click', function(event){ 
		$.ajax({ 
			url: $(this).attr('href'),
			dataType: 'html', 
			success: function( ret ){ 
				info( ret );
			} 
		});    
		return false;
	});
 }
 
/**
  *
  */
Site.Events.usersEditprofilevisibility = function(){

	$("input[name^='mvo_profile_visibility']").eq('2').bind('click', function(){
		$("input[name^='mvo_profile_visibility']")
			.filter("input[value='"+ $(this).val() +"']").not(this).trigger('click');
	});
}
 
 
 /**
 * CategoryFilter
 **/
 Site.Events.categoryFilter = function(){
	
	
	$('.jsCategoryFilter').bind('change.categoryFilter',function(){
		
		if( !$(this).val() ){
			return false;
		}
		
		var catId = $(this).val();
		var selectObj = $('#' + $(this).attr('rel') );
		
		$.ajax({ 
			url: Site.Helper.getSluggedUrl('/ajax/getCategoryChildren'),
			dataType: 'json', 
			data:{ id: catId },
			success: function( ret ){ 
				Site.Helper.Select.replaceOptions( selectObj, ret );
				selectObj.focus();
			} 
		});    
		
		return false;
	})
	.each(function(){
		if( !$(this).hasClass('jsNoAutoFilter') ){
			$(this).trigger('change.categoryFilter');
		}
	});
 }
 
 /**
 * Coupon
 */
 Site.Events.couponIndex = function(){

	$('.jsCouponView').bind( 'click', function(event){ 
		$.ajax({ 
			url: $(this).attr('href') + '?' +(new Date()).getTime(), //IE :(
			dataType: 'html', 
			success: function( ret ){ 
				dialogManager.open({
					title: __('My World') +' - '+ __('Coupon'),
					height: 500,
					text: ret
				}, function( dialogObj ){
					dialogObj.find('form').bind('submit', function(){return false;});
					dialogObj.find('.jsCouponPrint').bind('click',function(){
						
						if( !dialogObj.find('#jsShopSlug').val() ){
							dialogObj.find('#jsCouponShopError').show();
							return false;
						}
						
						var oForm = dialogObj.find('#jsCouponPrintForm'); 
						var sUrl = oForm.attr('action');
						sUrl+= '?slug=' + oForm.find('#jsCouponSlug').val();
						sUrl+= '&shop=' + oForm.find('#jsShopSlug').val();
						
						$('<iframe>')
							.attr('src', sUrl )
							.css({ visibility:'hidden', height: 0, width: 0 })
							.bind('load', dialogManager.close )
							.appendTo('body');
						
						if( $.browser.msie ){
							window.setTimeout( dialogManager.close, 5000 );
						}
						info(__('Please wait, printing in process!'));
						return false;
					});
				});
			} 
		});    
		return false;
	});
 }
 
 Site.Events.recipeSearch = function(){
	recipeSearchManager.init();
 }
 
 Site.Events.shopping_listEdit = function(){
	shoppingListManager.init();
 }

Site.Events.blogNewpost = function(){
    $("#blog_tags").autocomplete( Site.Helper.getSluggedUrl('/ajax/tagSearch'), {
        multiple: true,
        cacheLength: 20,
        minChars: 2,
        parse: function(data) {
            return $.map(eval(data), function(row) {
                return {
                    data: row,
                    value: row,
                    result: row
                }
            });
        },
        formatItem: function(item) {
            return item;
        }
    });
}

Site.Events.messagesActions = function(){
	/* multiple-t leszedjuk a selectekrol */
	$('.messagesActions #message_recipients').removeAttr("multiple");
	$('.messagesActions #message_recipients').removeAttr("name");
	var recipientsArr = [];
	REitem = $('#REitem a').attr('rel');
	if ( REitem > '') {
		recipientsArr.push ( REitem );
	}

	/* hozzaadas */
	$('.messagesActions .add_recipient').live('click', function() {

		/* select elerese */
		selectRecipient = $('#message_recipients option:selected');

		/* recipient value es nev */
		recipientName = selectRecipient.text();
		recipientValue = selectRecipient.val();

		/* recipient html es input(hidden) */
		recipientHTML = '<li><span>' + recipientName + '</span><a href="#" rel="' + recipientValue + '" title="' + __("Delete") + '" class="delete_recipient">' + __("Delete") + '<span class="fir png">&nbsp;</span></a></li>';
		recipientHIDDEN = '<input type="hidden" name="message[recipients][]" value="' + recipientValue + '" id="' + recipientValue + '" />';

		/* volt-e mar? */
		benneE = $.inArray ( recipientValue, recipientsArr );

		if ( benneE == -1 ) {
			/* ha meg nem volt */
			recipientsArr.push ( recipientValue );
			/* kiiras html-be */
			$('#recipients_list').append(recipientHTML);
			$('#recipients_hiddens').append(recipientHIDDEN);
		} else {
			/* ha mar volt */
			alert(__("User already added"));
		}
		if ( recipientsArr.length > 0 ) {
			$('#recipientsList').hide();
		} else {
			$('#recipientsList').show();
		}
		return false;
	});

	/* torles */
	$('.messagesActions .delete_recipient').live('click', function() {
		recipientID = $(this).attr('rel');
		$(this).parent().remove();
		$('#' + recipientID).remove();
		recipientsArr = $.grep( recipientsArr, function ( a ) {
			return a != recipientID;
		});
		if ( recipientsArr.length > 0 ) {
			$('#recipientsList').hide();
		} else {
			$('#recipientsList').show();
		}
		return false;
	});

}

Site.Events.brand_stock_marketIndex = function() {
	$('.jsBSMBuyLink').bind('click', $.BSMDialog );
	$('#jsTransPiece').live('keyup', $.BSMCalculate );
	$('#jsTransPrice').live('keyup', $.BSMCalculate );
}

Site.Events.brand_stock_marketPortfolio = function() {
	$('.jsBSMSellLink').bind('click', $.BSMDialog );
	$('#jsTransPiece').live('keyup', $.BSMCalculate );
	$('#jsTransPrice').live('keyup', $.BSMCalculate );
}

$.BSMCalculate = function() {
	var tTimer;
	clearTimeout(tTimer);
	var oSource = $(this);
	var fPrice  = parseFloat($('.BOX_BRANDSTOCKMARKETTRANS ul li').eq(1).text().split(':')[1]);
	if ( parseInt(oSource.val()) ) {
		switch ( this.id ) {
			case 'jsTransPiece':
				$('#jsTransPrice').val(parseInt(oSource.val()) * fPrice);
				var iFee = Math.round(parseInt(oSource.val()) * fPrice * 0.1);
				$('#jsTransFee').val(iFee>0?iFee:1);
				break;
			case 'jsTransPrice':
				tTimer = setTimeout(function(){
					var amount = Math.floor(oSource.val() / fPrice);
					if ( oSource.val() && amount > 0 ) {
						$('#jsTransPiece').val(amount);
						$('#jsTransPrice').val(amount * fPrice);
						var iFee = Math.round(amount * fPrice * 0.1);
						$('#jsTransFee').val(iFee>0?iFee:1);
					} else {
						$('#jsTransPiece').val('');
						$('#jsTransPrice').val('');
						$('#jsTransFee').val('1');
					}
				}, 500);
				break;
		}
	} else {
		$('#jsTransPiece').val('');
		$('#jsTransPrice').val('');
		$('#jsTransFee').val('1');
	}
}

$.BSMDialog = function() {
	$.ajax({
		url: $(this).attr('href'),
		dataType: 'html',
		success: function(ret) {
			if ( ret.substr(0, 1) != '@' ) {
				dialogManager.open({
					title: __('Brand Stock Market'),
					height: 200,
					text: ret
				}, function( dialogObj ){
					dialogObj.find('.jsButton').bind('click', function() {
						$.ajax({
							url: dialogObj.find('form').attr('action'),
							type: 'POST',
							data: dialogObj.find('form').serialize(),
							dataType: 'html',
							success: function(ret) {
								if ( ret.substr(0, 1) == '@' ) {
									dialogManager.close();
									location.href = location.href;
								} else {
									dialogObj.find('#message').html(ret);
								}
							}
						})
						return false;
					})
				});
			}
		}
	});
	return false;
}

Site.Events.top21Index = function() {
	$('.brand_item:not(.disabled)').live('click', function() {
		if ( $('#jsUserSelection img').length < 6 ) {
			var imgObj = $(this).find('img').clone();
			imgObj.addClass('selected');
			$('#jsUserSelection').append(imgObj);
			$(this).css({'opacity' : 0.4}).addClass('disabled');
			$('#jsInputPoint').trigger('keyup');
		} else {
			alert( __('The maximum number is selected.') );
		}
	})

	$('img.selected').live('click', function() {
		var iBrandId = $(this).attr('id');
		$('.brand_item img#' + iBrandId).parent().parent().css({'opacity' : 1}).removeClass('disabled');
		$(this).remove();
		$('#jsInputPoint').trigger('keyup');
	})

	$('#jsTop21Form input[type=submit]').bind('click', function() {
		$('#jsInputHidden').val($('#jsUserSelection img').map(function(){return $(this).attr('id')}).get().join(','));
		$.ajax({
			url: $('#jsTop21Form').attr('action'),
			type: 'POST',
			data: $('#jsTop21Form').serialize(),
			dataType: 'html',
			success: function(ret) {
				if ( ret.substr(0, 1) == '@' ) {
					dialogManager.close();
					location.href = location.href;
				} else {
					alert(ret);
				}
			}
		})
		return false;
	})

	var tTimer;
	$('#jsInputPoint').bind('keyup', function() {
		clearTimeout(tTimer);
		var brandCount = $('#jsUserSelection img').length;
		var amount = parseInt($(this).val());
		if ( amount && brandCount > 1 ) {
			$('#jsInputWin').val(amount*brandCount);
		} else {
			$(this).val('');
			$('#jsInputWin').val('');
		}
	})

	$('#jsInputWin').bind('keyup', function() {
		clearTimeout(tTimer);
		var self = this;
		var brandCount = $('#jsUserSelection img').length;
		var amount = parseInt($(self).val());
		tTimer = setTimeout(function(){
			if ( amount && brandCount > 1 ) {
				$('#jsInputPoint').val(Math.floor(amount/brandCount));
				$(self).val(Math.floor(amount/brandCount)*brandCount);
			} else {
				$(self).val('');
				$('#jsInputPoint').val('');
			}
		}, 300);
	})

}

Site.Events.flashgameRecipe = function() {
	var oDiv = $('div#flashgame');
	var sHash = oDiv.attr('hash');
	oDiv.flash( '/swf/recipe_game.swf', {
		width: '650px',
		height: '390px',
		flashvars: {
			pHash: sHash
		},
		paremeters: {
			wmode: 'transparent',
			quality: 'high'
		}
	});
}

Site.Events.promo_reg_apiIndex = function() {
	$.mask.definitions['#'] = '[0-1]';
	$.mask.definitions['%'] = '[0-2]';
	$.mask.definitions['§'] = '[0-3]';
	$.mask.definitions['¤'] = '[0-5]';
	$.mask.definitions['×'] = '[2,3,7]';
	$('#promotion_purchase').mask("2011-#9-§9 %9:¤9");
	$('#promotion_phone').mask("36-×0-999-9999");
	$('#promotion_captcha').mask("****", {placeholder:" "});

	if ( typeof aError != 'undefined' ) {
		alert(aError.join('<br />'))
	}
}
