$(document).ready(function() {
	$('.removeme').remove();

    var title = $('.item-page h2').html();
    $('.item-page h2').remove();

    if (title == "" || title == null) {
        title = $('.subheading-category').html();
        $('.subheading-category').remove();
    }

    $('#pagetitle').html($.trim(title));
    
    $('.hiddenitem').each(function() {
    	$(this).closest('li').remove();
    });
	
	$('#topmenu a').html("<span>"+$('#topmenu a').html()+"</span>");
	
});


//-------------
var count = 0;
var move_lenght = 965;
var moving = $("#moving");
var start = 2;
var actual = start;
$(document).ready(function() {
    //prepareGallitems(moving, start)
});

//$('.bigmenuitem').click(function() {
//    window.location = $(this).find('a').attr('href');
//});
$('#productsmenutitle').click(function() {
    window.location = "http://www.amylon.cz/index.php/produkty";
});

$(".imgarrows_").click(function () {
    var dir = $(this).attr("dir");
    move(dir, moving, 700)
    changeFirstLast(dir, moving.find("img[id*=banner]"));
    changeArrows(dir, moving.find("img[id*=banner]"), ".imgarrows")
    setDots()
});

//$("#imagesdots div").click(function(){
//    moveTo($(this).attr("name"));
//})

//function moveTo(to){
//    diff = parseInt(to) - actual;
//     
//}

function setDots(){
    $("#imagesdots .greendot").addClass("graydot").removeClass("greendot");
    $("#imagesdots div[name="+actual+"]").addClass("greendot").removeClass("graydot")
}

function prepareGallitems(moving, start){
    count = 0;
    moving.find("img").each(function(index){
        $(this).attr("name",index);
        count++;
    });

    var left = 0;
    
    moving.find("img").each(function(index){
        $(this).css("left",left+"px");
        left= left + move_lenght;
        if (index < start) move("-",moving,1);
    });
    
    moving.find("img[name="+start+"]").fadeIn();
    $("#imagesdots .imagesdot").each(function(index){
        $(this).attr("name",index);
    })
}

function changeArrows(dir, what, arrows){
    if (dir == "-"){
        if (actual == (count-1)) $("#imgrightarrow").hide();
        $("#imgleftarrow").fadeIn();
    } else {
        if (actual == 0) $("#imgleftarrow").hide();
        $("#imgrightarrow").fadeIn();
    }
}

function changeFirstLast(dir, what){
    if (dir == "-"){
        
        what.filter(':visible:first').fadeOut();
        var tmp = what.filter(':visible:last').next();
        tmp.fadeIn("slow");
        actual = parseInt(tmp.attr("name"));
    } else {
        var tmp = what.filter(':visible:first').prev();
        actual = parseInt(tmp.attr("name"));
        tmp.fadeIn("slow");
        what.filter(':visible:last').fadeOut();
    }
    
}

function move(dir, what,speed){
    what.animate({"left": dir+"="+move_lenght+"px"}, speed);
}

function outerHTML(node){
    // if IE, Chrome take the internal method otherwise build one
  return node.outerHTML || (
      function(n){
          var div = document.createElement('div'), h;
          div.appendChild( n.cloneNode(true) );
          h = div.innerHTML;
          div = null;
          return h;
      })(node);
  }

$('.menuproducts').hover(function() {
    var position = $(this).offset();
    $('#productsmenutitle').css({
			top: position.top,
			left: position.left
                    })
                    .show();
    $('#productsmenucontent').css({
		top: position.top,
		left: position.left
                })
                .show();
	$('#contactsmenu').hide();
}, function() {
//    $('#productsmenu').hide();
});

$('.menukontakty').hover(function() {
    var position = $(this).offset();
    $('#contactsmenu').css({
			top: position.top,
			left: position.left-135
                    })
                    .show();
    $('#productsmenutitle').hide();
    $('#productsmenucontent').hide();
});


$(document).click(function() {
    $('.floatmenu').hide();
});

$('#productsmenucontent').hover(function() {
}, function() {
    $('.floatmenu').hide();
});


$(document).ready(function() {
    $('input[type=text], textarea, select').each(function() {
    	if ($(this).attr('id') != 'nwslt_email') {
	        if ($(this).attr('arounddiv') == null || $(this).attr('arounddiv') == "true" )
			var div = $('<div class="inputaround">'+$('<div>').append($(this).clone()).remove().html()+'</div>')
	        $(this).replaceWith(div);
    	}
    });

    $('ol').each(function() {
        var i=0;
		var repltable = "<table class=\"ollitable\">";
       $(this).find('li').each(function() {
          i++;
          repltable += "<tr><td><div style=\"height:42px; width:42px; background-image: url(/images/amylon/cisla/"+i+".png)\"></div></td><td><p>"+$(this).html()+"</p></td></tr>";
       });
	   repltable += "</table>";
	   $(this).replaceWith(repltable);
    });
});


$('.inputwitherror').live('focus', function() {
	$(this).removeClass('inputwitherror');
	if ($(this).val() == "Povinná položka" || $(this).val() == "Vložte prosím e-mail") {
		$(this).val("");
	}
});

$('#contactformbtn').click(function() {
	$('.emailresultmsg').remove();
	if ($(this).attr('class') == 'formsubmitbtn_en') {
		var okmsg = "<p class=\"emailresultmsg\" style=\"font-size: 11pt; color: #b2d053;\">The message has been sent. Thank you for your interest.</p>";
	} else {
		var okmsg = "<p class=\"emailresultmsg\" style=\"font-size: 11pt; color: #b2d053;\">Zpráva byla odeslána. Děkujeme za váš zájem.</p>";
	}
	if ($(this).attr('class') == 'formsubmitbtn_en') {
		var errmsg = "<p class=\"emailresultmsg\" style=\"font-size: 11pt; color: red;\">The message has not been sent.</p>";
	} else {
		var errmsg = "<p class=\"emailresultmsg\" style=\"font-size: 11pt; color: red;\">Zprávu se bohužel nepodařilo odeslat.</p>";
	}

	var table = $('#contactformtable');
	send = validateInputs('#contactformtable');
	var name  = table.find("input[name=name]");
    var phone = table.find("input[name=phone]");
    var email = table.find("input[name=emailsender]");
	var text = table.find("textarea[name=text]");

    if (email.val() == "" || !valEmail(email.val())) {
        send = false;
        email.val("Vložte prosím validní e-mail");
        email.addClass("inputwitherror");
    }
	
	if (send) {
		var emailrec = "michalkab@gmail.com";
		var url="../index.php?option=com_sendemail&format=raw&sendtype=php";
		log(url);
		$.ajax( {
					type : "POST",
					url : "" + url,
					dataType : "html",
					data : read('#contactformtable'),
					success : function(g) {
					log(g);
							if (g == 'ok') {
								name.val("");
								phone.val("");
								email.val("");
								text.val("");
								table.before(okmsg);
							} else {
								table.before(errmsg);
							}
					},
					error : function(xhr, ajaxOptions, thrownError) {
							alert("Chyba při kontaktu serveru. Zkuste to prosím znovu."
											+ xhr.statusText + ' ' + thrownError);

					}
			});
	}
});

function validateInputs(parentitem) {
	var result=true;
	$(parentitem + ' .required').each(function() {
		if (($(this).val() == "") || ($(this).val() == "Povinná položka")) {
			result=false;
			$(this).val("Povinná položka");
			$(this).addClass("inputwitherror");
		}
	});
	return result;
}

function read(form){
    var values = "";
    $(form+" input, "+form+" select, "+form+" textarea").each(function(index){
        if($(this).attr("type")=="checkbox") {
            values += "&"+$(this).attr("name") + "=" + $(this).attr("checked");
        }
        if ($(this).val() != "") {
            if ( $(this).val() == "true" || $(this).val()=="false" ) {
                values += "&"+$(this).attr("name") + "=" + ($(this).val() == "true") ? 1 : 0;
            } else {
                values += "&"+$(this).attr("name") + "=" + $(this).val();
            }
        }
    });

    return values;
}

function log() {
	if (window.console && window.console.log)
		window.console.log('[amylon] ' + Array.prototype.join.call(arguments,' '));
};
