// some globals are more global than others
var imgpath = '/images/gallery/',
    galpath = '/gallery/',
    // globals needed for keynavigation
    // isoverlay will be set by Shadowbow onOpen handler
    isoverlay = false,
    globalid = '',
    maxid;

// funktion, um den titel zu veraendern
var changetitle = function(imgid, imgtitle) {
    var oldtitle = document.title,
        newtitle = 'Portfolio » "' + imgtitle + '" » www.wondertom.de - Tom Arnold, Illustration, Frankfurt am Main';
    if (oldtitle != newtitle) {
        document.title = newtitle;
    }
};

// funtion um piwikcode zu aktualisieren
var writePiwikCode = function(imgid, imgtitle) {
    $('#pwajax').remove();
    imgtitle = imgtitle.replace(/(['\/])/, "\\$1");
    //window.console.log(imgtitle);
    var tracktitle = "Portfolio (Ajax) » \"" + imgtitle + "\" » www.wondertom.de - Tom Arnold, Illustration, Frankfurt am Main",
        trackurl = '/gallery/' + imgid + '/',
        piwikscript = document.createElement('script');
    piwikscript.type = 'text/javascript';
    piwikscript.id = 'pwajax';
    piwikscript.text = "try {";
    piwikscript.text += "  piwikTracker.setDocumentTitle('" + tracktitle + "');";
    piwikscript.text += "  piwikTracker.setCustomUrl('" + trackurl + "');";
    piwikscript.text += "  piwikTracker.trackPageView();";
    piwikscript.text += "  piwikTracker.enableLinkTracking();";
    piwikscript.text += "} catch(err) {}";

    document.body.appendChild(piwikscript);
};

// funktion zum img(nach)laden
var imgload = function(target, src, description) {
    if (src == $(target).attr('src')) {
        return false;
    } else {
        $(target).wrap('<div class="loaderwrap">');
        $('div.loaderwrap').empty();
        $('div.loaderwrap').append('<img class="loader" src="/images/ajax-loader-1.gif" />');
        var galimg = new Image();
        $(galimg).load(function() {
            $(this).hide();
            $('div.loaderwrap').empty().append(this).zap();
            $(this).fadeIn();
        }).attr('src', src).attr('id', 'galleryimg').attr('title', description);
    }
    return true;
};

// test auf html5 localstorage
var supports_html5_storage = function() {
    try {
        return 'localStorage' in window && window.localStorage !== null;
    } catch (e) {
        return false;
    }
};

// angesehenes bild speichern
var setLastSeenPic = function(imgid) {
    if (!supports_html5_storage()) {
        return false;
    }
    localStorage['wt.lastpic'] = imgid;
    return true;
};

// zum zuletzt gesehenes bild gehen
var getLastSeenPic = function() {
    if (!supports_html5_storage()) {
        return false;
    }
    return localStorage['wt.lastpic'];
};

// undo wrap()
$.fn.zap = function() {
    return this.each(function() {
        $(this.childNodes).insertBefore(this);
    }).remove();
};

var writethumbs = function(thumbs, imgid) {
    var out = '<ul>';
    $(thumbs).each(function() {
        var act = (imgid == this.id) ? ' class="active"' : '';
        out += '<li' + act + '><a href="' + this.href + '/" class="trigger-' + this.id + '"><img src="' + this.src + '" title="' + this.title + '" /></a></li>';
    });
    out += '</ul>';
    return out;
};

var initpage = function(imgid) {
    $.getJSON('/json.php?callback=?', {
        img: imgid
    }, function(gal) {

        // for keynavigation
        globalid = imgid;

        // history veraendern (hachja)
        if (history.pushState) {
            history.pushState({
                img: imgid
            }, 'Portfolio » "' + gal.image.info.Motiv + '" » www.wondertom.de - Tom Arnold, Illustration, Frankfurt am Main', '/gallery/' + imgid + '/');
        }
        // titel machen
        changetitle(imgid, gal.image.info.Motiv);

        // piwik auf ajax ansetzen:
        writePiwikCode(imgid, gal.image.info.Motiv);

        // raus damit
        if (gal.prevgal) {
            $('#prev').html('<a href="/gallery/' + gal.prevgal.id + '/" class="trigger-' + gal.prevgal.id + '" title="' + gal.prevgal.title + '"><img src="' + gal.prevgal.src + '" /></a>');
        } else {
            $('#prev').empty();
        }
        $('#thumbs').html(writethumbs(gal.thumbs, imgid));
        if (gal.nextgal) {
            $('#next').html('<a href="/gallery/' + gal.nextgal.id + '/" class="trigger-' + gal.nextgal.id + '" title="' + gal.nextgal.title + '"><img src="' + gal.nextgal.src + '" /></a>');
        } else {
            $('#next').empty();
        }
        if (gal.previmg) {
            $('#prev-img').html('<a href="/gallery/' + gal.previmg.id + '/" class="trigger-' + gal.previmg.id + '" title="' + gal.previmg.title + '"><img src="' + gal.previmg.src + '" /></a>');
        } else {
            $('#prev-img').empty();
        }

        // hauptbild
        imgload('#galleryimg', gal.image.src, gal.image.info.Motiv);

        if (gal.nextimg) {
            $('#next-img').html('<a href="/gallery/' + gal.nextimg.id + '/" class="trigger-' + gal.nextimg.id + '" title="' + gal.nextimg.title + '"><img src="' + gal.nextimg.src + '" /></a>');
        } else {
            $('#next-img').empty();
        }

        if (gal.image.info) {
            out = '';
            if (gal.image.info.Motiv) {
                out += '<h3 class="light">' + gal.image.info.Motiv + '</h3>';
            }
            out += '<p><span class="light">Für:</span> ' + gal.image.info.Kunde + '<br />';
            out += '<span class="light">Mit:</span> ' + gal.image.info.Technik + '</p>';
            if (gal.image.info.detailpic) {
                out += '<p>&nbsp;</p>';
                out += '<p style="font-weight:bold;">';
                out += '+ <a href="' + gal.image.info.detailpic + '" class="thickbox" rel="shadowbox[b' + gal.image.id + ']" title="' + gal.image.info.detailinfo + '">' + gal.image.info.detaillabel + '</a>';
                // follow-ups vorhanden?
                if (gal.image.info.detailfollow) {
                    var temp = gal.image.info.detailfollow.split(','); // array
                    out += '<span class="bot-content">(';
                    var more = 1;
                    for (more = 1; more <= temp.length; more++) {
                        out += '<a href="' + temp[more - 1] + '" class="thickbox" rel="shadowbox[b' + gal.image.id + ']" title="' + gal.image.info.detailinfo + '">' + more + '</a> ';
                    }
                    out += ')</span>';
                }
                out += '</p>';
            }
            if (gal.image.info.kaufen == "1") {
                out += '<p>&nbsp;</p>';
                out += '<h3 class="light">Dieses Bild kann man übrigens auch <a href="/shop/#' + gal.image.info.detailid + '">KAUFEN</a> :-)</h3>';
            }
            // share links
            var shareurl = escape('http://wondertom.de/?img=' + imgid);
            out += '<div class="shares"><ul><li class="tw">';
            out += '<a href="http://twitter.com/share?url=' + shareurl + '&amp;count=vertical&amp;related=webrocker&amp;text=' + escape('I went to wondertom.de and all I got was this lousy link :) ') + '" title="Zeigs den anderen auf Twitter…" target="_blank">';
            out += '<span>Twitter</span></a></li><li class="fb">';
            out += '<a href="http://facebook.com/sharer.php?u=' + shareurl + '" title="Zeigs den anderen auf Facebook…" target="_blank">';
            out += '<span>Facebook</span></a></li></ul></div>';
            //
            $('#description').html(out);
        } else {
            $('#description').empty();
        }
        //re-attach thickbox/shadowbox
        //tb_init('a.thickbox, area.thickbox, input.thickbox');
        Shadowbox.clearCache();
        Shadowbox.setup('a.thickbox', {
            overlayOpacity: 0.9,
            overlayColor: '#567',
            onOpen: function() {
                isoverlay = true;
            },
            onClose: function() {
                isoverlay = false;
            }
        });
/*
            Shadowbox.setup('.shares a', {
                width: 600,
                height: 400,
                overlayOpacity: 0.9,
                overlayColor: '#567'
            });*/

        // test mit localstorage
        if (imgid != getLastSeenPic()) {
            setLastSeenPic(imgid);
        }
    });
};
var getTrigger = function(trigger){
	return trigger.replace('trigger-','');
};

$('#news a').live('click', function(e) {
	initpage( getTrigger($(this).attr('class')) );
    e.preventDefault();
});
$('#thumbs a').live('click', function(e) {
	var triggerID = getTrigger($(this).attr('class'));
    if (triggerID != getLastSeenPic()) {
        initpage(triggerID);
    }
    e.preventDefault();
});
$('#prev a').live('click', function(e) {
    initpage(getTrigger($(this).attr('class')));
    e.preventDefault();
});
$('#next a').live('click', function(e) {
	initpage(getTrigger($(this).attr('class')));
    e.preventDefault();
});
$('#prev-img a').live('click', function(e) {
    initpage(getTrigger($(this).attr('class')));
    e.preventDefault();
});
$('#next-img a').live('click', function(e) {
    initpage(getTrigger($(this).attr('class')));
    e.preventDefault();
});
// tastatur
$(document).keydown(function(e) {
    if (!isoverlay) {
        var myid = globalid;
        // arrow left
        if (e.keyCode == 37) {
            if (myid <= 1) {
                myid = maxid;
            } else {
                myid--;
            }
            initpage(myid);
            e.preventDefault();
        }
        // arrow right
        if (e.keyCode == 39) {
            if (myid == maxid) {
                myid = 1;
            } else {
                myid++;
            }
            initpage(myid);
            e.preventDefault();
        }
    }
});

$(document).ready(function() {

    var imgid = 1,
        //fallback
        lsp = getLastSeenPic(),
        qs = document.location.search,
        dl = document.location.toString(),
        temp = '',
        temp1 = '';

    if (lsp && lsp !== '') {
        imgid = getLastSeenPic();
    }

    if (document.location.search !== '') {
        temp = qs.split('?img=');
        imgid = temp[1];
        temp = '';
    }

    if (dl.indexOf('/gallery/') != -1 && document.location.hash === '') {
        temp = dl.split('/gallery/');
        temp1 = temp[1].split('/');
        imgid = temp1[0];
        temp = '';
        temp1 = '';
    } else if (document.location.hash !== '' && document.location.hash.indexOf('/gallery/') != -1) {
        temp = document.location.hash.split('/gallery/');
        temp1 = temp[1].split('/');
        imgid = temp1[0];
    }
    //
    initpage(imgid);
    globalid = imgid;
    maxid = getTrigger($('#news a').attr('class'));

    Shadowbox.init({
        skipSetup: true
    });
    //
    $('#news h3 a').effect("pulsate", {
        times: 3
    }, 5000);

});

