//global var
var scroll_size;

function resizeAdjust() { //position adjustment when changing the window size
	$('#header .menu').css('top', ($(window).height() - $('#header .menu').height()) / 2.5);
	$('#footer').css('width', $(window).width() - 202);
	$('#contact').css('width', $(window).width() - 202);
	$('#contact_info').css('width', $(window).width() - (202 + 410)); //400 = #contact_me width
	$('#scrollable_posts').css('height', $(window).height() - 100);
	scroll_size = Math.floor(($(window).height() -110) / 155); //how much post we see (scroll)
	var full_post_w = Math.floor($(window).width() - ($('#header .menu').width() + 250 + 140));
	var full_post_h = $(window).height() - 180;
	$('#full_post').css({left: $('#header .menu').width() + 80, width: full_post_w, height: full_post_h});
	$('.entry').css({ width: full_post_w - 55});
	$('.jScrollPaneContainer').css({height: full_post_h - 45, width: full_post_w});
	$('.entry').jScrollPane({scrollbarMargin: 50, showArrows: true, arrowSize: 10});
}

function alp_categories() { //load post on activating and deactivating categories
	loading('on');
	$('#scroll_indicator').hide();
	var categories = '&cat=';
	$("#header .menu").find(".actived_cat").each(function() {
		categories += $(this).attr('name') + ',';
    });
	categories = categories.substring(0, categories.length-1);
	if (categories == '&cat') categories = '';
	$('#load_post').clearQueue().animate({right: -300}, {queue:false, duration: 500, easing: 'easeOutExpo'});
	if (alp.indexOf('?') == -1) { var amp_or_what = '?'; } else { var amp_or_what = '&'; }
	$('#load_post').load(alp + amp_or_what + 'twi_cat' + categories, function(){
		$('#load_post').animate({right: 0}, {queue:false, duration: 500, easing: 'easeOutExpo'});
		$('#load_post').animate({top:0});
		load_home();
		loading('off');
		scroll_indicator();
	});
}

function alp_posts(name, twi) { //load post AND page content
	loading('on');
	if (alp.indexOf('?') == -1) { var amp_or_what = '?'; } else { var amp_or_what = '&'; }
	background(name, twi);
	$('#full_post').load(alp+amp_or_what+twi+'&slug=' + name, function(){
		load_home();
		$('.entry').css({height: $(window).height() - 225});
		$('#full_post').fadeIn('slow', function(){
			$('.entry').jScrollPane({scrollbarMargin: 50, showArrows: true, arrowSize: 10, wheelSpeed: 100, reinitialiseOnImageLoad: true});
		});
		loading('off');
		scroll_indicator();
		$("#content #full_post .entry a:has(img)").fancybox({
			'titlePosition'	:	'over',
			'onComplete'	:	function() {
				$("#fancybox-wrap").hover(function() {
					$("#fancybox-title").show();
				}, function() {
					$("#fancybox-title").hide();
				});
			}
		});
	});
}

function loading(action) { //loading animation
	if (action == 'on') $('#loading').fadeTo('fast', 0.8);
		else $('#loading').fadeTo('fast', 0);
}

function sendmail(name, mail, message) {
	if (alp.indexOf('?') == -1) { var amp_or_what = '?'; } else { var amp_or_what = '&'; }	
	$.post(alp + amp_or_what + 'twi_sendmail=0', { name: name, mail: mail, message: message },
	   function(data){
	   	//sent
	   });
}


function load_home() { //reset everything there is no content
	if ( ($('#full_post').is(':empty')) && ($('#load_post').is(':empty')) ) {
		$('#homepage').clearQueue().fadeTo('fast', 1);
		$('#homepage').css('display', 'block');
		$('#contact').fadeOut('slow');
		$('#gmaps').animate({left: -210}, {queue:false});
		background(home, 'pagename');
    }

}

function scroll_indicator() { //show scroll_indicator or not
	var nb_posts = $("#load_post").find(".posts"); 
	if (nb_posts.length > scroll_size) { $('#scroll_indicator').show(); } else { $('#scroll_indicator').hide(); }
}

function background(name, twi) {
	if (alp.indexOf('?') == -1) { var amp_or_what = '?'; } else { var amp_or_what = '&'; }
	if (twi == 'twi_post') { var type = 'name'; } else { var type = 'pagename'; }
	$.getJSON(alp+amp_or_what+'twi_bg&slug=' + name + '&type=' + type, function(data){
		if (slider_activate == 'on') {
			$.fn.bgslide.plop(data[0], data[1], data[2]);
		} else {
			if ($('#firstbg').attr('src') == '') {
				activebg = 'secondbg';
				unactivebg = 'firstbg';
			} else {
				activebg = 'firstbg';
				unactivebg = 'secondbg';
			}
			if (data[0]!='') {
				if (data[0] != $('#'+activebg).attr('src')) {
					$('#'+unactivebg).attr('src', data[0]);
					var img = new Image();
					img.src = data[0];
					var FullscreenrOptions = {  width: img.width, height: img.height, bgID: '#'+unactivebg };
					jQuery.fn.fullscreenr(FullscreenrOptions);
					
					$('#'+activebg).fadeOut('slow', function(){
						$('#'+unactivebg).fadeIn('slow');
						$('#'+activebg).attr('src', '');
					});
					
					
				}
			} else {
				$('#'+activebg).css('opacity', 0);
			}
		}
	});
}


$(document).ready(function () {

    resizeAdjust();

    //fixing a margin problem on firefox mac
    userAgent = navigator.userAgent.toLowerCase();
    if ((userAgent.indexOf('mac') != -1) && (userAgent.indexOf('firefox') != -1)) {
        $('#footer .menu ul li').css({ marginBottom: 0 });
    }

    $('.categories').click(function () { //activate or deactivate categories
        if (!$(this).hasClass('actived_cat')) {
            if (multicategories == false) { //multicat or not?
                $("#header .menu").find(".actived_cat").each(function () {
                    $(this).css({ paddingLeft: '10px' });
                    $('.categories').removeClass('actived_cat');
                    $('.pages').removeClass('actived_cat');
                });
            }

            $('#contact').fadeOut('slow');
            $('#footer .menu a').removeClass('actived_page');

            if ($('#gmaps').css('left') == '0px') {
                $('#contact').fadeOut('slow');
                $('#gmaps').animate({ left: -210 }, { queue: false });
                $('#go_contact_page').removeClass('actived_page');
            }

            $('#homepage').fadeTo('slow', 0, function () {
                $('#homepage').css('display', 'none');
            });
            $(this).addClass('actived_cat');
        } else {
            $(this).removeClass('actived_cat');
        }
        alp_categories();
    });

    $('#load_post .posts').live('click', function () { //load one post content
        $('#contact').fadeOut('slow');
        $('#go_contact_page').removeClass('actived_page');

        if (!$('h2', this).hasClass('actived_post')) {
            $('h2.actived_post').animate({ opacity: 1 }, { queue: false });
            $('h2').removeClass('actived_post');
            $('h2', this).addClass('actived_post');
            alp_posts($(this).attr('id'), 'twi_post');
        } else {
            $('h2', this).removeClass('actived_post');
            $('#full_post').hide('slow', function () {
                $('#full_post').empty();
            });
        }
    });

    // start modifs by DS

    $('.pages').click(function () { //load one page content

        $('#homepage').fadeTo('slow', 0, function () {
            $('#homepage').css('display', 'none');
        });
        if (!$(this).hasClass('actived_cat')) {
            $("#header .menu").find(".actived_cat").each(function () {
                $(this).css({ paddingLeft: '10px' });
                //$('.categories').removeClass('actived_cat');
            });
            $('#header .menu ul li a').removeClass('actived_cat');
            $('#contact').fadeOut('slow');

            $('#footer .menu a').removeClass('actived_page');

            alp_categories();
            $(this).addClass('actived_cat');
            alp_posts($(this).parents('li').attr('id'), 'twi_page');
        } /*else {
            $(this).removeClass('actived_cat');
            $('#full_post').hide('slow', function () {
                $('#full_post').empty();
                load_home();
                if ($(this).attr('id') != 'go_contact_page') {

                    $('#contact').fadeOut('slow');
                    $('#gmaps').animate({ left: -210 }, { queue: false });

                }
            });
        }*/
    });

    // end modifds by ds

    $('#footer .menu a').click(function () { //load one page content
        $('#homepage').fadeTo('slow', 0, function () {
            $('#homepage').css('display', 'none');
        });
        if (!$(this).hasClass('actived_page')) {
            $('#footer .menu ul li a').removeClass('actived_page');
            $(this).addClass('actived_page');
            if ($(this).attr('id') != 'go_contact_page') {
                $("#header .menu").find(".actived_cat").each(function () {
                    $(this).css({ paddingLeft: '10px' });
                });
                $('.categories').removeClass('actived_cat');
                $('.pages').removeClass('actived_cat');
                alp_categories();
                alp_posts($(this).parents('li').attr('id'), 'twi_page');
                if ($('#gmaps').css('left') == '0px') {
                    $('#contact').fadeOut('slow');
                    $('#gmaps').animate({ left: -210 }, { queue: false });
                    $('#go_contact_page').removeClass('actived_page');
                }
                $('#contact').fadeOut('slow');
            } else {
                //Click Action Contact form here
                $('#contact').fadeIn('slow');
            }
        } else {
            $(this).removeClass('actived_page');
            $('#contact').fadeOut('slow');
        }
    });

    $('#logo').click(function () { //reset everything!
        $('#header .menu .categories').removeClass('actived_cat');
        $('#footer .menu a').removeClass('actived_page');
        $('#scroll_indicator').hide();
        $('#load_post').animate({ right: -300 }, function () {
            $('#load_post').empty();
            $('#full_post').hide('slow', function () {
                $('#full_post').empty();
                load_home();
                $('#go_home').click();  // added by DS
            });
        });
    });

    $('#network').hover(function () { //facebook, twitter, etc...
        $(this).animate({ opacity: 0.8 }, { queue: false });
    },
	function () {
	    $(this).animate({ opacity: 0.3 }, { queue: false });
	});

    $('#header .menu li a').hover(function () { //animation for categories menu
        $(this).animate({ paddingLeft: '20px' }, { queue: false, duration: 100 });
    },
	function () {
	    if (!$(this).hasClass('actived_cat'))
	        $(this).animate({ paddingLeft: '10px' }, { queue: false, duration: 100 });
	});

    $('#load_post .posts').live('mouseover mouseout', function (event) { //opacity effect on post hover
        if ((!$('h2', this).hasClass('actived_post'))) {
            if (event.type == 'mouseover') {
                $('h2', this).animate({ opacity: 0.4 }, { queue: false, duration: 100 });
                $('h4', this).animate({ opacity: 0.4 }, { queue: false, duration: 100 });
            } else {
                $('h2', this).animate({ opacity: 1 }, { queue: false, duration: 100 });
                $('h4', this).animate({ opacity: 1 }, { queue: false, duration: 100 });
            }
        }
    });


    //Send mail
    $("#contact_me").submit(function () {
        $("#error").html('');
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            url: wpurl + "/wp-admin/admin-ajax.php",
            data: 'action=contact_form&' + str,
            success: function (msg) {
                $("#error").ajaxComplete(function (event, request, settings) {
                    if (msg == 'sent') {
                        $('#contact_me').fadeOut('fast');
                        $('#sent').fadeIn('fast');
                    } else {
                        $("#error").html(msg);
                    }
                });
            }
        });
        return false;
    });




    $('#scrollable_posts').scrollable({ //make the thumbnail scrollable
        vertical: true,
        size: scroll_size
    }).mousewheel(100);

    // Load content if we have an specific URL... this is this easy part :P
    var url = document.location.href;
    url = parseUri(url).anchor;
    if (url != '') {
        if (url.indexOf('/portfolio|') == -1) { //load page or categories
            id = url.replace(/\//g, '');
            $('#go_' + id).click();
        } else { //load portfolio post
            var re = '((?:[a-z][a-z0-9_]*))((?:\\/[\\w\\.\\-]+)+)'; //read a portfolio post url
            var regex = new RegExp(re, ['i']);
            var matches = regex.exec(url);
            var cat_to_load = matches[1];
            var post_to_load = matches[2].substr(1);

            $('#go_' + cat_to_load).css({ paddingLeft: '20px' });
            if (post_to_load != '') {
                alp_posts(post_to_load, 'twi_post');
            }
            else {
                $('#go_' + cat_to_load).click();
            }
        }
    }
    else {
        $('#go_home').click(); // added by DS
    }
    if (slider_activate == 'off') {
        var img_home = new Image();
        img_home.src = $('#firstbg').attr('src');
        if (img_home.src != '') {
            var w = img_home.width;
            var h = img_home.height;
            var FullscreenrOptions = { width: w, height: h, bgID: '#firstbg' };
            jQuery.fn.fullscreenr(FullscreenrOptions);
            $('#firstbg').fadeIn('slow');
        }
    }

});

window.onresize = function() {
	resizeAdjust();
	var api = $('#scrollable_posts').scrollable();
	api.getConf().size = scroll_size;
}


// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};
parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
