function openLink( href ) {
	window.open(href);
}

var Application = new JS.Class( {

  initialize : function() {
    $( document ).ready( function() {
      App.init();
    } );
  },

  init : function() {
  },

  run : function() {
  },

  parseHref : function() {
  	/*var href = this.getHref();
 		return href.split( '/' );*/
  },

  // hack! ha majd kell a nyitóoldalon a régi megoldás akkor vissza kell állítani "#termekek/kiemeltek"
  getHref : function() {
  	//var slices = window.location.href.split( '#' );
 		//return slices[ 1 ] || '';
  }

} );

var MainApplication = new JS.Class( Application, {

  init : function() {
    this.callSuper();
    this.run();
    this.signupBoxFocus();
    this.productVerticalText();
    this.Cart.initQuantities();
    this.Cart.Order.initHistory();
    this.initLoginSubmit();
		this.newsletterInit();
		this.profileInit();
		this.signupInit();
	//	this.goProductList();
		this.initLinkListAction();
    //$( 'img' ).lazyload( { placeholder : URI_STATIC + 'images/dummy.png', effect : 'fadeIn' } );
  },

  /**
   * Keresés
   */
  Search : {

  	/**
  	 * Kereső form ellenőrzése
  	 */
  	checkSubmit : function() {

  		var valid  = false;
  		var fields = $( '#searchForm input[name!=relation][name!=ebook], #searchForm select' );

  		$.each( fields, function( index, field ) {
  			if(
  				( $( field ).attr( 'id' ) != 'category' && $( field ).val() ) ||
  				( $( field ).attr( 'id' ) == 'category' && $( field ).val() > 0 )
  			) {
  				valid = true;
  			}
  		} );

  		return valid;

  	}

	},

  /**
   * Kuponok beváltása
   */


  addCampaign: function( event ){

    var element;


    event.preventDefault();
    var couponForm = $( '#couponForm' )[0];
    if (couponForm.ak_autoIncrement){
        ++couponForm.ak_autoIncrement;
    } else {
        couponForm.ak_autoIncrement=1;
    }

    var nextIndex = couponForm.ak_autoIncrement;
    if (language == 'hu')
     var couponuse = 'Bevált';
    else
     var couponuse = 'Use';

        $( '#couponForm' ).append( element = $( '<div class="morecoupon"><input type="text" name="coupons['+nextIndex+']"><input  type="checkbox" name="coupon_discount[]" value="'+nextIndex+'" />' + couponuse + '<a class="remove" href="#"> X </a></div>' )  );

element.children( 'a' ).bind(
      'click',
      {},
      event.data.obj.removeCampaign
    );

    $( '#couponForm div:first a.remove' ).show();

    element.children('input[type="checkbox"]').click(App.Cart.Check);
  },

  removeCampaign: function( event ){

    event.preventDefault();

    $( this ).parent().remove();

    if ($( '#couponForm div.morecoupon' ).length == 1){
        $( '#couponForm div a.remove' ).hide();
    }
  },

  Campaign : function(){

    $( '#campaignAdd' ).bind(
      'click',
      {obj: this},
      this.addCampaign
    );

    $( '#couponForm div:first a.remove' ).click(this.removeCampaign);
  },

  /**
   * Ajándékkönyvek
   */
  Gift : {

  	// Kiválasztottak száma
  	selecteds : 0,

  	// Limit
  	quantity : 0,

  	/**
  	 * Kiválasztás
  	 *  @param (integer) Termék ID
  	 */
  	Select : function( id, quantity ) {
  		App.Gift.quantity = quantity;
			$( '#gift_' + id ).addClass( 'selected' );
			App.Gift.updateSelecteds( App.Gift.selecteds + 1 );
			App.Gift.addID( id );
  	},

  	/**
  	 * Kiválasztás visszavonása
  	 *  @param (integer) Termék ID
  	 */
  	Cancel : function( id ) {
  		$( '#gift_' + id ).removeClass( 'selected' );
  		App.Gift.updateSelecteds( App.Gift.selecteds - 1 );
  		App.Gift.removeID( id );
  	},

  	/**
  	 * Kiválasztottak számának frissítése
  	 *  @param (integer) Kiválasztottak száma
  	 */
  	updateSelecteds : function( quantity ) {
  		App.Gift.selecteds = quantity;
  		$( '.js_gift_quantity' ).html( App.Gift.selecteds );
  		if( App.Gift.selecteds < App.Gift.quantity )
  			$( '#gifts' ).removeClass( 'noselect' );
  		else
  			$( '#gifts' ).addClass( 'noselect' );
  	},

  	/**
  	 * ID hozzáadása a listához
  	 *  @param (integer) ID
  	 */
  	addID : function( id ) {
  		var giftIDs = $( '#giftids' ).val();
  		if( giftIDs )
  			giftIDs += ',';
  		giftIDs += id + '';
  		$( '#giftids' ).val( giftIDs );
  	},

  	/**
  	 * ID törlése a listából
  	 *  @param (integer) ID
  	 */
  	removeID : function( id ) {

  		var oldGiftIDs = $( '#giftids' ).val().split( ',' );
  		var newGiftIDs = [];
  		var giftIDs = '';

  		$.each( oldGiftIDs, function( index, giftID ) {
  			if( giftID != id )
  				newGiftIDs[ newGiftIDs.length ] = giftID;
  		} );

  		$.each( newGiftIDs, function( index, giftID ) {
  			giftIDs += giftID + '';
  			if( index < newGiftIDs.length - 1 )
  				giftIDs += ',';
  		} );

  		$( '#giftids' ).val( giftIDs );

  	},

  	/**
  	 * Lista léptetése
  	 *  @param Lépések száma
  	 */
  	Step : function( change ) {
  		var left  = $( '.js_gift_list' ).scrollLeft();
  		var width = $( '#gifts li:first' ).width() + 7;
  		$( '.js_gift_list' ).scrollLeft( left + ( width * change ) );
  	},

  	/**
  	 * Ajándék könyv ID-k elkérése
  	 *  @return (string) Ajándék könyv ID-k, vesszővel elválasztva
  	 */
  	getGiftIDs : function() {
  		if( $( '#giftids' ).val )
  			return $( '#giftids' ).val();
  		return false;
  	}

  },

  /**
   * Login elküldésének inicializálása
   */
  initLoginSubmit : function() {

  	$( '#signinOuterForm' ).submit( function() {return App.signin();} );

  },

  /**
   * Felhasználó
   */
  User : {

  	/**
  	 * Jelszó gépeléskor lefutó esemény
  	 */
  	passChange : function() {

  		$( '.js_delete_form .js_label' ).removeClass( 'error' );

  	},

  	/**
  	 * Felhasználó törlése
  	 */
  	'delete' : function() {

  		var password = $( '.js_delete_form #password' ).val();
  		var password_retype = $( '.js_delete_form #password_retype' ).val();

  		if( password != password_retype || !password || !password_retype ) {

  			$( '.js_delete_form .js_label' ).addClass( 'error' );

  		} else {

  			$.ajax( {
  				cache   : false,
  				async   : false,
  				url     : URI_FRONTEND + 'ak/deleteprofile?password=' + password,
  				success : function( response ) {

  					if( response == 'success' ) {

  						$( '.js_delete_form' ).hide();
  						$( '.js_delete_success' ).show();

  						setTimeout( function() {
  							window.location.href = URI_FRONTEND;
  						}, 3000 );

  					} else {

  						$( '.js_delete_form .js_label' ).addClass( 'error' );

  					}

  				}
  			} );

  		}

  	}

  },

  /**
   * Kosár
   */
  Cart : {

    /**
     * Kupon ellenőrzés
     */
    Check: function(){

      var data    = $("form#couponForm").serialize();
          
  				$.post( URI_FRONTEND + 'ak/checkcampaign',
                  data,
                  function( response ) {

                    if( response.success  ) {
                       $( '.newcartitems' ).hide();
                       $( '.js_coupon_error' ).hide();
                       $( '.js_coupon_success' ).show();
                       $( '.js_coupon_success' ).html( response.html );
                       $( '.js_fullprice' ).html( response.fullprice );
                       App.Cart.Order.setPrice( response.fullprice );


                    } else {

                       if( response.oldcart ){
                         $( '.js_fullprice' ).html( response.oldprice );
                         App.Cart.Order.setPrice( response.oldprice );
                         $( '.js_coupon_success' ).hide();
                         $( '.newcartitems' ).show();
                       }
                       $( '.js_coupon_success' ).hide();
                       $( '.js_coupon_error' ).show();
                       $( '.js_coupon_error' ).html( response );
                    }

                  },
                  'json' );

    },

    /**
     * Kupon beváltása
     */
    CouponUse: /*function(){

      var data    = 10000;

  				$.post( URI_FRONTEND + 'ak/usecampaign',
                  data,
                  function( response ) {

                    if( response.success  ) {
                       $( '.js_coupon_fullprice' ).show();

                    } else {
                       $( '.js_coupon_fullprice' ).hide();

                    }

                  },
                  'json' );

    },*/
    {   Fullprice : function( fullprice ) {
       //alert(($('input[name="coupon_discount"]').attr('checked') ))

//alert($('input[name="coupon_discount"]:checked').val());
        if($('input[name="coupon_discount"]:checked').val() == 1 )
            $('input[name="coupon_discount"]').attr('checked', true);
         else
            $('input[name="coupon_discount"]').attr('checked', false);


  			//var input       = $( 'input[name="coupon_discount"]:checked' );
  			var fullprice   = fullprice * 1;
  			//var deliveryFee = input.attr( 'rel' ) * 1;
  			//var endprice    = fullprice + deliveryFee;
  			var endprice    = fullprice ;

  			//$( '.js_shipping_fee' ).html( deliveryFee );

                        if($('input[name="coupon_discount"]').attr('checked', true)){
                            $( '.js_coupon_fullprice_tr' ).show();
                            $( '.js_coupon_fullprice' ).html( endprice );

                        }
                        else{
                            $( '.js_coupon_fullprice_tr' ).hide();
                        }

  		}

    },

  	/**
  	 * Rendeléssel kapcsolatos műveletek
  	 */
  	Order : {

                price: null,

                setPrice: function( price ){

                    this.price = price;
                },

  		/**
  		 * Korábbi rendelések oldal inicializálása
  		 */
  		initHistory : function() {

  			$( '.js_toggle_order' ).click( function() {
  				var id = $( this ).attr( 'rel' );
  				var opened = $( this ).hasClass( 'opened' );
  				if( opened ) {
						$( '#toggle_order_' + id + ', #order_info_' + id ).removeClass( 'opened' );
					} else {
						$( '.js_toggle_order, .js_order_info' ).removeClass( 'opened' );
						$( '#order_info_' + id ).addClass( 'opened' );
					}
  			} );

  		},

  		/**
  		 * Fizetés mód váltásakor lefutó eseménykezelő
  		 *	@param	(int)	Utánvét, vagy átutalás
  		 */
  		changeBillingType : function( index ) {
  			$('input[name="deliveryType"]').attr('checked', false);
				$( 'div.delivery' ).hide();
				$( '#delivery' ).show( 'normal' );
				$( '.'+index ).show();

  		},

			/**
  		 * Szállítási mód váltásakor lefutó eseménykezelő
  		 *	@param	(float)	Eredeti végösszeg
  		 */
  		changeDeliveryType : function() {

  			var input       = $( 'input[name="deliveryType"]:checked' );
  			var fullprice   = this.price;
  			var deliveryFee = input.attr( 'rel' ) * 1;
  			var endprice    = fullprice + deliveryFee;

  			$( '.js_shipping_fee' ).html( deliveryFee );
  			$( '.js_fullprice'    ).html( endprice    );

  		},

  		/**
  		 * Rendelés elküldése
  		 */
  		Send : function( isOnlyEbook ) {

        

  			var deliveryType   = $( 'input[name="deliveryType"]:checked' ).val();
  			var billingType    = $( 'input[name="billingType"]:checked'  ).val();
  			var couponDiscount = $( 'input[name="coupon_discount"]:checked'  ).val();
  			var newsletters     = $( 'input[name="newsletter"]:checked'  ).val();
  			var termsAccepted  = $( '#terms_accept' ).attr( 'checked' );

  			var valid = true;
        var coupon_discount    = 0;
        if (couponDiscount){

          coupon_discount    = 1;

        }
         var newsletter    = 0;

         if (newsletters){

          newsletter  = 1;

        }

  			if ( !isOnlyEbook ){
				if( deliveryType )
					$( '.js_delivery_type_error' ).hide();
				else {
					$( '.js_delivery_type_error' ).show( 'normal' );
					valid = false;
				}
			}

  			if( billingType )
	  			$( '.js_billing_type_error' ).hide();
	  		else {
	  			$( '.js_billing_type_error' ).show( 'normal' );
	  			valid = false;
	  		}

  			if( termsAccepted )
	  			$( '.js_order_terms_error' ).hide();
	  		else {
	  			$( '.js_order_terms_error' ).show( 'normal' );
	  			valid = false;
	  		}

  			if( valid ) {

  				var gifts = App.Gift.getGiftIDs();

  				/*window.location.href = URI_FRONTEND +
  					'ak/order' +
  					'?delivery=' + deliveryType +
  					'&billing='  + billingType +
  					( gifts ? '&gifts=' + gifts : '' ); */

					setTimeout( function() {window.location = URI_FRONTEND +
  					'ak/order' +
  					'?delivery=' + deliveryType +
  					'&billing='  + billingType +
            ( newsletter ? '&newsletter=' +  newsletter : '&newsletter=' + 0 ) +
            ( couponDiscount ?'&coupon_discount=' +  coupon_discount : '&coupon_discount=' + 0 ) +

  					( gifts ? '&gifts=' + gifts : '' );}, 0 );

  			}

  		}

  	},

  	/**
  	 * Címekkel kapcsolatos műveletek
  	 */
  	Address : {

  		bUsed : '',
  		pUsed : '',

  		/**
  		 * Cím alkalmazása
  		 *	@param	(char)	Cím típusa (p: szállítási, b: számlázási)
  		 */
  		Use : function( type ) {

  			var json = $( '.js_' + type + '_select' ).val();

  			$( '.js_' + type + '_form input, .js_' + type + '_form select:not(.js_' + type + '_select)' ).val( '' );

  			if( json ) {
					$( '.js_' + type + '_modify' ).show();
    			eval( 'var data = ' + json + ';' );
    			App.Cart.Address[ type + 'Used' ] = data.id;
    		}else {
    			var data = [];
    			$( '.js_' + type + '_modify' ).hide();
    		}

  			$.each( data || [], function( key, value ) {
  				$( '#' + type + '_' + key ).val( value );
  			} );

  			if( type == 'p' && $( '.js_b_eq_p' ).attr( 'checked' ) )
  				App.Cart.Address.SameBilling();

  		},

  		/**
  		 * "Számlázási cím ugyanaz, mint a szállítási cím" - váltogatás
  		 */
  		SameBilling : function() {

  			var checked = $( '.js_b_eq_p' ).attr( 'checked' );

  			if( checked )
  				$( '.js_b_select' ).attr( 'disabled', 'disabled' );
  			else
  				$( '.js_b_select' ).attr( 'disabled', '' );


  			var fields = $( '.js_b_form input:not(.js_b_eq_p), .js_b_form select:not(.js_b_select)' );
  			$.each( fields, function( index, field ) {
  				var field = $( field );
  				field.val( '' );
  				if( checked )
  					field.attr( 'disabled', 'disabled' );
  				else
  					field.attr( 'disabled', '' );
  			} );

  			var fields = $( '.js_p_form input, .js_p_form select:not(.js_p_select)' );
  			$.each( fields, function( index, field ) {
					var field = $( field );
  				if( checked )
						$( '#' + field.attr( 'id' ).replace( 'p_', 'b_' ) ).val( field.val() );
  				else
						$( '#' + field.attr( 'id' ).replace( 'p_', 'b_' ) ).val( '' );
  			} );

  		},

  		/**
  		 * Cím módosítása
  		 *	@param	(char)	Cím típusa (p: szállítási, b: számlázási)
  		 */
  		Modify : function( type ) {

  			// Ha valid az űrlap, akkor feldolgozzuk és módosítunk
  			if( App.Cart.Address.validateForm( type ) ) {

  				var data = App.Cart.Address.fetchForm( type );
					data[ 'id' ] = App.Cart.Address[ type + 'Used' ];

  				$.ajax( {
  					cache    : false,
  					async    : false,
  					url      : URI_FRONTEND + 'ak/' + type + 'addressmodify',
  					data     : data,
  					type     : 'post',
  					dataType : 'html',
  					success  : function( response ) {
  						response = response.split( '|' );
  						var value = response[ 0 ];
  						var text  = response[ 1 ];
  						$( '.js_p_insert_success' ).hide();
  						$( '.js_p_modify_success' ).hide();
  						$( '.js_b_insert_success' ).hide();
  						$( '.js_b_modify_success' ).hide();
  						$( '.js_' + type + '_modify_success' ).show( 'normal' );
  						var option = $( '.js_' + type + '_select' ).children( 'option:selected' );
		  						option.attr( 'value', value.replace( /\"/gi, "'" ) );
		  						option.html( text );
  					}
  				} );

  				return true;

  			}

  			// Különben hibával térünk vissza
  			else return false;

  		},

  		/**
  		 * Cím mentése újként
  		 *	@param	(char)	Cím típusa (p: szállítási, b: számlázási)
  		 */
  		Insert : function( type ) {


  			// Ha valid az űrlap, akkor feldolgozzuk és módosítunk
  			if( App.Cart.Address.validateForm( type ) ) {

  				$.ajax( {
  					cache    : false,
  					async    : false,
  					url      : URI_FRONTEND + 'ak/' + type + 'addressinsert',
  					data     : App.Cart.Address.fetchForm( type ),
  					type     : 'post',
  					success  : function( response ) {
  						response = response.split( '|' );
  						var value = response[ 0 ];
  						var text  = response[ 1 ];
							eval( 'var data = ' + value + ';' );
							App.Cart.Address[ type + 'Used' ] = data.id;
  						$( '.js_p_insert_success' ).hide();
  						$( '.js_p_modify_success' ).hide();
  						$( '.js_b_insert_success' ).hide();
  						$( '.js_b_modify_success' ).hide();
  						$( '.js_' + type + '_insert_success' ).show( 'normal' );
  						$( '.js_' + type + '_select' ).append( '<option value="' + value + '" selected="selected">' + text + '</option>' );
  						$( '.js_' + type + '_select' ).show();
  					}
  				} );

  				return true;

  			}

  			// Különben hibával térünk vissza
  			else return false;

  		},

  		/**
  		 * Cím alkalmazása
  		 *	@param	(string)	URL, ahová sikeres alkalmazás után dobni kell
  		 */
  		Set : function( url ) {

  			// Űrlapok validálása
  			var valid = true;
  					valid = ( !App.Cart.Address.validateForm( 'p' ) ? false : valid );
  					valid = ( !App.Cart.Address.validateForm( 'b' ) ? false : valid );

  			// Ha valid mindkét űrlap, akkor feldolgozzuk és alkalmazzuk
  			if( valid ) {

					var data    = {};
					var postal  = App.Cart.Address.fetchForm( 'p' );
					var billing = App.Cart.Address.fetchForm( 'b' );
					$.each( postal , function( field, value ) {if( field ) data[ 'postal['  + field + ']' ] = value;} );
					$.each( billing, function( field, value ) {if( field ) data[ 'billing[' + field + ']' ] = value;} );

  				$.ajax( {
  					cache    : false,
  					async    : false,
  					url      : URI_FRONTEND + 'ak/setaddresses',
  					type     : 'post',
  					data     : data,
  					success  : function( response ) {
  						if( response )
  							//window.location.href = response;
								setTimeout( function() {window.location = response;}, 0 );
  					}
  				} );

  			}

  		},

  		/**
  		 * Űrlap validálása típus alapján
  		 *	@param	(char)	Cím típusa (p: szállítási, b: számlázási)
  		 */
  		validateForm : function( type ) {

  			var valid = true;

  			// Mezők kigyűjtése a megfelelő űrlapból
  			var fields = $( '.js_' + type + '_form input, .js_' + type + '_form select' );

  			// Mezők validálása
  			$.each( fields || [], function( index, field ) {

  				var field = $( field );
  				var vrule = field.attr( 'rel' );

  				if( typeof vrule != 'undefined' ) {

  					if( !App.Cart.Address.validateField( field, vrule, type ) )
  						valid = false;

  				}

  			} );

  			return valid;

  		},

  		/**
  		 * Mező validálása
  		 *	@param	(object)	Validálandó mező (jQuery objektum)
  		 *	@param	(string)	Validálási szabály
  		 *	@param	(char)		Cím típusa (p: szállítási, b: számlázási)
  		 */
  		validateField : function( field, vrule, type ) {

  			var vrule = vrule.split( ':' );
  			var value = field.val();
  			var validation = vrule[ 0 ];
  			var condition  = vrule[ 1 ];
  			var valid = App.Cart.Address.Validations[ validation ]( condition, value );

  			if( valid )
  				$( 'label[for="' + field.attr( 'id' ) + '"]' ).removeClass( 'error' );
  			else {
  				window.scrollTo( 0, $( 'label[for="' + field.attr( 'id' ) + '"]' ).offset().top - 30 );
  				$( 'label[for="' + field.attr( 'id' ) + '"]' ).addClass( 'error' );
				if (language == 'hu')
				  App.layer( 'Kérem töltse ki a kötelező mezőket!' );
				else
				  App.layer( 'Fields marked with an asterisk (*) are requied.' );
  			}

  			return valid;

  		},

  		/**
  		 * Űrlap feldolgozása típus alapján
  		 *	@param	(char)	Cím típusa (p: szállítási, b: számlázási)
  		 */
  		fetchForm : function( type ) {

  			var data = {};

  			// Mezők kigyűjtése a megfelelő űrlapból
  			var fields = $( '.js_' + type + '_form input, .js_' + type + '_form select' );

  			// Mezők értékeinek kinyerése
  			$.each( fields || [], function( index, field ) {
  				var field = $( field );
  				data[ field.attr( 'id' ).replace( type + '_', '' ) ] = field.val();
  			} );

  			// Visszatérés a kinyert értékekkel
  			return data;

  		},

  		/**
  		 * Validációk
  		 */
  		Validations : {

  			/**
  			 * Kötelezőség
  			 */
  			required : function( condition, value ) {
  				return ( condition !== 'false' ? ( value ? true : false ) : true );
  			},

  			/**
  			 * Kötelezőség, ha nincs kitöltve egy másik mező
  			 */
  			requiredIfNotFilled : function( condition, value ) {
  				var v = $( '#' + condition ).val();
  				if( !v )
  					return ( !value ? false : true );
  				return true;
  			},

  			/**
  			 * Kötelezőség, ha ki van töltve egy másik mező
  			 */
  			requiredIfFilled : function( condition, value ) {
  				var v = $( '#' + condition ).val();
  				if( v )
  					return ( !value ? false : true );
  				return true;
  			},

  			/**
  			 * Formátum
  			 */
  			format : function( condition, value ) {

  				var regexp = '.+';
  				switch( condition ) {

						//case 'zip'   :  if ( $('this.parent').val() == '89' || $('#b_countries_id').val() == '89' ) regexp = '^[0-9]{4}$'; break;
  					case 'email' :regexp = '^[\._0-9a-z-]+@[0-9a-z][-0-9a-z\.]*\.[a-z]{2,4}$';break;
  				}

  				var regexp = new RegExp( regexp );
  				return ( value.match( regexp ) ? true : false );

  			}

  		}

  	},

  	/**
  	 * Darabszám állítások inicializálása
  	 */
  	initQuantities : function() {

  		var inputs = $( '.js_cart_quantity_field' );

  		$.each( inputs || [], function( index, field ) {

  			var field = $( field );

  			field.keyup( function( e ) {
  				field.val( field.val().replace( /[^0-9]/gi, '' ) );
  				if( e.keyCode == 13 )
  					App.Cart.changeQuantity( field );
  			} );

  			field.change( function() {
  				App.Cart.changeQuantity( field );
  			} );

  		} );

  	},

  	/**
  	 * Darabszám állítása
  	 */
  	changeQuantity : function( field ) {

  		$( '.js_cart_quantity_field' ).attr( 'disabled', 'disabled' );
  		window.location.href = URI_FRONTEND + 'ak/cartqtychange?id=' + field.attr( 'rel' ) + '&qty=' + field.val();

  	},

  	/**
  	 * Kosárhoz adás termék ID alapján
  	 */
  	add : function( productID ) {

  		$.ajax( {
  			url   : URI_FRONTEND + 'ak/addtocart',
  			data  : {productID : productID},
  			type  : 'post',
  			cache : false,
  			async : false,
  			complete : function( xhr ) {

  				var response = xhr.responseText.split( '|' );

  				if( response.length == 3 ) {

						var quantity   = response[ 0 ];
						var fullprice  = response[ 1 ];
						var percentage = response[ 2 ];

						$( '.js_minicart_percentage' ).effect( 'pulsate', {times : 2, duration : 750} );
						$( '.js_minicart_percentage' ).animate( {'width' : percentage + '%'} );
						$( '.js_minicart_quantity' ).html( quantity );
						$( '.js_minicart_fullprice' ).html( fullprice );
						$( '.js_minicart_button' ).show();

						window.scrollTo( 0, $( '.bk_cart-smalldisplay' ).scrollTop() );

						if( quantity == 1 ) {
							$( '.js_minicart_quantity_more' ).hide();
							$( '.js_minicart_quantity_one' ).show();
						} else {
							$( '.js_minicart_quantity_one' ).hide();
							$( '.js_minicart_quantity_more' ).show();
						}

  				} else {

  					App.layer( response[ 0 ] );

  				}

  			}
  		} );

  	},


    /**
  	 * Kosárhoz adás termék ID alapján - nyomtatott + e-book
  	 */
  	addAll : function( productID, ebookID ) {

  		$.ajax( {
  			url   : URI_FRONTEND + 'ak/addalltocart',
  			data  : { productID : productID, ebookID : ebookID},
  			type  : 'post',
  			cache : false,
  			async : false,
  			complete : function( xhr ) {

  				var response = xhr.responseText.split( '|' );

  				if( response.length == 3 ) {

						var quantity   = response[ 0 ];
						var fullprice  = response[ 1 ];
						var percentage = response[ 2 ];

						$( '.js_minicart_percentage' ).effect( 'pulsate', { times : 2, duration : 750 } );
						$( '.js_minicart_percentage' ).animate( { 'width' : percentage + '%' } );
						$( '.js_minicart_quantity' ).html( quantity );
						$( '.js_minicart_fullprice' ).html( fullprice );
						$( '.js_minicart_button' ).show();

						window.scrollTo( 0, $( '.bk_cart-smalldisplay' ).scrollTop() );

						if( quantity == 1 ) {
							$( '.js_minicart_quantity_more' ).hide();
							$( '.js_minicart_quantity_one' ).show();
						} else {
							$( '.js_minicart_quantity_one' ).hide();
							$( '.js_minicart_quantity_more' ).show();
						}

  				} else {

  					App.layer( response[ 0 ] );

  				}

  			}
  		} );

  	},


    /**
  	 * Előrendelés a termék ID alapján
  	 */
  	preOrder : function( productID ) {

  		$.ajax( {
  			url   : URI_FRONTEND + 'ak/preorder',
  			data  : {productID : productID},
  			type  : 'post',
  			cache : false,
  			async : false,
  			complete : function( xhr ) {
  				App.layer( xhr.responseText );
				}
			} );

  	}

  },

  /**
   * Termék kiemelt/ajánlott/akciós feliratok SVG renderelése
   */
  productVerticalText : function() {

		// TODO: jobb pozicionalas (IE alatt is)
		$( '.js_product_vertical_text' ).each( function() {
			var _t = $( this );
			var txt = _t.html();
			_t.removeClass( 'js_product_vertical_text' );
			_t.html('');

			if ( $.browser.msie && $.browser.version == '6.0' ) {
				var _theight = _t.parent().height();
			} else {
				var _theight = _t.height();
			}

			var txtR = Raphael( _t.context, 33, _theight )
				.text( 0, 0, txt )
				.attr( {
						font : '24px "Trebuchet MS", Arial, sans-serif',
						fill : _t.css( 'color' )
					} )
					.rotate( -90 );

			var height = txtR.getBBox().width;
			txtR.attr( {x : 10 + ( ( $.browser.msie ) ? 3 : 0 ), y : _theight - ( height / 2 ) - 5} );

		} );

  },

 	/**
 	 * Ugrás a termék listához
 	 */
 /* goProductList : function() {

  	var params = App.parseHref();
  	var pos = 0;

  	if( !App.getHref() ) {
  		var postfix = $( '.bk_aklinklists-linklistaction li:first a' ).attr( 'href' );
  		if( postfix )
	  		window.location.href += postfix;
  	}

  	if( params[ 0 ] ==  'termekek' || params[ 0 ] == 'products' ) {
  		pos = parseInt( $( '.bk_aklinklists-linklistaction a[href="#' + App.getHref() + '"]' ).attr( 'rel' ) );
  	}

  	$( '.bk_aklinklists-linklistaction li' ).removeClass( 'selected' );
		$( '.bk_aklinklists-linklistaction a[href="#' + App.getHref() + '"]' ).parent().addClass( 'selected' );

		$( '.bk_akproducts-featureds .w' ).animate( {
			left: ( - parseInt( $( '.bk_akproducts-featureds .group' ).width() ) - 20 ) * pos + 'px'
		}, 500, 'easeInBack' );

  },
 */
 	/**
 	 * Link lista inicializálása
 	 */
  initLinkListAction : function() {

	/*	$( function () {

			App.goProductList();

			$( '.bk_aklinklists-linklistaction a' ).click( function() {
				setTimeout( App.goProductList, 50 );
			} );

		} ); */

  },

 	/**
 	 * Login és regisztrációs blokk animálása
 	 */
  signupBoxFocus : function() {

  	setTimeout( function() {

			var parts = window.location.href.split( '#' );

			if( parts[ 1 ] ) {

				switch( parts[ 1 ] ) {

					case 'Signup':
					case 'Regisztracio':
						$( '.pulsate' ).effect( 'pulsate', {times : 2, duration : 1000} );
					break;

					case 'Signin':
					case 'Belepes':
						$( '.bk_akusers-signin' ).effect( 'pulsate', {times : 2, duration : 1000} );
					break;

				}

			}

  	}, 250 );

  },

 	/**
 	 * Beléptetés
 	 */
 	signin : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/signin',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'signinForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText != 'failure' ) {
 					//window.location.href = xhr.responseText;
					setTimeout( function() {window.location = xhr.responseText;}, 0 );
 				} else {
					$( '#lostPasswordErrorForm .error' ).hide();
					$( '#signinSuccesForm .success' ).hide();
					$( '#signupErrorForm .error' ).hide();
					$( '#signinErrorForm .error' ).hide();
 					$( '#signinErrorForm .error' ).show();
					$( '#signinErrorForm .error' ).effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 		return false;

 	},

	/**
 	 * Elfelejtett jelszó
 	*/
 	lostpassword : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/lostpassword',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'signinForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
 					$( '#signinErrorForm .error' ).hide();
 					$( '#lostPasswordErrorForm .error' ).hide();
					$( '#signupErrorForm .error' ).hide();
					$( '#signinSuccesForm .success' ).show();
 				} else {
					$( '#signinErrorForm .error' ).hide();
					$( '#signinSuccesForm .success' ).hide();
					$( '#signupErrorForm .error' ).hide();
 					$( '#lostPasswordErrorForm .error' ).show();
					$( '#lostPasswordErrorForm .error' ).effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Regisztrációs blokk inicializálasa
 	 */
	signupInit : function() {

		$( '.bk_akusers-signup .newsletter .title input' ).change(function() {
			if ( $( this ).is( ':checked' ) ) {
				$( '.bk_akusers-signup .newsletter .cols' ).show();
				$( '.bk_akusers-signup .newsletter .col input' ).attr( 'checked', false );
			} else {
				$( '.bk_akusers-signup .newsletter .cols' ).hide();
			}
		});
	},

	/**
 	 * Regisztráció
 	 */
 	signup : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/signup',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'signupForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
 					//window.location.href = URI_FRONTEND;
					setTimeout( function() {window.location = URI_FRONTEND;}, 0 );
 				} else if( xhr.responseText == 'cimek' ) {
          setTimeout( function() {window.location = URI_FRONTEND + 'cimek';}, 0 );
        } else if( xhr.responseText == 'adresses' ) {
          setTimeout( function() {window.location = URI_FRONTEND + 'adresses';}, 0 );
        }else {
					$( '#lostPasswordErrorForm .error' ).hide();
					$( '#signinSuccesForm .success' ).hide();
 					$( '#signinErrorForm .error' ).hide();
 					$( '#signupErrorForm .error' ).html( xhr.responseText ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Hírlevél inicializálás
 	 */
	newsletterInit : function() {

		$( '.bk_akusers-newsletterregister .newsletter .title input' ).change(function() {
			if ( $( this ).is( ':checked' ) ) {
				$( '.bk_akusers-newsletterregister .newsletter .cols' ).show();
				$( '.bk_akusers-newsletterregister .newsletter .col input' ).attr( 'checked', false );
			} else {
				$( '.bk_akusers-newsletterregister .newsletter .cols' ).hide();
			}
		});
	},

	/**
 	 * Hírlevél regisztráció
 	 */
 	newsletterRegister : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/newsletterregister',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'newsletterRegisterForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
 					//window.location.href = window.location.href + '?success=1';
					setTimeout( function() {window.location = window.location + '?success=1';}, 0 );
 				} else {
					$( '#signinErrorForm .error' ).hide();
					$( '#lostPasswordErrorForm .error' ).hide();
 					$( '#newsletterRegisterErrorForm .error' ).html( xhr.responseText ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Profil inicializálás
 	 */
	profileInit : function() {

		$( '.bk_akusers-profiledisplay #newsletter' ).change(function() {
			if ( $( this ).is( ':checked' ) ) {
				$( '.bk_akusers-profiledisplay .newsletter .col' ).show();
			//	$( '.bk_akusers-profiledisplay .newsletter .col input' ).attr( 'checked', false );
			} else {
				$( '.bk_akusers-profiledisplay .newsletter .col' ).hide();
			}
		});
	},

	/**
 	 * Profil
 	 */
 	profile : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/profile',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'profileForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
					$( '#profileErrorForm .error' ).hide();
					$( '#profileSuccesForm .succes' ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				} else {
					$( '#profileSuccesForm .succes' ).hide();
					window.scrollTo( 0, 200 );
					$( '#profileErrorForm .error' ).html( xhr.responseText ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Profil normál felhasználó esetén
 	 */
 	profile : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/profile',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'profileForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
					$( '#profileErrorForm .error' ).hide();
					$( '#profileSuccesForm .succes' ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				} else {
					$( '#profileSuccesForm .succes' ).hide();
					window.scrollTo( 0, 200 );
					$( '#profileErrorForm .error' ).html( xhr.responseText ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Profil jelszó nélkül belépett felhasználó esetén
 	 */
 	profileOld : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/profileOld',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'profileForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
					$( '#profileErrorForm .error' ).hide();
					$( '#profileSuccesForm .succes' ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				} else {
					$( '#profileSuccesForm .succes' ).hide();
					window.scrollTo( 0, 200 );
					$( '#profileErrorForm .error' ).html( xhr.responseText ).show().effect( 'pulsate', {times : 2, duration : 1000} );
 				}

 			}
 		} );

 	},

	/**
 	 * Számlázási, vagy szállítási cím törlése
 	 */
 	deleteAddressDates : function( id, type) {

		//var data = [];
		var data = App.serializeForm( 'modify' + type + 'Form' );
		var confirm = window.confirm("Biztos törölni akarja?")

		data.id = id;
		data.type = type;

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/deleteaddressdates',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : data,
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' && confirm ) {
						window.location.reload();

 				} else {
					$( '#updateTransportForm .transport' ).hide();
					$( '#updateTransportFormError .error' ).hide();
					$( '#updateBillingFormError .error' ).hide();
					$( '#updateBillingForm .billing' ).hide();
 				}

 			}
 		} );

 	},
	/**
 	 * Szállítási cím módosítása
 	 */
 	updateTransport : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/updatetransport',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'updateTransportForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
 					window.location.reload();
 				} else {
					$( '#modifyBillingForm .billing' ).hide();
					$( '#updateBillingFormError .error' ).hide();
					$( '#updateTransportFormError .error' ).show();
					$( '#updateTransportForm .transport' ).show();
 				}

 			}
 		} );

 	},

	/**
 	 * Számlázási cím módosítása
 	 */
 	updateBilling : function() {

 		$.ajax( {
 			url    : URI_FRONTEND + 'ak/updatebilling',
 			cache  : false,
 			async  : false,
 			type   : 'post',
 			data   : App.serializeForm( 'updateBillingForm' ),
 			complete : function( xhr ) {

 				if( xhr.responseText == 'success' ) {
 					window.location.reload();
 				} else {
					$( '#updateTransportForm .transport' ).hide();
					$( '#updateTransportFormError .error' ).hide();
					$( '#updateBillingFormError .error' ).show();
					$( '#updateBillingForm .billing' ).show();
 				}

 			}
 		} );

 	},

 	/**
 	 * Form JSON-ná alakítása, AJAX kéréshez
 	 *   @param  (string) Form ID
 	 *   @return (object) Form adatok, JSON-ban
 	 */
 	serializeForm : function( formID ) {

 		var selector = '' +
 			'#' + formID + ' input, ' +
 			'#' + formID + ' select, ' +
 			'#' + formID + ' textarea';

 		var fields = $( selector );
 		var params = {};

 		$.each( fields, function( index, field ) {
			if( $( field ).attr( 'type' ) == 'checkbox' )
				params[ $( field ).attr( 'name' ) ] = ( field.checked ? 1 : 0 );
			else
				params[ $( field ).attr( 'name' ) ] = $( field ).val() || $( field ).html();
 		} );

 		return params;

 	},

 	/**
 	 * Üzenet réteg megjelenítése
 	 */
 	layer : function( msg ) {
		$( '.js_layer_message' ).html( msg );
		$( '.js_layer_background' ).css( 'height', $( document.body ).height() + 20 );
		$( '.js_layer' ).show();
		window.scrollTo( 0, 0 );
 	},

 	/**
 	 * Profil oldal
 	 */
 	Profile : {

 		/**
 		 * Címek
 		 */
 		Address : {

 			pID : 0,
 			bID : 0,

 			/**
 			 * Új cím
 			 *	@param	(char)	Típus: p (postal), vagy b (billing)
 			 */
 			create : function( type ) {

 				App.Profile.Address.reset( type );
 				App.Profile.Address[ type + 'ID' ] = 0;

 				$( '.js_p_form, .js_b_form, .js_p_form_modify, .js_b_form_modify' ).hide();
 				$( '.js_' + type + '_form, .js_' + type + '_form_insert' ).show();

 				window.scrollTo( 0, $( '#' + type.toUpperCase() + 'Form' ).offset().top );

 			},

 			/**
 			 * Cím módosítása
 			 *	@param	(char)		Típus: p (postal), vagy b (billing)
 			 *	@param	(object)	Cím adatok
 			 */
 			modify : function( type, data ) {

 				App.Profile.Address.reset( type );
 				App.Profile.Address[ type + 'ID' ] = data.id;

 				$.each( data, function( field, value ) {
 					$( '.js_' + type + '_form #' + type + '_' + field ).val( value );
 				} );

 				$( '.js_p_form, .js_b_form, .js_p_form_insert, .js_b_form_insert' ).hide();
 				$( '.js_' + type + '_form, .js_' + type + '_form_modify' ).show();

 				window.scrollTo( 0, $( '#' + type.toUpperCase() + 'Form' ).offset().top );

 			},

 			/**
 			 * Cím törlése
 			 *	@param	(char)		Típus: p (postal), vagy b (billing)
 			 *	@param	(integer)	Cím ID
 			 */
 			'del' :   function( type, id ) {

 				$( '.js_p_form, .js_b_form' ).hide();

 				$.ajax( {
 					cache   : false,
 					async   : false,
 					url     : 'ak/' + type + 'addressdelete?id=' + id,
 					success : function() {
 						$( '#' + type + '_row_' + id ).hide( 'drop', {direction : 'down'}, 500, function() {window.location.reload();} );
 					}
 				} );

 			},

 			/**
 			 * Cím elmentése
 			 *	@param	(char)	Típus: p (postal), vagy b (billing)
 			 */
 			save : function( type, url ) {

 				if( App.Cart.Address.validateForm( type ) ) {

 					var data = App.Cart.Address.fetchForm( type );
 					var id = App.Profile.Address[ type + 'ID' ];
 					var method = 'insert';
 					if( id ) {
 						data[ 'id' ] = id;
 						method = 'modify';
 					}

 					$.ajax( {
 						cache : false,
 						async : false,
 						type  : 'post',
 						data  : data,
 						url   : 'ak/' + type + 'address' + method,
 						complete : function() {
 							window.location.reload();
 						}
 					} );

 				}

 			},

 			/**
 			 * Űrlap ürítése
 			 *	@param	(char)	Típus: p (postal), vagy b (billing)
 			 */
 			reset : function( type ) {

 				var inputs = $( '.js_' + type + '_form input' );
 				$.each( inputs, function( index, input ) {$( input ).val( '' );} );

 				var selects = $( '.js_' + type + '_form select' );
 				$.each( selects, function( index, select ) {$( select ).val( '' );} );

 			}

 		}

 	}

} );

var App = new MainApplication();

var Util = {};

Util.urlMedia = function( parameters ) {

	parameters.id     = parameters.id     || 0;
	parameters.width  = parameters.width  || 320;
	parameters.height = parameters.height || 240;
	parameters.mode   = parameters.mode   || 'O';
	parameters.ext    = parameters.ext    || 'jpg';

	var path = '';
	var length = ( parameters.id + '' ).length;
	for( chr = 0; chr < length; chr++ )
		path += ( parameters.id + '' ).charAt( chr ) + '/';

	return URI_STATIC +
		'media/' + path +
		parameters.id + '_' +
		parameters.mode.toUpperCase() + '_' +
		parameters.width + 'x' +
		parameters.height + '.' +
		parameters.ext;
}

