/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Create multiple cookies at once stored in an object, with optional parameters affecting them all.
 *
 * @example $.cookie({ 'the_cookie' : 'the_value' });
 * @desc Set/delete multiple cookies at once.
 * @example $.cookie({ 'the_cookie' : 'the_value' }, { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Set/delete multiple cookies with options.
 *
 * @param Object name An object with multiple cookie name-value pairs.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the names and values of all cookies for the page.
 *
 * @example $.cookie();
 * @desc Get all the cookies for the page
 *
 * @return an object with the name-value pairs of all available cookies.
 * @type Object
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
          for (var n in name) { jQuery.cookie(n, name[n], value||options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};







$(document).ready(function(){

	//checking the window hash and forcing to load the appropriate project/news item 
	var projectid = window.location.hash.substr(1);
	if(projectid) loadProject1(projectid);

	//cufon
	Cufon.replace('.din');
	Cufon.replace('.menu a.mainitem',{
							hover: {
								color: '#ffffff'
							}
	});
	Cufon.replace('.menu .submenu a', {
							hover: {
								color: '#000000'
							}
	});

	//fancybox
	if($("a.fancybox").length)
		$("a.fancybox").fancybox();
	if($("a.iframe").length)
		$("a.iframe").fancybox({widht:560, height:320});

	//scroller
	$(".up").click(function(){
		window.scrollBy(0,-920);
	});
	$(".down").click(function(){
		window.scrollBy(0,920);
	});

	//search form display
	$("#search").click(function(){
		$(".menu>a").removeClass("selected");
		$(this).addClass("selected");
		$(".searchfrm").show();
	});
	
	$("#searchinput").keypress(function(e){
	//	e.preventDefault();
		c = e.which?e.which:e.keyCode;
		if(e.which == 13){
			$('form#searchfrm').submit();
		}
	});

	//gallery project click listeners
	projectListeners();

	$('#projects').infinitescroll({
//		callback		: function () { console.log('using opts.callback'); },
		navSelector  	: "a#next:last",
		nextSelector 	: "a#next:last",
		itemSelector 	: "#projects",
		debug		 	: false,
		dataType	 	: 'html',
		loading: {
			finishedMsg: "&nbsp;",
			img: "imgs/loading.gif",
			msgText: ""
		},
		// behavior		: 'twitter',
		// appendCallback	: false, // USE FOR PREPENDING
		// pathParse     	: function( pathStr, nextPage ){ return pathStr.replace('2', nextPage ); }
		}, function(newElements){
			//USE FOR PREPENDING
			// $(newElements).css('background-color','#ffef00');
			// $(this).prepend(newElements);
			//END OF PREPENDING
//			window.console && console.log('context: ',this);
//			window.console && console.log('returned: ', newElements);
			projectListeners();
	});

});

	function projectListeners(){
		var deviceAgent = navigator.userAgent.toLowerCase();
		var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
		if (agentID) {
			$(".grid1").live('touchend',function(obj){loadProject(obj);});
			$(".grid2").live('touchend',function(obj){loadProject(obj);});
			$(".grid3").live('touchend',function(obj){loadProject(obj);});
			$(".grid4").live('touchend',function(obj){loadProject(obj);});
		}else{
			$(".grid1").click(function(obj){loadProject(obj);});
			$(".grid2").click(function(obj){loadProject(obj);});
			$(".grid3").click(function(obj){loadProject(obj);});
			$(".grid4").click(function(obj){loadProject(obj);});
		}
	}


	function loadProject(obj){
		obj.preventDefault();
		var c = $(obj.target).attr('class');
		var projectid;
		switch(c){
//			case 'hover' : projectid = $(obj.target).parent().attr('id').substr(7); break;
			case 'title' :  projectid = $(obj.target).parent().parent().attr('id').substr(7); break;
			case 'logosmall' :  projectid = $(obj.target).parent().parent().attr('id').substr(7); break;
			default : projectid = $(obj.target).parent().attr('id').substr(7); break;
		}
		//in FF we need to use html in Chrome and Safari we use body
		var node='html';
		if($.browser.chrome||$.browser.safari){var node='body';}
		
		if($("#project"+projectid).hasClass('selected')){
			$(node).animate({scrollTop: 0},'slow', 'linear');
			return;
		}
		$(".grid1").removeClass('selected');
		$(".grid2").removeClass('selected');
		$(".grid3").removeClass('selected');
		$(".grid4").removeClass('selected');
		$("#project"+projectid).addClass('selected');

		//scrolling to top
		var delay1 = 800;
		if($(node).scrollTop()>10){
			var delay = 600;
		}else{
			var delay = 0;
		}

		$(node).animate({scrollTop: 0}, delay, 'linear', function(){
			//displaying the loading icon
			$("#projectDetails").slideUp(delay1, function(){
		//		$("#projectDetails").html("<div class='loading'><img src='imgs/loading.gif' border='0'/> LOADING PROJECT DATA...</div>");
		//		$("#projectDetails").slideDown('fast');
				//loading content via AJAX
				//if we are in news we need to just change the action property
				var action='getProject';
				if($("#isnews").val()=='news'){action='getNews';}
				$.post('projects.api.php', {action: action, id: projectid}, function(data){
					//find how to load the content 
//					$("#projectDetails").slideUp(delay1, function(){
						$("#projectDetails").html(data);
						var title = $("#projectDetails .content>h1").html();
						title = title.split('|');
						document.title=title[0];
						$("a.fancybox").fancybox();
						$("a.iframe").fancybox({widht:560, height:320});
						$("#projectDetails").slideDown(delay1);
						//updateing the hash URL
						window.location.hash = projectid;
						galleryLikeListener();
//					});
				});

			});
		});
	}
	
	
	function loadProject1(projectid){
		//in FF we need to use html in Chrome and Safari we use body
		var node='html';
		if($.browser.chrome||$.browser.safari){var node='body';}
		
		if($("#project"+projectid).hasClass('selected')){
			$(node).animate({scrollTop: 0},'slow', 'linear');
			return;
		}
		$(".grid1").removeClass('selected');
		$(".grid2").removeClass('selected');
		$(".grid3").removeClass('selected');
		$(".grid4").removeClass('selected');
		$("#project"+projectid).addClass('selected');
		//scrolling to top
		var delay1 = 800;
		if($(node).scrollTop()>10){
			var delay = 600;
		}else{
			var delay = 0;
		}
		$(node).animate({scrollTop: 0}, delay, 'linear', function(){
			//displaying the loading icon
			$("#projectDetails").slideUp(delay1, function(){
				var action='getProject';
				if($("#isnews").val()=='news'){action='getNews';}
				$.post('projects.api.php', {action: action, id: projectid}, function(data){
						$("#projectDetails").html(data);
						var title = $("#projectDetails .content>h1").html();
						title = title.split('|');
						document.title=title[0];
						$("a.fancybox").fancybox();
						$("a.iframe").fancybox({widht:560, height:320});
						$("#projectDetails").slideDown(delay1);
						//updateing the hash URL
						window.location.hash = projectid;
						galleryLikeListener();
				});
			});
		});
	}
	
function galleryLikeListener(){
		//gallery like
	$("a.like").hover(function(){
		if($(this).html()!='LIKE'){
			$(this).attr('likes',$(this).html());
			$(this).html('LIKE');
		}
	});
	$(".like").mouseout(function(){
		if($(this).html()=='LIKE'&&$(this).attr('likes')){
			$(this).html($(this).attr('likes'));
		}
	});
	$("a.like").click(function(){
		var type = 'projects';
		if($("#isnews").val()=='news'){type='news';}
		if($.cookie(type+$(this).attr('gallery'))==1){
			//already voted for this gallery
		}else{
			var action = type+'like';
			$.post("projects.api.php", {action:action, id: $(this).attr('gallery')});
			if($(this).attr("likes")){
				$(this).attr("likes", parseInt($(this).attr("likes"))+1);
			}else{
				$(this).attr("likes", 1);
			}
			$(this).html($(this).attr('likes'));
			$.cookie(type+$(this).attr('gallery'), 1);
		}
	});
}







function submitFrm(id){
	$("#"+id).submit();
}
