
function addArticle(picture_id, article_id, article_price) {
    $.ajax({
        type: "POST",
        url: "/action/shop/do_addarticle.php",
        data: {
            picture_id : picture_id,
            article_id : article_id,
            article_price : article_price
        },
        dataType: "json" ,
        success: function(res){
            $('div#add2Cart_' + article_id).html('Added');
            $('div#cart2').show('slow');
            if(res['fk_user_id'] == 0) {
                $('div#cart3').append('<li><span class="tooltip_new" title="<img src=\'http://hicker-frontend-julian.dev.addmore.local/images/150/'+res['domain_filename']+'-'+res['id']+'.jpg\' />"><a href="'+res['link']+'">'+res['title']+'</a></span></li>');
            } else {
                $('div#cart3').append('<li><span class="tooltip_new" title="<img src=\'http://hicker-frontend-julian.dev.addmore.local/images/'+res['fk_user_id']+'/150/'+res['title2']+'-'+res['siteid']+'-'+res['id']+'.jpg\' />"><a href="'+res['link']+'">'+res['title']+'</a></span></li>');
            }
            $(".tooltip_new, .fancy2").tooltip({
                track: true,
                delay: 0,
                showURL: false,
                opacity: 1,
                fixPNG: true,
                showBody: " - ",
                extraClass: "pretty fancy",
                top: -120,
                left: 5
            });
        }
    });
}

function editArticle(picture_id, article_id, quantity, article_price) {
    var quanti = parseInt($('div#'+picture_id+'_'+article_id).html());
    if (quanti+quantity != 0) {
			
        $.ajax({
            type: "POST",
            url: "/action/shop/do_editarticle.php",
            data: {
                picture_id : picture_id,
                article_id : article_id,
                quantity : quantity,
                article_price : article_price
            },
            dataType: "json" ,
            success: function(res){
                var quanti = parseInt($('div#'+picture_id+'_'+article_id).html());
	
                if (quanti+quantity == 0)
                    $('div#'+picture_id+'_'+article_id).html('0');
                else
                    $('div#'+picture_id+'_'+article_id).html(quanti+quantity);
						 
                var price = parseFloat($('span#price_'+picture_id+'_'+article_id).html());
                $('span#amount_'+picture_id+'_'+article_id).html(((quanti+quantity)*price).toFixed(2));
				 
                var subtotal = parseFloat($('span#subtotal').html());
                $('span#subtotal').html((subtotal + (quantity * price)).toFixed(2));
            }
        });
    }
}

function trim (zeichenkette) {
    if (zeichenkette == undefined)
        zeichenkette = '1234567890';
    // Erst f�hrende, dann Abschlie�ende Whitespaces entfernen
    // und das Ergebnis dieser Operationen zur�ckliefern
    return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function deleteArticle(picture_id, article_id, article_price, quantity) {
    $.ajax({
        type: "POST",
        url: "/action/shop/do_deletearticle.php",
        data: {
            picture_id : picture_id,
            article_id : article_id,
            article_price : article_price,
            quantity : quantity
        },
        dataType: "json" ,
        success: function(res){
            $('tr#del_'+picture_id+'_'+article_id).fadeOut('slow');
            $('li#li_'+picture_id+'_'+article_id).remove();
			
            var pads = trim($('div#pads').html());
            if(pads.length == 0) {
                $('div#pads_h').remove();
                $('div#pads').remove();
            }
			
            var prints = trim($('div#prints').html());
            if(prints.length == 0) {
                $('div#prints_h').remove();
                $('div#prints').remove();
            }
			
            var mugs = trim($('div#mugs').html());
            if(mugs.length == 0) {
                $('div#mugs_h').remove();
                $('div#mugs').remove();
            }
			
            var trivets = trim($('div#trivets').html());
            if(trivets.length == 0) {
                $('div#trivets_h').remove();
                $('div#trivets').remove();
            }
			
            var trays = trim($('div#trays').html());
            if(trays.length == 0) {
                $('div#trays_h').remove();
                $('div#trays').remove();
            }
			
            var panorama = trim($('div#panorama').html());
            if(panorama.length == 0) {
                $('div#panorama_h').remove();
                $('div#panorama').remove();
            }
				
            var cart = trim($('div#cart3').html());
            if(cart.length == 0)
                $('div#cart2').remove()
				
            var amount = parseFloat($('span#amount_'+picture_id+'_'+article_id).html());
            var subtotal = parseFloat($('span#subtotal').html());
            $('span#subtotal').html((subtotal - amount).toFixed(2));
        }
    });
}

function addPictureToSelectedLightbox(form) {
    var picture = form.picture.value;
    var lightbox = form.lightbox.value;
    $.ajax({
        type: "POST",
        url: "/action/lightbox/do_addpicture.php",
        data: {
            picture : picture,
            lightbox : lightbox
        },
        dataType: "json" ,
        success: function(j)
        {
            $('a#lightbox_btn_rmv').show();
        }
    });
}

function removePictureFromSelectedLightbox(form) {
    var picture = form.picture.value;
    var lightbox = form.lightbox.value;
    $.ajax({
        type: "POST",
        url: "/action/lightbox/do_removepicture.php",
        data: {
            picture : picture,
            lightbox : lightbox
        },
        dataType: "json" ,
        success: function(j)
        {
			
        }
    });
}

function createNewLightbox(lightboxName) {
    $.ajax({
        type: "POST",
        url: "/action/lightbox/do_addlightbox_json.php",
        data: {
            lightboxName : lightboxName
        },
        dataType: "json",
        success: function(j_response) {
            $('#lightbox').append("<option value=" + j_response['lightboxId'] + " selected>" + lightboxName + "</option>");
            document.getElementById('lightboxName').value = '';
            $('#ulLightboxes').append(j_response['link']);
        }
    });
}


function subStrDelete(delimiter, needle, str) {
    var haystack = new Array();
    haystack = str.split(delimiter);
    var newArray = new Array();
		
    len = haystack.length;
    for(var j = 0; j < len; j++) {
        if (haystack[j] != needle) {
            newArray.push(haystack[j]);
        }
    }
	
    return(newArray.join(delimiter));
}



function getKeywords(keys) {

    $.ajax({
        type: "POST",
        url: "/action/keywordtool/get_keywords.php",
        data: {
            ids: keys
        },
        dataType: "json" ,
        success: function(j)
        {
       		       		
            if(j !== false && typeof j != "undefined" && j !== null) {
       		
                $('.tdKeyword').each(function() {
	       			
                    var id = $(this).attr('id').substr(10);
	       			
                    if(typeof j[id] != "undefined") {
                        $(this).children('A').fadeIn('fast');
                        $(this).children('A').children('SPAN').text(j[id].count);
                    } else {
                        $(this).children('A').fadeOut('fast');
                    }
	       			
                });
       		
            } else {
                $('.tdKeyword').children('A').fadeIn('fast');
            }
       		
			
        }
    });
}


function setFilter(keywordId) {
	
    var keywordIds =  $('#keywordIds').val();
    keywordIds = subStrDelete(',', keywordId, keywordIds);
	
    if ($('#tdKeyword_' + keywordId).css("font-weight") != "bold" && $('#tdKeyword_' + keywordId).css("font-weight") != 700 ) {
        $('#keywordIds').val(keywordIds + keywordId + ',');
        $('#tdKeyword_' + keywordId).css("font-weight", "bold");
    } else {
        $('#keywordIds').val(keywordIds);
        $('#tdKeyword_' + keywordId).css("font-weight", "");
    }
	
    getKeywords($('#keywordIds').val());
}

function setVoting(picId, vote) {
	
    if($('.votingStar').size() > 0) {
		
        $.get('/action/do_setVoting.php?pic=' + picId + '&vote=' + vote, function(data) {
			
            $('.votingStar').each(function(i) {
                if(i >= vote) {
                    $(this).removeClass('yellowStar');
                    $(this).addClass('greyStar');
                    $(this).data('star', 'grey');
                } else {
                    $(this).removeClass('greyStar');
                    $(this).addClass('yellowStar');
                    $(this).data('star', 'yellow');
                }
            });
			
            $('#votingText').text('Your vote for this picutre: ' + vote + ' stars');
			
        });
	
    }
	
}

function clearFilter() {
    $('.tdKeyword').css("font-weight", "");
    $('#keywordIds').val('');
    getKeywords($('#keywordIds').val());
}


function createKeywordTable() {
	
}

function openPopup (url, name, width, height) {
    fenster = window.open(url, name, "width=" + width + ",height=" + height + ",resizable=no,location=no,scrollbars=yes,status=no");
    fenster.focus();
    return false;
}

function selectDistribution() {
    if(document.getElementById('distribution').value == 'National')
        $('#distribution_country').show('slow');
    else
        $('#distribution_country').hide('slow');
}

function openCommentForm() {
    $('#divCommentForm').slideToggle();
}

function openContactForm() {
    $('#divContactForm').slideToggle();
}

function showAllComments() {
    $('#divShowAllComments').hide();
    $('#divMoreComments').slideToggle();
}

function getNextComments(picture, start, limit, quantity) {
    $.ajax({
        type: "POST",
        url: "/action/do_getComments.php",
        data: {
            picture : picture,
            start : start,
            limit : limit
        },
        dataType: "json",
        success: function(j_response) {

            for(var i = 0; i < j_response.length; i++) {
                $('#divComment_'+i).remove();
                $('#divAllComments').append('<div id="divComment_'+i+'" class="divComment"><i>'+j_response[i].username+' wrote</i><br /><br /><h2>'+j_response[i].title+'</h2><p>'+j_response[i].comment+'</p><div class="floatRight"><i>'+j_response[i].create_ts+'</i></div><div class="clearFloat"></div></div>');
            }
			
            $('#divPrevPage').show();
			
            var next = parseInt(document.getElementById('next').value) + parseInt(limit);
            $('#next').val(next);
            var back = parseInt(document.getElementById('back').value) + parseInt(limit);
            $('#back').val(back);
			
            if(document.getElementById('next').value >= quantity)
                $('#divNextPage').hide();
		
        }
    });
}

function getPrevComments(picture, start, limit) {
    $.ajax({
        type: "POST",
        url: "/action/do_getComments.php",
        data: {
            picture : picture,
            start : start,
            limit : limit
        },
        dataType: "json",
        success: function(j_response) {

            for(var i = 0; i < j_response.length; i++) {
                $('#divComment_'+i).remove();
                $('#divAllComments').append('<div id="divComment_'+i+'" class="divComment"><i>'+j_response[i].username+' wrote</i><br /><br /><h2>'+j_response[i].title+'</h2><p>'+j_response[i].comment+'</p><div class="floatRight"><i>'+j_response[i].create_ts+'</i></div><div class="clearFloat"></div></div>');
            }
			
            var next = parseInt(document.getElementById('next').value) - parseInt(limit);
            $('#next').val(next);
            var back = parseInt(document.getElementById('back').value) - parseInt(limit);
            $('#back').val(back);
			
            if(document.getElementById('back').value == -limit) {
                $('#divPrevPage').hide();
            }
			
            $('#divNextPage').show();
		
        }
    });
}

function checkRequest() {
     // Eingabe pr�fen     
     // typ='edit' -> changeuser
	typ = 'request';
    // Fehlermeldungen leeren
    $("div#error").empty();
    $("div#error").show();

     var f = document.getElementById('request');
     var fields = $("#request input").get();

    var noError = true;

    var fields_check = true;

    for (var i = 0; i < fields.length; i++ )
    {
        //console.log('CHECKFIELD: '+ fields[i].name);
        if (checkField(fields[i], 'checkform', typ) != true) {
            //console.log("false");
            fields_check = false;
        }
    }   
    
    if (!fields_check) {
        return false;
    }
    else {
	    // Formular abschicken
	    f.submit();
	    return true;
    }
}

// Benötigt für checkRequest
var checkField = function (el, mode, typ) {

    if (el == undefined || el.id == undefined)
        return false;
  
    /*
    if (mode != 'checkform')
    {
        // Wenn der User normal durch die Felder navigiert, sollen
        // leere Felder nicht als Fehler markiert werden. Nur beim
        // abschlie�enden CheckForm beim Abschicken der Registrierung
        if (el.value == '')
        {
            isError = false;
            return true;
        }   
    }
    */
    

    var reg, res, stErrorMsg = '', noError = true;
    
    //var f = document.getElementById('newuser');


    if (typ == "register") {
        var f = document.getElementById('newuser');
        var fields = $("#newuser input").get();
    } else if (typ == "request") {
        var f = document.getElementById('request');
        var fields = $("#request input").get();
    }

    //var f = getParentElement(el, 'form');
    //var r = YAHOO.util.Dom.getRegion(el);
    var ret = new Array();
    var noError = true;
    
    

    switch (el.name)
    {
        case 'user':
            //var badwords = findBadwordsInString(el.value);
            
            reg = new RegExp('^([a-zA-Z0-9!_-]{1,17})$');
            res = (reg.test(el.value));
            
            //console.log(el.value.charAt(el.value.length-1));
            
            if (!res || el.value.charAt(0) == '_')
            {
                stErrorMsg = 'Your username may only consist of letters (a-z, A-Z) and digits (0-9).<br />';
                displayFieldhint(stErrorMsg);
                noError = false;
            }
            else if (el.value.charAt(el.value.length-1) == '_')
            {
                stErrorMsg = 'Your username may not end with a _!<br />';
                displayFieldhint(stErrorMsg);
                noError = false;
            }
            else if(checkIfUsernameAlreadyExists(el.value) == true)
            {
                //console.log("username existiert 2");
                // var altUsernames = getAlternativeUsernames(el.value);                
                // YAHOO.log(altUsernames['alternatives']);
                
                stErrorMsg = 'This username already exists!<br />';
                displayFieldhint(stErrorMsg);
                noError = false;
            }
            else if (el.value.length < 3)
            {
                stErrorMsg = 'Invalid username: The username must be longer than 3 characters!<br />';
                displayFieldhint(stErrorMsg);
                noError = false;
            }
            else
            {
                // hideFieldhint(r['top']);
                noError = true;
            }
            
            
            break;
        case 'password':
            if (typ == "edit" && el.value=="") {
                // muss nicht gef�llt sein
                noError = true;
            } else {
                if (el.value.length < 5)
                {
                    stErrorMsg = 'Your password must be longer than 5 characters.<br />';
                    displayFieldhint(stErrorMsg);
    
                    noError = false;
                }
                else
                {
                    // hideFieldhint(r['top']);
                    noError = true;
                }
            
            }
	            
            break;
        case 'password2':
            if (typ == "edit" && el.value=="") {
                // muss nicht gef�llt sein
                noError = true;
            } else {
                if (f.password.value != el.value)
                {
                    stErrorMsg = 'Please repeat your password.<br />';
                    displayFieldhint(stErrorMsg, 'error');
                    noError = false;
                }
                else
                {
                    // hideFieldhint(r['top']);
                    noError = true;
                }
            }
	            

            break;
        case 'email':
            if (checkEmail(el.value) == false)
            {
                stErrorMsg = 'Please enter a valid e-mail address.!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            /*
            else if (checkIfEmailAlreadyExists(el.value) == true)
            {
                stErrorMsg = 'Sorry... Ein Benutzer mit dieser E-Mail-Adresse wurde bereits angelegt!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            */
            else
            {
                // hideFieldhint(r['top']);
                noError = true;
            }
            break;
        
        case 'name':
            if (el.value == '')
            {
                stErrorMsg = 'Please enter a valid name!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
            
        case 'webmaster':
            if (el.value == '')
            {
                stErrorMsg = 'Please enter a name!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
        case 'recipurl':
            if (el.value == '')
            {
                stErrorMsg = 'Please enter a valid url where we can find our link!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
        case 'url':
            if (el.value == 'http://' || el.value == '')
            {
                stErrorMsg = 'Please enter a valid url!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
        case 'website':
            if (el.value == '')
            {
                stErrorMsg = 'Please enter a Website!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
        case 'subject':
            if (el.value == '')
            {
                stErrorMsg = 'Please enter a valid subject!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
        
        case 'message':
        	alert(el.value);
            if (el.value.length == 0)
            {
                stErrorMsg = 'Please enter a message!<br />';
                displayFieldhint(stErrorMsg, 'error');
                noError = false;
            }
            else
            {
                noError = true;
            }
            break;
            			
        default:
            return true;
    }
    
    isError = !noError;
    
    if (isError == true)
    {
        fieldWithError = el.id;
    }

    return noError;
}

var checkEmail = function (s) {
    var a = false;
    var res = false;
    
    if(typeof(RegExp) == 'function')
    {
        var b = new RegExp('abc');
        if(b.test('abc') == true){a = true;}
    }
    
    if(a == true)
    {
        reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+ '(\\@)([a-zA-Z0-9\\-\\.]+)'+'(\\.)([a-zA-Z]{2,4})$');
        res = (reg.test(s));
    }
    else
    {
        res = (s.search('@') >= 1 && s.lastIndexOf('.') > s.search('@') && s.lastIndexOf('.') >= s.length-5);
    }

    return(res);
}
