var myscrollpos = 0;
var usemyscrollpos = false;

var  isiPad = navigator.userAgent.match(/iPad/i)  != null;
var  isiPhone = navigator.userAgent.match(/iPhone/i)  != null;

var  padbrowser = false;

if(isiPad || isiPhone) padbrowser = true;



function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
	{
	    hash = hashes[i].split('=');
	    vars.push(hash[0]);
	    vars[hash[0]] = hash[1];
	}
    return vars;
}


//url setzen...
if(window.location.pathname.length != (window.location.pathname.lastIndexOf('/')+1)){
    urlvars = getUrlVars();
	if(urlvars['path'] == undefined){
		window.location.href = window.location.protocol +"//"+ window.location.host + window.location.pathname.substr(0, (window.location.pathname.lastIndexOf('/')+1))+window.location.hash;
	    }else{
		window.location.href = window.location.protocol +"//"+ window.location.host + window.location.pathname.substr(0, (window.location.pathname.lastIndexOf('/')+1))+'#'+urlvars['path'];
	    }
}

var pendingrequest = 0;
var navigationinit = false;

function navigation(hash)
{
    if(navigationinit || hash != ""){
		var status = "big";  
		if($("#nx_contentwraper").length > 0 && pendingrequest == 0){
		status = "smal";
		}
		pendingrequest++ ;
		navigationinit = true;
		$.get('ajaxcontent.php',{
		'path':  hash,
		'status': status
		},ajaxreturn,'json')
	}else{
		navigationinit = true;
	}
}

function ajaxreturn(data) {
    
    if(data.status == 'smal'){
	if($("#nx_contentwraper").length > 0){
	    $("#nx_contentwraper").html(data.html);
	}else{
	    $("#nx_maxcontentwrapper").html(data.navigation+"<script type='text/javascript'>$('#nx_akordion ul li').tsort('span a');$('#nx_akordion ul li ul li').tsort('span a');$('#nx_akordion ul li ul li ul li').tsort('span a');$('#nx_akordion').AKordion();</script>"+"<div id='nx_contentwraper'>"+data.html+"</div>");
	}
	if(usemyscrollpos){
	    $(window).scrollTop(myscrollpos);
	    usemyscrollpos = false;
	}
    }else if(data.status == 'big'){
	$("#nx_maxcontentwrapper").html(data.html);
	if(usemyscrollpos){
	    $(window).scrollTop(myscrollpos);
	    usemyscrollpos = false;
	}
    }
    if(pendingrequest>0){
	pendingrequest-- ;
    }
}

$("a[href^='index.php?path=']").livequery('click',function(e){
    var callurl = str_replace('?path=','',this.search)
    myscrollpos = $(window).scrollTop();
    $(window).scrollTop(0);  
    $.history.load(callurl);
    $(this).parent().trigger('click');
    return false;
});

$("a[href*='#back']").livequery('click',function(e){
    $(window).scrollTop(0);  
    history.go(-1);
    usemyscrollpos = true;
    return false;
});

$("a[href='#']").livequery('click',function(e){
    $(window).scrollTop(0);    
    return false;
});

if(!padbrowser){
$("a.jqzoom").livequery( function() {
                $(this).addClass('cloud-zoom');
		$(this).CloudZoom();
});
}


$(".nx_smalimage").livequery(function(){
	var mysrc = $(this).attr("src");
	var mypopsrc = $(this).attr("title");
	$(this).bind("mouseover",function(){
		$(".nx_smalimage").removeClass('smalimageactive');
		$(this).addClass('smalimageactive');
		if(mypopsrc != '#'){
		    $('.nx_detail_imagebox').html("<a href='" + mypopsrc+ "' class='jqzoom' id='zoom1' rel='adjustX: 45, adjustY:0, zoomWidth: 520, zoomHeight: 352, title:false'><img src='"+mysrc+"' alt='' title='' /></a>");		                
		}else{
		    $('.nx_detail_imagebox').html("<img src='"+mysrc+"' alt='' title='' />");		                
		}
		
	})
})

var serachtextdefault ="";

$("#suche").livequery( function() {
	serachtextdefault = this.value;
	$(this).bind("click",function(){
		this.value = '';
		$('input').keydown(function(e){
		    if (e.keyCode == 13) {
			$.history.load("search/result&sq="+encodeURI($("#suche").val()));
			return false;
		    }
		});
	})
	$(this).bind("blur",function(){
		if(this.value == ''){
			this.value = serachtextdefault;
		}
	})

});


$("#nx_search_button").livequery( function() {
	$(this).bind("click",function(){
		if( $("#suche").val() != serachtextdefault){
		    $.history.load("search/result&sq="+encodeURI($("#suche").val()));
		}
	})
});

$("#select-language").livequery(function(){
    $(this).bind("change",function(){
	var values = new Object();
	var d = new Date();
	values['action'] = "language";
	values['language'] = $(this).val();
	values['time'] = d.getTime();
	$.ajax({
	     type: 'POST',
	     url: "ajaxaction.php",
	     data: values,
	     success: reload,
	     dataType: "json"
	});
	return false;
	
    })
})

function reload(){
    var d = new Date();
    var currentURL = window.location;

    window.location.href =  window.location.pathname;
    window.location.reload(true);
}



$("a.crossimage").livequery( function() {
    $(this).tooltip({ 
	bodyHandler: function() { 
	    return $(this).parent().next('div').html(); 
	}, 
	showURL: false  
    });
});

$("#variants select").livequery('change',function(e){
     var values = new Object();
     $("#variants select").each(function (i) {
	if(this.value != '') values[this.name] = this.value;
     });
     values[this.name] = this.value;
     values['path'] = location.hash;
     values['action'] = 'variants';
     $("#variants").load("ajaxcontent.php",values,function(){$('#vaiants').append('&nbsp;')});
});


$("a[href*='#nx_cartdelete']").livequery('click',function(e){
     var values = new Object();
     var myartid = $(this).attr('rel');
     values['action'] = "deletefromcart";
     values['articlevariant'] = myartid;
     
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: updateincart,
      dataType: "json"
    });
    return false;
});



$(".nx_deliveryoptions").livequery('change',function(e){
     var values = new Object();
     var mydelivery = $('#nx_deliveryselect').val();
     var mycountry = $('#nx_contryselect').val();
     
     values['delivery'] = mydelivery;
     values['country'] = mycountry;
     values['action'] = "updatedelivery";
     
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: updateincart,
      dataType: "json"
    });
    return false;
});


$(".nx_cart_menge").livequery('change',function(e){
     var values = new Object();
     var myartid = $(this).attr('rel');
     var mymenge = $(this).val();
     values['action'] = "updateamountcart";
     values['articlevariant'] = myartid;
     values['newmenge'] = mymenge;
     
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: updateincart,
      dataType: "json"
    });
    return false;
});


function updateincart(data,textStatus, XMLHttpRequest){
    if(data.error == true){
	alert(data.alert);
	$('#nx_warenkorbinfo').parent().parent().fadeOut('fast');
	$('#nx_short_cart').text(data.shortcarttext);
	$('#nx_warenkorbinfo').parent().parent().fadeIn('fast').fadeOut('fast').fadeIn('fast');
	navigation('cart/step1');
    }else{
	$('#nx_warenkorbinfo').parent().parent().fadeOut('fast');
	$('#nx_short_cart').text(data.shortcarttext);
	$('#nx_warenkorbinfo').parent().parent().fadeIn('fast').fadeOut('fast').fadeIn('fast');
	navigation('cart/step1');
    }
}

$("#nx_cart_button").livequery('click',function(e){
     var values = new Object();
     var myartid = $("#nx_cart_id").val();
     var myartamount = $("#nx_cart_menge").val();
     
     values['action'] = "addtocart";
     values['article'] = myartid;
     values['amount'] = myartamount;
     
     if($("#variants select").length > 0){
	values['variants'] = new Object();
	$("#variants select").each(function (i) {
	    if(this.value != '') values['variants'][this.name] = this.value;
	});
     }
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: updatecart,
      dataType: "json"
    });
    return false;
});

function updatecart(data,textStatus, XMLHttpRequest){
    if(data.error == true){
	$('#nx_short_cart').text(data.shortcarttext);
	alert(data.alert);
	
    }else{
	$('#nx_warenkorbinfo').parent().parent().fadeOut('fast');
	$('#nx_short_cart').text(data.shortcarttext);
	$('#nx_warenkorbinfo').parent().parent().fadeIn('fast').fadeOut('fast').fadeIn('fast');
	// alert(data.alert); //um zu wissen was geht
    }
}


$("#nx_shoplogin_button").livequery('click',function(e){
     var values = new Object();
     var mykdnr = $("#adr_nr").val();
     var mypass = $("#adr_pass").val();
     values['action'] = "login";
     values['kdnr'] = mykdnr;
     values['pass'] = mypass;
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: logincallback,
      dataType: "json"
    });
    return false;
});


function logincallback(data,textStatus, XMLHttpRequest){
    if(data.status == "loggedin"){
	$('#nxloginstatus').html(data.longinstatus)
    }
    if(data.error == true){
	alert(data.alert);
	if(data.action != undefined){
	   $.history.load(data.action); 
	}
    }else{
	
	if($('#nxloginpage').length > 0){
	    $.history.load('');
	}else{
	    $.history.load('cart/step2a');
	}
    }
}

$("a[href*='#nx_logout']").livequery('click',function(e){
     var values = new Object();
     values['action'] = "logout";
     $.ajax({
      type: 'POST',
      url: "ajaxaction.php",
      data: values,
      success: logoutcallback,
      dataType: "json"
    });
    return false;
});

function logoutcallback(data,textStatus, XMLHttpRequest){
    if(data.error == true){
	alert(data.alert);
    }else{
	$('#nxloginstatus').html(data.longinstatus);
	$('#nx_warenkorbinfo').parent().parent().fadeOut('fast');
	$('#nx_short_cart').text(data.shortcarttext);
	$('#nx_warenkorbinfo').parent().parent().fadeIn('fast').fadeOut('fast').fadeIn('fast');
	 $.history.load('');
    }
}


function updatefilter() {
    var callurl = $("#fpath").attr('value')
    callurl = str_replace('&fangebote=1','',callurl)
    callurl = str_replace('&fneuheiten=1','',callurl)
    callurl = str_replace('&sort=1','',callurl)
    if($('#sort').attr('value') != ''){
	callurl +='&sort='+ $('#sort').attr('value');
    }
    if($('#ffilter').attr('value') == 'fangebote'){
	callurl +='&fangebote=1';
    }
    if($('#ffilter').attr('value') == 'fneuheiten'){
	callurl +='&fneuheiten=1';
    }
    if($('#fhersteller').attr('value') != ''){
	callurl +='&fhersteller='+ $('#fhersteller').attr('value');
    }
    if($('#fcategories')){
	if($('#fcategories').attr('value') != undefined && $('#fcategories').attr('value') != ''){
	    callurl +='&fcategories='+ $('#fcategories').attr('value');
	}
    }
    if($('#searchterm').attr('value') != '' && $('#searchterm').attr('value') != undefined ){
	callurl +='&sq='+ $('#searchterm').attr('value');
    }
    $.history.load(decodeURI(callurl));
};

function trig_bind() {
  //unbind old events
  $("input[type='checkbox']").unbind( 'click' )
  $("input[type='radio']").unbind( 'click' )
  //bind the events
  
  $("input[type='checkbox']").bind( 'click', function() {
    $(this).trigger( 'change' )
  })
  
  $("input[type='radio']").bind( 'click', function() {
    $(this).trigger( 'change' )
  })
}

$("#filterform select").livequery('change',updatefilter);
$("#filterform p input").livequery('change',updatefilter);
$("#filterform p input").livequery( 'click', function() {
    if (jQuery.browser.msie) {
	$(this).trigger( 'change' )
    }
})


$(document).ready(function() {
    $("#jswarning").remove();
    $.history.init(navigation);
    $("#nx_akordion").AKordion();
    $('#nx_akordion ul li').tsort('span a');
    $('#nx_akordion ul li ul li').tsort('span a');
    $('#nx_akordion ul li ul li ul li').tsort('span a');
});



