/*!
Copyright © 2010-2011 Clickwise Limited
All rights reserved.

No part of this code may be used, reproduced, transmitted, or stored in any
retrieval system of any nature, without the written permission of Clickwise
Limited.
*/

/********************************************************************************
CLK global object
********************************************************************************/
var CLK = CLK || {};

CLK.root = 'http://www.pwntechnologies.nl';
//CLK.root = 'file:///Users/Daniel/Projects/PWN%20Technologies/www.pwntechnologies.nl/development/wwwroot';
//CLK.root = 'http://www.clickwise.co.nz/laboratory/www.pwntechnologies.nl';

/*###############################################################################
CLK tools namespace
###############################################################################*/
CLK.tools = CLK.tools || {};

/********************************************************************************
cookie method to read and write cookies
********************************************************************************/
CLK.tools.cookie = function(name, value, args) {
    var cookie, cookies, cookieValue, date, domain, expires, i, path, secure;

    date = new Date();
    if (typeof value !== 'undefined') {
        args = args || {};
        if (value === null) {
            value = '';
            args.expires = -1;
        }
        if (args.expires && (typeof args.expires === 'number' || args.expires.toUTCString)) {
            if (typeof args.expires === 'number') {
                date.setTime(date.getTime() + (args.expires * 24 * 60 * 60 * 1000));
            } else {
                date = args.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = args.path ? '; path=' + (args.path) : '; path=/';
        domain = args.domain ? '; domain=' + (args.domain) : '';
        secure = args.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            cookies = document.cookie.split(';');
            for (i = 0; i < cookies.length; i++) {
                cookie = $.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/********************************************************************************
date converter method
********************************************************************************/
CLK.tools.dateFromString = function(args) {
    var dash1, dash2, dash3, dd, mm, yyyy, days, months, date;

    days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

    dash1 = args.indexOf('-');
    dash2 = args.indexOf('-', dash1 + 1);
    dash3 = args.indexOf('T', dash2 + 1);
    yyyy = args.substring(0, dash1);
    mm = args.substring(dash1 + 1, dash2);
    dd = args.substring(dash2 + 1, dash3);

    date = new Date(mm + '/' + dd + '/' + yyyy);
    return days[date.getDay()] + ', ' + date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();
};

/********************************************************************************
query method to read the querystring
********************************************************************************/
CLK.tools.query = function() {
    var key, result, query, val;

    result = {};
    query = location.search;
    /* remove the leading ? */
    query = query.replace(/^\?/, '');
    /* remove the trailing & */
    query = query.replace(/\&$/, '');
    $.each(query.split('&'), function() {
        key = this.split('=')[0];
        val = this.split('=')[1];
        /* convert floats */
        if (/^[0-9.]+$/.test(val)) {
            val = parseFloat(val);
        }
        /* ingnore empty values */
        if (val) {
            result[key] = val;
        }
    });
    return result;
};

/*###############################################################################
CLK services namespace
###############################################################################*/
CLK.services = CLK.services || {};

CLK.services.cache;

/********************************************************************************
news list services
********************************************************************************/
CLK.services.newslist = function(args) {

    if (args.container) { args.container.html('<div class="loader"></div>'); }

    if (CLK.services.cache) {
        if (args.callback) { args.callback(CLK.services.cache, args); }
    } else {
        CLK.services.lock = true;
        $.ajax({
            async: false,
            type: 'GET',
            url: CLK.root + '/resources/news/news.xml',
            cache: false,
            data: {},
            dataType: 'xml',
            success: function(data, textStatus) { CLK.services.cache = data; if (args.callback) { args.callback(data, args); } },
            error: function() { if (args.container) { args.container.html('<div class="ajaxerror"></div>'); } }
        });
    }
};

/********************************************************************************
builds news list
********************************************************************************/
CLK.newslist = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsList(container) {
        var html = [];

        html[html.length] = '<div class="news">';
        $(cache).find('entry').each(function() {
            html[html.length] = '<div class="header2">';
            html[html.length] = $(this).find('title').text();
            html[html.length] = '</div>';
            html[html.length] = '<div class="date">';
            html[html.length] = CLK.tools.dateFromString($(this).find('updated').text());
            html[html.length] = '</div>';
            html[html.length] = '<div class="content">';
            html[html.length] = $(this).find('summary').text();
            html[html.length] = '<br />';
            html[html.length] = '<a href="'; html[html.length] = $(this).find('link').attr('href'); html[html.length] = '">';
            html[html.length] = 'Read more»';
            html[html.length] = '</a>';
            html[html.length] = '</div>';
        });
        html[html.length] = '</div>';
        container.html(html.join(''));
    }

    function callbackNewsList(data, args) {
        cache = data;
        buildNewsList(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsList });
    });
};

/********************************************************************************
builds latest news list
********************************************************************************/
CLK.newslistlatest = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsList(container) {
        var i = 0, html = [];

        html[html.length] = '<div class="news">';
        $(cache).find('entry').each(function() {
            if (i < 4) {
                html[html.length] = '<div class="header2">';
                html[html.length] = $(this).find('title').text();
                html[html.length] = '</div>';
                html[html.length] = '<div class="date">';
                html[html.length] = CLK.tools.dateFromString($(this).find('updated').text());
                html[html.length] = '</div>';
                html[html.length] = '<div class="content">';
                html[html.length] = $(this).find('summary').text();
                html[html.length] = '<br />';
                html[html.length] = '<a href="';
                html[html.length] = $(this).find('link').attr('href');
                html[html.length] = '">';
                html[html.length] = 'Read more»';
                html[html.length] = '</a>';
                html[html.length] = '</div>';
            }
            i++;
        });
        html[html.length] = '</div>';
        container.html(html.join(''));
    }

    function callbackNewsList(data, args) {
        cache = data;
        buildNewsList(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsList });
    });
};


/********************************************************************************
builds archive news item
********************************************************************************/
CLK.newslistarchive = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsList(container) {
        var i = 0, html = [];

        html[html.length] = '<div class="news">';
        $(cache).find('entry').each(function() {
            if (i >= 4) {
                html[html.length] = '<div class="header2">';
                html[html.length] = $(this).find('title').text();
                html[html.length] = '</div>';
                html[html.length] = '<div class="date">';
                html[html.length] = CLK.tools.dateFromString($(this).find('updated').text());
                html[html.length] = '</div>';
                html[html.length] = '<div class="content">';
                html[html.length] = '<a href="';
                html[html.length] = $(this).find('link').attr('href');
                html[html.length] = '">';
                html[html.length] = 'Read more»';
                html[html.length] = '</a>';
                html[html.length] = '</div>';
            }
            i++;
        });
        html[html.length] = '</div>';
        container.html(html.join(''));
    }

    function callbackNewsList(data, args) {
        cache = data;
        buildNewsList(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsList });
    });
};

/********************************************************************************
builds news item
********************************************************************************/
CLK.newsitem = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsList(container) {
        var html = [], social = [];

		social[social.length] = '<div class="social-button"><a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical">Tweet</a></div>';
		social[social.length] = '<div class="social-button"><iframe src="http://www.facebook.com/plugins/like.php?app_id=260606583964946&amp;href&amp;send=false&amp;layout=box_count&amp;width=60&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=90" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:60px; height:90px;" allowTransparency="true"></iframe></div>';
		social[social.length] = '<div class="social-button"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-counter="top"></script></div>';
		social[social.length] = '<div class="social-button"><g:plusone size="tall"></g:plusone></div>';

		social[social.length] = '<div class="social-button"><a href="https://twitter.com/PWNTechnologies" class="twitter-follow-button">Follow @PWNTechnologies</a></div>';

		social[social.length] = '<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
		
		social[social.length] = '<script type="text/javascript"> (function() { var po = document.createElement("script"); po.type = "text/javascript"; po.async = true; po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s);  })();</script>';

        html[html.length] = '<div class="news">';
        $(cache).find('entry').each(function() {
            if (CLK.tools.query().id) {
                if (parseInt(CLK.tools.query().id, 10) === parseInt($(this).find('id').text().split(',')[1], 10)) {
					
					$(document).attr("title", $(this).find('title').text());
					
                    html[html.length] = '<div class="header1">';
                    html[html.length] = $(this).find('title').text();
                    html[html.length] = '</div>';
                    html[html.length] = '<div class="date">';
                    html[html.length] = CLK.tools.dateFromString($(this).find('updated').text());
                    html[html.length] = '</div>';
                    html[html.length] = '<div class="content">';
                    html[html.length] = $(this).find('content').text();
                    html[html.length] = '</div>';
                }
            }
        });
        html[html.length] = '</div>';
        container.html(html.join(''));
		$('#social-media', container).append(social.join(''));
    }

    function callbackNewsList(data, args) {
        cache = data;
        buildNewsList(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsList });
    });
};

/********************************************************************************
builds newsbanner
********************************************************************************/
CLK.newsbanner = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsBanner(container) {
        var i = 0, html = [];

        html[html.length] = '<ul id="newsscroll" class="news">';
        $(cache).find('entry').each(function() {
            if (i < 4) {
                html[html.length] = '<a href="' + $(this).find('link').attr('href') + '">';
                html[html.length] = '<span class="date">';
                html[html.length] = CLK.tools.dateFromString($(this).find('updated').text());
                html[html.length] = '</span> ';
                html[html.length] = $(this).find('title').text();
                html[html.length] = '</a>';
            }
            i++;
        });
        html[html.length] = '</ul>';
        container.html(html.join(''));
    }

    function callbackNewsBanner(data, args) {
        cache = data;
        buildNewsBanner(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsBanner });
    });

};

/********************************************************************************
builds features newsitem
********************************************************************************/
CLK.newsfeatured = function(elements, args) {

    var defaults, options, cache, container, summary;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    show = function() {
        var html = [];
        $(cache).find('entry[featured=true]').each(function() {
            html[html.length] = '<div class="h2">';
            html[html.length] = $(this).find('title').text();
            html[html.length] = '</div>';
            html[html.length] = '<p class="content">';

			/*
            summary = $(this).find('summary').text();
            if (summary.length > 95) {
                summary = summary.substring(0, 95) + '...';
            }
			*/

            html[html.length] = summary;
            html[html.length] = ' ';
            html[html.length] = '<a href="';
            html[html.length] = $(this).find('link').attr('href');
            html[html.length] = '">';
            html[html.length] = 'continue»';
            html[html.length] = '</a>';
            html[html.length] = '</p>';
        });
        container.html(html.join(''));
    }

    function callbackLatestNews(data, args) {
        cache = data;
        container = args.container;
        show();
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackLatestNews });
    });
};

/********************************************************************************
builds newsshorlist
********************************************************************************/
CLK.newsshortlist = function(elements, args) {

    var cache, defaults, options;

    defaults = {
        debugging: false,
        theme: ''
    };
    options = $.extend({}, defaults, args);

    cache = {};

    function buildNewsList(container) {
        var i = 0, html = [];

        html[html.length] = '<div class="news">';
        $(cache).find('entry').each(function() {
            if (i < 3) {
                html[html.length] = '<div class="divider">';
                html[html.length] = '<a href="';
                html[html.length] = $(this).find('link').attr('href');
                html[html.length] = '">';
                html[html.length] = $(this).find('title').text();
                html[html.length] = '</a>';
                html[html.length] = '</div>';
            }
            i++;
        });
        html[html.length] = '</div>';
        container.html(html.join(''));
    }

    function callbackNewsList(data, args) {
        cache = data;
        buildNewsList(args.container);
    }

    return elements.each(function() {
        CLK.services.newslist({ container: $(this), callback: callbackNewsList });
    });
};

/********************************************************************************
random photos
********************************************************************************/
$.fn.showphotos = function(options) {
    var me = this;

    showphoto = function() {
		var seen = '';
        me.each(function() {
            var group = 0, photo = '', groups = [
				[7,29,74,81,82,67,15,43,86,87], // 1 - toepassing
				[57,58,37,38,39,40,41,42,43,44,45,46,19,20,21,22,23,24,25,26,56,91], // 2 - perfector-e
				[1,61,62,63,64,65,66,67,68,69,84,85,88,89,90], // 3 - perfector-p+r
				[5,14,49,52,53,28], // 4 - membranen
				[30,31,59,4,32,60,33,34,35,36,8,9,10,70,71,72,73,75,76,77,50,51,79,80,27,55,83], // 5 - techniek
				[8,9,10,71,73,18,76,75,78], // 6 - six
				[13,14,52,53,27,28,35,34,72,77], // 7 - integrated
				[72,77] // 8 - ceramac
			];
            group = $(this).attr('group');
			do {
            	photo = groups[group - 1][Math.floor(Math.random() * groups[group - 1].length)];
			}
			while (seen.indexOf('|' + photo + '|') > -1);
			seen = seen + '|' + photo + '|';
            $(this).fadeOut('slow', function() { $(this).html('<img src="' + CLK.root + '/resources/photos/thumbs/' + (photo < 10 ? '0' + photo : photo) + '.jpg" width="250" height="170"/>'); $(this).fadeIn(); });
        });
    }

    showphoto();
    setInterval('showphoto()', 8000);
}

/********************************************************************************
droppy
********************************************************************************/
$.fn.droppy = function(options) {

    options = $.extend({ speed: 250 }, options || {});

    this.each(function() {

        var root = this, zIndex = 1000;

        function getSubnav(ele) {
            if (ele.nodeName.toLowerCase() == 'li') {
                var subnav = $('> ul', ele);
                return subnav.length ? subnav[0] : null;
            } else {
                return ele;
            }
        }

        function getActuator(ele) {
            if (ele.nodeName.toLowerCase() == 'ul') {
                return $(ele).parents('li')[0];
            } else {
                return ele;
            }
        }

        function hide() {
            var subnav = getSubnav(this);
            if (!subnav) return;
            $.data(subnav, 'cancelHide', false);
            setTimeout(function() {
                if (!$.data(subnav, 'cancelHide')) {
                    $(subnav).slideUp(options.speed);
                }
            }, 50);
        }

        function show() {
            var subnav = getSubnav(this);
            if (!subnav) return;
            $.data(subnav, 'cancelHide', true);
            $(subnav).css({ zIndex: zIndex++ }).slideDown(options.speed);
            if (this.nodeName.toLowerCase() == 'ul') {
                var li = getActuator(this);
                $(li).addClass('hover');
                $('> a', li).addClass('hover');
            }
        }

        $('ul, li', this).hover(show, hide);
        $('li', this).hover(
            function() { $(this).addClass('hover'); $('> a', this).addClass('hover'); },
            function() { $(this).removeClass('hover'); $('> a', this).removeClass('hover'); }
        );
    });
}

/********************************************************************************
scroll
********************************************************************************/
$.fn.scroll = function(settings) {
    settings = jQuery.extend({
        travelocity: 0.08
    }, settings);
    return this.each(function() {
        var $strip = jQuery(this);
        $strip.addClass("newsticker")
        var stripWidth = 3000;
        var $mask = $strip.wrap("<div class='mask'></div>");
        var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
        var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width 	
        $strip.find("li").each(function(i) {
            stripWidth += jQuery(this, i).width();
        });
        $strip.width(stripWidth);
        var totalTravel = stripWidth + containerWidth;
        var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye		
        function scrollnews(spazio, tempo) {
            $strip.animate({ left: '-=' + spazio }, tempo, "linear", function() { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
        }
        scrollnews(totalTravel, defTiming);
        $strip.hover(function() {
            jQuery(this).stop();
        },
        function() {
            var offset = jQuery(this).offset();
            var residualSpace = offset.left + stripWidth;
            var residualTime = residualSpace / settings.travelocity;
            scrollnews(residualSpace, residualTime);
        });
    });
};

/********************************************************************************
facebook
********************************************************************************/
(function($){

	$.fn.facebookWall = function(options){
		
		options = options || {};
		
		if(!options.id){
			throw new Error('You need to provide an user/page id!');
		}
		
		if(!options.access_token){
			throw new Error('You need to provide an access token!');
		}
		
		// Default options of the plugin:
		
		options = $.extend({
			limit: 3	// You can also pass a custom limit as a parameter.
		},options);

		// Putting together the Facebook Graph API URLs:

		var graphUSER = 'https://graph.facebook.com/'+options.id+'/?fields=name,picture&access_token='+options.access_token+'&callback=?',
			graphPOSTS = 'https://graph.facebook.com/'+options.id+'/posts/?access_token='+options.access_token+'&callback=?&date_format=U&limit='+options.limit;
		
		var wall = this;
		
		$.when($.getJSON(graphUSER),$.getJSON(graphPOSTS)).done(function(user,posts){
			
			// user[0] contains information about the user (name and picture);
			// posts[0].data is an array with wall posts;
			
			var fb = {
				user : user[0],
				posts : []
			};

			$.each(posts[0].data,function(){
				
				// We only show links and statuses from the posts feed:
				if((this.type != 'link' && this.type!='status') || !this.message){
					return true;
				}

				// Copying the user avatar to each post, so it is
				// easier to generate the templates:
				this.from.picture = fb.user.picture;
				
				// Converting the created_time (a UNIX timestamp) to
				// a relative time offset (e.g. 5 minutes ago):
				this.created_time = relativeTime(this.created_time*1000);
				
				// Converting URL strings to actual hyperlinks:
				this.message = urlHyperlinks(this.message);

				fb.posts.push(this);
			});
			
			// Creating an unordered list for the posts:
			var ul = $('<ul>').appendTo(wall);
			
			// Generating the feed template and appending:
			$('#feed').tmpl(fb.posts).appendTo(ul);
		});
		
		return this;

	};

	// Helper functions:

	function urlHyperlinks(str){
		return str.replace(/\b((http|https):\/\/\S+)/g,'<a href="$1" target="_blank">$1</a>');
	}

	function relativeTime(time){
		
		// Adapted from James Herdman's http://bit.ly/e5Jnxe
		
		var period = new Date(time);
		var delta = new Date() - period;

		if (delta <= 10000) {	// Less than 10 seconds ago
			return 'Just now';
		}
		
		var units = null;
		
		var conversions = {
			millisecond: 1,		// ms -> ms
			second: 1000,		// ms -> sec
			minute: 60,			// sec -> min
			hour: 60,			// min -> hour
			day: 24,			// hour -> day
			month: 30,			// day -> month (roughly)
			year: 12			// month -> year
		};
		
		for (var key in conversions) {
			if (delta < conversions[key]) {
				break;
			}
			else {
				units = key;
				delta = delta / conversions[key];
			}
		}
		
		// Pluralize if necessary:
		
		delta = Math.floor(delta);
		if (delta !== 1) { units += 's'; }
		return [delta, units, "ago"].join(' ');
		
	}
	
})(jQuery);


/********************************************************************************
document ready
********************************************************************************/

$(document).ready(function() {
    $('#nav').droppy();
    $('.randomphotos').showphotos();
    $('#solutions a:first').click(function(e) { e.preventDefault(); });
    $('#resources a:first').click(function(e) { e.preventDefault(); });
    $('#careers a:first').click(function(e) { e.preventDefault(); });
    $('#about-us a:first').click(function(e) { e.preventDefault(); });
});

