jQuery.fn.labelify = function(settings) {
  settings = jQuery.extend({
    text: "title",
    labelledClass: ""
  }, settings);
  var lookups = {
    title: function(input) {
      return $(input).attr("title");
    },
    label: function(input) {
      return $("label[for=" + input.id +"]").text();
    }
  };
  var lookup;
  var jQuery_labellified_elements = $(this);
  return $(this).each(function() {
    if (typeof settings.text === "string") {
      lookup = lookups[settings.text]; // what if not there?
    } else {
      lookup = settings.text; // what if not a fn?
    };
    // bail if lookup isn't a function or if it returns undefined
    if (typeof lookup !== "function") { return; }
    var lookupval = lookup(this);
    if (!lookupval) { return; }

    // need to strip newlines because the browser strips them
    // if you set textbox.value to a string containing them    
    $(this).data("label",lookup(this).replace(/\n/g,''));
    $(this).focus(function() {
      if (this.value === $(this).data("label")) {
        this.value = this.defaultValue;
        $(this).removeClass(settings.labelledClass);
      }
    }).blur(function(){
      if (this.value === this.defaultValue) {
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);
      }
    });
    
    var removeValuesOnExit = function() {
      jQuery_labellified_elements.each(function(){
        if (this.value === $(this).data("label")) {
          this.value = this.defaultValue;
          $(this).removeClass(settings.labelledClass);
        }
      })
    };
    
    $(this).parents("form").submit(removeValuesOnExit);
    $(window).unload(removeValuesOnExit);
    
    if (this.value !== this.defaultValue) {
      // user already started typing; don't overwrite their work!
      return;
    }
    // actually set the value
    this.value = $(this).data("label");
    $(this).addClass(settings.labelledClass);

  });
};


jQuery.fn.buttonify = function(settings) {
    settings = jQuery.extend( {
        text: "title",
        labelledClass: ""
    }, settings);
    $(this).each(function() {
        var button = $(this);
        var tt = '';
        if (button.is(":submit") || button.is(":button")) {
            tt = button.val();
            newbutton = $('<a class="' + button.attr('class') + '" id="' + button.attr('id') + '">' + button.val() + '</a>');
            newbutton.insertAfter(button);
            $('<input type="hidden" name="' + button.attr('name') + '" value="' + button.val() + '" />').insertAfter(button);
            button.remove();
            //	trace($(newbutton).text())
            button = newbutton;
            button.click(function(e) {
                e.preventDefault();
                var form = $(e.target).closest("form");
                if (form) {
                    form.submit();
                }
            });
        } else {
            tt = button.text();
        }
        button.text('').css( {
            cursor: 'pointer'
        })
        //.prepend('<i></i>')
        .append($('<span>').text(tt))
        //.append('<i></i><span></span>'));
    });
};
function custom_confirm(prompt, action, title) {
    if (title === undefined) {
        title = "Megerősítés";
    }
    $("#main").append('<div id="confirm" title="' + title + '">' + prompt + '</div>');
    $("#confirm").dialog( {
        modal: true,
        resizable: false,
        show: "slide",
        hide: "blind",
        buttons: {
            "Ok": function() {
                $(this).dialog('close');
                action();
            },
            "Mégsem": function() {
                $(this).dialog('close');
            }
        },
        close: function(ev, ui) {
            $(this).remove();
        }
    });
}
/*

ORDER-SHIPPING-PAYMENT

*/
function loadBillingEditor() {
    target = $('#place-order-billing-panel .section-content');
    target.mask('Számlázási adat szerkesztés betöltése...');
    $.ajax( {
        url: '/hu/checkout/load_billing_editor',
        success: function(data) {
            target.css('height', 'auto').unmask();
            target.fadeOut('fast', function() {
                target.empty().append(data).fadeIn("fast", function() {
                    $.scrollTo(target, 500);
                });
                $('.btn', target).buttonify();
                initBillingDataViewer();
            });
        }
    });
}
function initShippingEditor() {
    $('#shipping-edit').click(function(e) {
        e.preventDefault();
        url = $(this).attr('rel');
        target = $('#place-order-shipping-panel .section-content');
        target.mask('Szállítási adat szerkesztés betöltése...');
        $.ajax( {
            url: url,
            success: function(data) {
                target.unmask();
                $('#place-order-billing-panel .section-content').empty().fadeOut();
                target.fadeOut('fast', function() {
                    target.empty().append(data).fadeIn("fast", function() {
                        $.scrollTo(target, 500);
                    });
                    $('.btn', target).buttonify();
                    initShippingDataViewer();
                });
            }
        });
    });
}
function initShippingDataViewer() {
    $('#place-order-shipping-panel form').validate( {
        submitHandler: function(form) {
            form = $(form);
            url = form.attr('action');
            formdata = form.serialize();
            target = $('#place-order-shipping-panel .section-content');
            target.mask('Szállítási adatok mentése...');
            $.post(url, formdata, function(data) {
                target.unmask();
                target.fadeOut('slow', function() {
                    target.hide().empty().append(data).fadeIn('fast', function() {
                        $.scrollTo('#place-order-shipping-panel', 500);
                    });
                    $('.btn', target).buttonify();
                    initShippingEditor();
                    loadBillingEditor();
                });
            });
        }
    });
}
function initBillingEditor() {

 	$('a#send-order').click(function(){
 	
		if ($('input#accept-terms:checked').length < 1){
			alert('El kell fogadnia a feltételeket!')
			return false;
		}
	})

   $('#billing-edit').click(function(e) {
        e.preventDefault();
        url = $(this).attr('rel');
        target = $('#place-order-billing-panel .section-content');
        target.mask('Számlázási adat szerkesztés betöltése...');
        $.ajax( {
            url: url,
            success: function(data) {
                target.unmask();
                target.fadeOut('fast', function() {
                    target.empty().append(data).fadeIn("fast", function() {
                        $.scrollTo(target, 500);
                    });
                    $('.btn', target).buttonify();
                    initBillingDataViewer();
                });
            }
        });
    });
}
function initBillingDataViewer() {


    $('#place-order-billing-panel form').validate( {
        submitHandler: function(form) {
            form = $(form);
            url = form.attr('action');
            formdata = form.serialize();
            target = $('#place-order-billing-panel .section-content');
            target.mask('Számlázási adatok mentése...');
            $.post(url, formdata, function(data) {
                target.css('height', 'auto').unmask();
                target.fadeOut('slow', function() {
                    target.empty().append(data).fadeIn('fast', function() {
                        $.scrollTo(target, 500);
                    });
                    $('.btn', target).buttonify();
                    
                    initBillingEditor();
                    
                })
                });
        }
    })
}
$(document).ready(function() {
    
    
    function drawMap(address, targetEl){
	    if(typeof GBrowserIsCompatible == 'function'){
		
			var geocoder = new GClientGeocoder();
				
			geocoder.getLatLng(
			  address,
			  function(point) {
			    if (!point) {
			      return false;
			    } else {
				  
				  var map = new GMap2(targetEl);
			      map.setMapType(G_NORMAL_MAP);
			      map.setCenter(point, 13);
			      var marker = new GMarker(point);
			      map.addOverlay(marker);
			      //marker.openInfoWindowHtml(address);
			    }
			  }
			);
					
		}else{
			return false;
		}
		
		
	}

	
	$('div.map-holder').each(function(){
	
			drawMap($(this).text(), this)
		
	
	})
	
	
    $('#partner-list .group h3').click(function(e){
		$('.col', $(this).parent().parent()).hide()
		$('.col', $(this).parent()).slideDown(200)
						
	})
    		
    		
    $('#slider-1 .slider-outer').jwSlider( {
        transition: 'slide',
        speed: 1000,
        pause: 8000
    })
    
    if($("#subscribe-form").length > 0){
	    $("#subscribe-form :text").labelify( {
   	     text: "label"
  	  })
    }
    

	$('.confirm').live('click', function(e) {
        var href = $(this).attr('href');
        e.preventDefault();
        custom_confirm($(this).attr('rel'), function() {
            location.href = href;
        }, $(this).attr('title'));
    });

    $('.product-checklist-btn').click(function(e) {
        e.preventDefault();
        $("#product-checklist").dialog( {
            modal: true,
            width: 600,
            height: 400,
            title: 'Válasszon a termékek közül!',
            hide: 'slide',
            show: 'slide'
        });
    })
        $("#product-checklist table tr").toggle(function() {
        $(this).addClass("checked");
        $('input.qty-input', this).val(1);
        calculateChecklistSum();
    }, function() {
        $(this).removeClass("checked");
        $('input.qty-input', this).val(0);
        calculateChecklistSum();
    });

    function calculateChecklistSum() {
        var qty = 0; 
        var price = 0; 
        var total = parseInt($('#cart-total-plain').text());
        
        $("#product-checklist table tr").each(function() {
            q = parseInt($('input.qty-input', this).val());
            if (q > 0) {
                qty = q + qty;
                price = parseInt($('input.price-input', this).val()) + price;
            }
        })
            $('#product-checklist-sum-cart').text(total + price);
        $('#product-checklist-sum-items').text(qty);
        $('#product-checklist-sum-price').text(price);
    }

    $('#faq-form').submit(function() {
        var faq_author = $('#faq_author').val(),
        faq_email = $('#faq_email').val(),
        faq_question = $('#faq_question').val(),
        url = $(this).attr('action');
        if (faq_author.length < 2 || faq_question.length < 4 || faq_email === null) {
            if ($('.error').length === 0) {
                $('form').append('<p class="error">Hibásan kitöltött adatok!</p>');
            }
            return false;
        }
        $.post(url, {
            'faq_question': faq_question,
            'faq_email': faq_email,
            'faq_author': faq_author
        }, function(r) {
            $('#faq-form').fadeOut(200).empty().append('Köszönjük a kérdést, hamarosan reagálunk!').fadeIn(1000);
        });
        // end post
        return false;
        // disable submit click
        
    });

	$('#add-to-cart-form').submit(function(e){
		

		var postdata = $(this).serialize();
		var url = $(this).attr('action')
		var maskcontent = $(this).parent().parent()
		maskcontent.mask('Korárhoz hozzáadás')
		
		$.post(url, postdata,
	      function(data){
			maskcontent.unmask()
			if(data == 'true'){
				$("#side-cart").mask('Frissítés')
				$.get("/hu/shoppingcart/show_cart", function(cart){ // Get the contents of the url cart/show_cart
					$("#side-cart").unmask()
					$("#side-cart").fadeOut(100).html(cart).fadeIn(1000); // Replace the information in the div #cart_content with the retrieved data
				});    

			}else{
				alert("Product does not exist");
			}

	     });
	    

		return false; // Stop the browser of loading the page defined in the form "action" parameter.
	   
		
	})


    $("#subscribe-popup").dialog( {
        modal: true,
        draggable: false,
        width: 470,
        dialogClass: 'nailvital-subscribe',
        resizable: false,
        title: 'Regisztráljon az ingyenes próbáért!',
        hide: 'slide',
        show: 'slide',
        autoOpen: false
    });

	
	$('#show-subscribe-window').click(function(e){
     
     
        e.preventDefault();

    	$("#subscribe-popup").dialog( 'open' );
    	
    	
	
	})

    if ( ! $.cookie('nailvital_subscribe_popup_times_displayed')) {
        $.cookie('nailvital_subscribe_popup_times_displayed', 0, {
            expires: 20
        });
    }
    if ($.cookie('nailvital_subscribe_popup_times_displayed') && $.cookie('nailvital_subscribe_popup_times_displayed') < 2) {
    
    	$("#subscribe-popup").dialog( 'open' )
    
        $.cookie('nailvital_subscribe_popup_times_displayed', parseInt($.cookie('nailvital_subscribe_popup_times_displayed')) + 1, {
            expires: 20
        });
    }
    
    
    
/* Subscribe */


    $("#feliratkozo_form").validate({

    	meta: "validate",

	    submitHandler: function(form) {
	    
	    	
	    	
	        var name = $("input#uname").val();
	        var email = $("input#subscr").val();
	        var g = $("input#g").val();
	        var sub = "feliratkozás";
	        var dataString = 'g=' + g + '&uname=' + name + '&subscr=' + email + '&sub=' + sub;
	        
	        
	        
	        $holder = $(form).parent().parent();
	        
	        $holder.mask('Kérelem küldése');

			//console.log(form.getAttribute("action") + ' -- ' + dataString)

	        $.ajax( {
	            type: "POST",
	            url: form.getAttribute("action"),
	            data: dataString,
	            dataType: 'json',
	            success: function(msg) {
	            	
	            	if(msg.success){

						$.cookie('nailvital_subscribe_popup_times_displayed', 10)	                    

	            	
		                $messageHolder = $(form).html("<div id='message'></div>");
	
						$holder.unmask()
	
						$btn = $('<a href="#" class="btn">Bezárás</a>').click(function(){
		                		$("#subscribe-popup").dialog( 'close' ); return false;}
		                	)
						
						$btn.buttonify()
	
		                $messageHolder.html("<h2>Köszönjük a feiratkozást!</h2><!--p><b>E-mailen elküldtük a további teendőket az ingyenes próbáért!</b></p><p><br /><b>Köszönjük!<br /><br /></b></p-->").append($btn)
		                .hide().fadeIn(500);


	            	}else{
	            	
	            	
	            			alert('A név, vagy az e-mail cím már létezik az adatbázisban!');
	            			
	            			$holder.unmask()

	            			return false;
	            	
	            	
	            	}
	            	
	            },
	            failure: function() {
	                alert('HIBA!');
	            }
	        });
	    }
	});
	
	
	
		
	
	
	
	
	
    initShippingEditor();
    initShippingDataViewer();
    
    
    
    $('.fancybox').fancybox();
    Cufon.replace('#top-navigation a');
    Cufon.replace('#product-family-selector h2');
    Cufon.replace('div.product-scroller-holder h2 a');
    Cufon.replace('#sidebar h3');
    Cufon.replace('.product-details h2');
    Cufon.replace('.helvetica');
});




$(window).load(function() {
    if ($('div.product-scroller').length > 0) {
        var container = $('div.product-scroller');
        var ul = $('ul', container);
        var ulwidth = 0;
        $('li', ul).each(function(e, item) {
            ulwidth += $(item).outerWidth();
        })
            ul.css( {
            'left': 0,
            'width': ulwidth
        });
        $('li img', ul).each(function(e, item) {
            $(item).wrap('<div></div>').css( {
                opacity: 0.6
            }).hover(function() {
                $(this).css( {
                    opacity: 1
                });
                var title = $(this).parent().parent().attr('title');
                $('#product-scroller-title').text(title);
            }, function() {
                $(this).css( {
                    opacity: 0.6
                });
                $('#product-scroller-title').empty();
            })
            })
            var itemsWidth = ul.outerWidth() - container.outerWidth();
        $('.slider').slider( {
            step: 10,
            min: 0,
            max: itemsWidth,
            slide: function(event, ui) {
                ul.stop().animate( {
                    'left': ui.value * -1
                });
            },
            change: function(event, ui) {
                ul.stop().animate( {
                    'left': ui.value * -1
                }, 500);
            }
        });
        if (container.attr('title')) {
            var selected = $('li#' + container.attr('title'), ul);
            if (selected && selected.length > 0) {
                $('.slider').slider('value', $(selected[0]).position().left - (container.outerWidth() / 2) + ($(selected[0]).outerWidth() / 2));
            }
        }
    }

    $('.btn').buttonify();


    $('input[type=hidden]').hide();
    
    
    
//maps generate
	
	
});
function msg(t) {
    //$('#message').stop()
    $('#message').empty().text(t).show().css( {
        opacity: 1
    }).fadeOut(1000)
    }
function trace() {
    var debug = document.getElementById('debug');
    if ( ! debug) {
        var debug = document.createElement('div');
        debug.setAttribute('id', 'debug');
        document.body.appendChild(debug);
        debug.onclick = function() {
            if (this.closed) {
                this.style.height = '200px';
                this.closed = false;
            } else {
                this.style.height = '2px';
                this.closed = true;
            }
        }
    }
    if (debug) {
        var o = '';
        o = 'arguments.length = ' + arguments.length + '<br />';
        //	 o += arguments;
        for (var i = 0; i < arguments.length; i ++ ) {
            o += '<div style="margin-left: 16px;">';
            o += arguments[i];
            for (j in arguments[i]) {
                o += '<div style="margin-left: 16px;">';
                o += '<b>' + j + '</b>&nbsp;=&nbsp;' + String(arguments[i][j]).split('<').join('&lt;').split('>').join('&gt;').split('\"').join('&raquo;');
                o += '</div>';
            }
            o += '</div>';
        }
        debug.innerHTML = o;
    }
}
