
// remap jQuery to $
(function($){
})(this.jQuery);



// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};



// catch all document.write() calls
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);





// form-filler.js
(function($)
{

    $.fn.FillForm = function()
    {
        return this.each( function()
        {
            if (this.tagName == 'FORM')
            {
                $(this).find('*').FillFormElements();

                $(this).submit( function()
                {
                    $(this).find('*').each( function()
                    {

                        if ( this.tagName == 'INPUT' && $(this).attr('type') == 'text' )
                        {

                            if ( $(this).attr('title') && this.value == $(this).attr('title'))
                            {
                                this.value = '';
                                $(this).removeClass('auto-filled');
                            }
                        }

                    });
                });
            }
        });
    };
    
    $.fn.FillFormElements = function()
    {
        return this.each( function()
        {
            if ( this.tagName == 'INPUT' && $(this).attr('type') == 'text' )
            {

                if ( $(this).attr('title') && this.value == '' )
                {

                    $(this).addClass('auto-filled');
                    this.value = $(this).attr('title');
                    $(this).focus( function()
                    {
                        this.value = "";
                        $(this).removeClass('auto-filled');
                        $(this).unbind('focus');
                    });
                }
            }

        });
    };
    
})(jQuery); // pass the jQuery object to this function






$.bookmark = function () {
    var isIEmac = false;
    var isMSIE  = (-[1,]) ? false : true;
    var cjTitle = "Glam Thumbs - Free Porn Movies and Sex Videos";
    var cjHref  = location.href;

    function hotKeys() {
        var ua = navigator.userAgent.toLowerCase();
        var str = '';
        var isWebkit = (ua.indexOf('webkit') != - 1);
        var isMac = (ua.indexOf('mac') != - 1);

        if (ua.indexOf('konqueror') != - 1) {
            str = 'CTRL + B'; // Konqueror
        } else if (window.home || isWebkit || isIEmac || isMac) {
            str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
        }
        return ((str) ? 'Press ' + str + ' to bookmark this page.' : str);
    }

    function isIE8() {
        var rv = -1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
        }
        if (rv > - 1) {
            if (rv >= 8.0) {
                return true;
            }
        }
        return false;
    }

    function addBookmark(a) {
        try {
            if (typeof a == "object" && a.tagName.toLowerCase() == "a") {
                a.style.cursor = 'pointer';
                if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
                    window.sidebar.addPanel(cjTitle, cjHref, ""); // Gecko
                    return false;
                } else if (isMSIE && typeof window.external == "object") {
                    if (isIE8()) {
                        window.external.AddToFavoritesBar(cjHref, cjTitle); // IE 8
                    } else {
                        window.external.AddFavorite(cjHref, cjTitle); // IE <=7
                    }
                    return false;
                } else if (window.opera) {
                    a.href = cjHref;
                    a.title = cjTitle;
                    a.rel = 'sidebar'; // Opera 7+
                    return true;
                } else {
                    alert(hotKeys());
                }
            } else {
                throw "Error occured.\r\nNote, only A tagname is allowed!";
            }
        } catch (err) {
            alert(err);
        }

    }

    return {
        addBookmark : addBookmark
    }
}();







/*
  @author: remy sharp
  @info: http://leftlogic.com/lounge/articles/microformats_bookmarklet/
  @date: 2007-10-22
  @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
*/


$.mf = function(src, trg)
{

    $.mf.buildBox(trg);
    $.mf.import_microformat( 'vcard',  $.mf.hCard );
    $.mf.import_microformat( 'vevent', $.mf.hCalendar );
    $.mf.emptyCheck();
    $.mf.styles();
    if ($.mf.var.msie && $.mf.var.found) {
        $('#mf-box A').click( $.mf.ie_microformat );
    }


}

$.mf.var = {};
$.mf.var.jqe           = null;
$.mf.var.run_once      = 0;
$.mf.var.found         = 0;
$.mf.var.photoguid     = 0;
$.mf.var.photocomplete = [];
$.mf.var.nl            = '%0D%0A'; // %0D%0A = nl! yay!
$.mf.var.server        = location.protocol + '//' + location.hostname;
$.mf.var.msie          = /*@cc_on!@*/0;


$.mf.var.mf_logo     = $.mf.var.server + '/www/gfx/microformats.jpg';
$.mf.var.vcard_image = $.mf.var.server + '/www/gfx/vcards.gif';
$.mf.var.ical_image  = $.mf.var.server + '/www/gfx/ical.gif';



$.mf.buildBox = function(trg)
{
	$( trg ).append('<div id="mf-box"><div id="mf-microformats"></div></div>');
	if (!$.browser.safari) $('#mf-box').hide();
}


// only in a function to help manage the styles - IE needs them
// applied directly to the elements
$.mf.styles = function()
{
    $('#mf-box').show();
    $('#mf-box')               .css({ 'font-size': 'x-small' });;
    $('#mf-box div.mf-card')   .css({ 'margin': '5px', 'paddingBottom': '5px', 'borderBottom': '1px #ccc solid', 'paddingLeft': '25px' });
    $('#mf-box p.mf-header a') .css({ 'font-size': 'x-small' });
    $('#mf-box p.mf-header, \
       #mf-box p.mf-detail')   .css({ 'margin': '0'});
    $('#mf-box div.mf-vcard')  .css({ 'background': 'url(' + $.mf.var.vcard_image + ') no-repeat top left'});
	$('#mf-box div.mf-vevent') .css({ 'background': 'url(' + $.mf.var.ical_image + ') no-repeat top left' });
}



$.mf.hCard = function( hc )
{
	$.mf.var.found++; // flag we've got one
	
	var hCard = {}, keys = [], i, kv, n;

	keys = [
            'fn', 'n', 'org', 'title', 'role', 'note', 'family-name',
            'given-name', 'additional-name', 'honorific-prefix',
            'honorific-suffix', 'nickname', 'category', 'note'
    ];
    
	for ( i = 0; i < keys.length; i++ )
    {
	    kv = $('.' + keys[i], hc)
		if (kv.length)
        {
		    hCard[keys[i]] = $.mf.cleanString(kv[0].title ? kv[0].title : kv.text(), true);
		}
	}

	// collect adr manually
	if ($('.adr', hc).length) {
		keys = ['post-office-box', 'extended-address', 'street-address',
                'locality', 'region', 'postal-code', 'country-name'];

		for (i = 0; i < keys.length; i++) {
		    kv = $('.' + keys[i], hc);
			if ( kv.length ) hCard[keys[i]] = $.mf.cleanString( kv.text() );
			hCard.adr = 1;
		}
	}

	hCard.tel = {};
	$('.tel', hc).each( function()
    {
		var t = $('.type', this); // should also check the class of $(this)
		if (!t.length) t = $(this);


		if ( t.length && t.attr('title') )
        {
		    t = t.attr('title'); // non-standard...?
		}
        else if (t.text())
        {
		    t = t.text();
		}
        else
        {
		    t = 'Work';
		}


		var v = $('.value', this).text();
		
		if (!v) v = $(this).text();

		hCard.tel[t] = v;
	});

	// attribute based values
	if ( $('.url',   hc).length ) hCard.url   = $('.url',   hc).attr('href');
	if ( $('.email', hc).length ) hCard.email = $('.email', hc).attr('href');
	if ( $('.bday',  hc).length ) hCard.bday  = $('.bday',  hc).attr('title');

	// clean up
	if ( hCard.email) hCard.email = $.mf.cleanEmail( hCard.email );
	if ( hCard.url)   hCard.url   = $.mf.cleanURL( hCard.url );
	if ( hCard.note ) hCard.note  = hCard.note.replace(/\n/g, '\\n');
	
	var note = 'Source: ' + location.hostname;
	if (hCard.note)
    {
	    hCard.note += '\\n' + note;
	}
    else
    {
	    hCard.note = note;
	}

	if (!hCard.fn && hCard.org) hCard.fn = hCard.org;

	/**
	* going against this - because if only fn is provided as 'Remy Sharp',
	* then n becomes 'Remy' which will be the only field I see in the contact
	* imported.  Therefore, copying the fn directly across.
	*/
	// http://microformats.org/wiki/hcard#Implied_.22n.22_Optimization
	if (!hCard.n) n = hCard.fn;

	this.log = function ()
    {
		console.log('hCard', hCard.fn, hCard.email, hCard.url, hCard.n);
	};

	this.show = function()
    {
	     // damn google maps for adding hCards with fns
	    if (!hCard.fn)
        {
	        $.mf.var.found--;
	        return;
	    }
	    
		var html = [];
        html.push( '<div class="mf-card mf-vcard">' );
        html.push( '<p class="mf-header"><a href="' );
        html.push( this.asDownload() );
        html.push( '" title="Add to address book">' );
        html.push( hCard.fn );
        html.push( '</a></p>' );
        
		if (hCard.email) html.push( '<p class="mf-detail">' + hCard.email + '</p>');
		if (hCard.url)   html.push( '<p class="mf-detail">' + hCard.url   + '</p>');
		if (hCard.org)   html.push( '<p class="mf-detail">' + hCard.org   + '</p>');
		
		html.push( '</div>' );
		
		$('#mf-microformats').append( html.join('') );
	};

	this.asDownload = function()
    {
	    var keys = [], i, parts;
		var vcard = 'data:text/vcard;utf-8,BEGIN:VCARD' + $.mf.var.nl;

		if (hCard['family-name']) hCard.n = hCard['family-name'];
		if (hCard['given-name'])
        {
			if (hCard.n) hCard.n += ';';
			hCard.n += hCard['given-name'];
		}

		if (hCard.adr)
        {
			keys = ['post-office-box', 'extended-address', 'street-address',
                    'locality', 'region', 'postal-code', 'country-name'];
			hCard.adr = '';
			for (i = 0; i < keys.length; i++)
            {
				if (hCard[keys[i]])
                {
					hCard.adr += hCard[keys[i]];
				}
				hCard.adr += ';';
			}
		}

		if (!hCard.n)
        {
			if (!hCard.n && hCard.fn && (hCard.fn.split(' ').length == 2))
            {
				parts = hCard.fn.split(' ');
				parts = parts.reverse();
				hCard.n = parts.join(';');
			}
		}

		keys = ['fn', 'n' , 'org', 'title', 'role', 'note', 'nickname',
                'adr', 'email', 'photo', 'url', 'bday'];
		for (i = 0; i < keys.length; i++)
        {
			if (hCard[keys[i]]) vcard += keys[i].toUpperCase() + ':' + encodeURIComponent(hCard[keys[i]]) + $.mf.var.nl;
		}

		for (i in hCard.tel)
        {
			vcard += 'TEL;' + i.toUpperCase() + ':' + hCard.tel[i] + $.mf.var.nl;
		}

		vcard += 'END:VCARD';
		return vcard;
	};

	return this;
};

$.mf.hCalendar = function(ve)
{
	$.mf.var.found++;
	var hCal = {}, keys = [], i, kv;

	keys = ['summary', 'location', 'description', 'attendee', 'contact', 'organizer'] ;
	for (i = 0; i < keys.length; i++) {
	    kv = $j('.' + keys[i], ve);
		if (kv.length) hCal[keys[i]] = cleanString(kv.text(), true);
	}

	// collect adr manually
	if ($j('.adr', ve).length) {
		keys = ['post-office-box', 'extended-address', 'street-address', 'locality', 'region', 'postal-code', 'country-name'];
		for (i = 0; i < keys.length; i++) {
            kv = $j('.' + keys[i], ve);
			if (kv.length) hCal[keys[i]] = cleanString(kv.text());
			hCal.adr = 1;
		}
	}

	keys = ['dtstart', 'dtend', 'duration'];
	for (i = 0; i < keys.length; i++) {
	    kv = $j('.' + keys[i], ve);
		if (kv.length) hCal[keys[i]] = kv.attr('title');
	}

	// how wasteful am I?!
	if (hCal.dtstart) hCal.dtstart_raw     = new cleanDateTime(hCal.dtstart);
	if (hCal.dtstart_raw) hCal.dtstart     = hCal.dtstart_raw.formatted();
	if (hCal.dtstart_raw) hCal.dtstart_str = hCal.dtstart_raw.toString();
	if (hCal.dtend) hCal.dtend_raw         = new cleanDateTime(hCal.dtend);
	if (hCal.dtend_raw) hCal.dtend         = hCal.dtend_raw.formatted();
	if (hCal.dtend_raw) hCal.dtend_str     = hCal.dtend_raw.toString();

	if ($j('.url', ve).length) hCal.url = $j('.url', ve).attr('href');
	if (hCal.url) hCal.url = cleanURL(hCal.url);

	if (hCal.description) hCal.description = hCal.description.replace(/\n/g, '\\n');

	var note = 'Source: ' + location.hostname;
	if (hCal.description) hCal.description += '\n' + note;
	else hCal.description = note;

	this.show = function() {
		var html = '<div class="MF_card MF_vevent">';
		html += '<p class="MF_header"><a href="' + this.vCalendar() + '" title="Add to calendar">' + hCal.summary + '</a></p>';
		if (hCal.location) html += '<p class="MF_detail">' + hCal.location + '</p>';
		if (hCal.dtstart) html += '<p class="MF_detail">' + hCal.dtstart_str + '</p>';

		html += '</div>';
		$j('#MF_microformats').append(html);
	};

	this.vCalendar = function() {
	    var keys = [], i;
		var vcal = 'data:text/calendar;utf-8,';
		vcal += 'BEGIN:VCALENDAR' + nl + 'VERSION:2.0' + nl + 'BEGIN:VEVENT' + nl;

		if (hCal.adr) {
			keys = ['post-office-box', 'extended-address', 'street-address', 'locality', 'region', 'postal-code', 'country-name'];
			hCal.location = '';
			for (i = 0; i < keys.length; i++) {
				if (hCal[keys[i]]) {
					if (keys[i] == 'locality') hCal.location += '\n';
					hCal.location += hCal[keys[i]] + ' ';
				}
			}
		}

		keys = ['summary', 'location', 'description', 'attendee', 'contact', 'organizer', 'dtstart', 'dtend', 'duration', 'note'];

		for (i = 0; i < keys.length; i++) {
			if (hCal[keys[i]]) vcal += keys[i].toUpperCase() + ':' + encodeURIComponent(hCal[keys[i]]) + nl;
		}

		vcal += 'END:VEVENT' + nl + 'END:VCALENDAR';
		return vcal;
	};

	return this;
};

$.mf.cleanEmail = function(e)
{
	e = e.replace('mailto:', '');
	return e.replace(/\?.*$j/, '');
}

$.mf.cleanURL = function(u)
{
	if (!u.match(/^http/)) {
		if (u.match(/^\//))	u = location.protocol + '//' + location.hostname + u;
		else {
			var parts = location.pathname.split('/');
			parts.pop();
			var p = parts.join('/');
			u = location.protocol + '//' + location.hostname + p + '/' + u;
		}
	}
	return u;
}

$.mf.cleanString = function(s, stripNL)
{
	s = s.replace(/^\s+/, '');
	s = s.replace(/\s+$j/, '');
	s = s.replace(/( )+/g, ' ');
	return stripNL ? s.replace(/\n/g, ' ') : s.replace(/\n/g, '\\n'); // plain text!
}

$.mf.emptyCheck = function()
{
	if (!$.mf.var.found) {
		var html = '<div class="mf-card">';
		html += '<p class="mf-header">No microformats could be found.</p>';
		html += '</div>';
		$('#mf-microformats').append(html);
	}
}

$.mf.ie_microformat = function()
 {
    // context is A element
    var f = null;
    f = document.getElementById('_mf_iframe');
    if (f) {
        document.body.removeChild(f);
    }
    f = document.createElement('iframe');
    f.style.position = 'absolute';
    f.style.left = '-1000px';
    f.style.width = '10px';
    f.id = "_mf_iframe";
    document.body.appendChild(f);
    // should I recollect?
    f = document.getElementById('_mf_iframe');
    f.src = server + '/save-microformats.html?' + this.href.substr(this.href.indexOf('BEGIN')) + '#' + this.innerHTML;
    return false;
}

$.mf.cleanDateTime = function(t) {
	// 20060913T1400-0700
	// 2006-09-13T14:00-07:00

	var pad = function(s) {
		if (s.length == 1) s = '0' + s;
		return s;
	};

	var num = function(str, s, e) {
		return parseInt(str.substr(s, e), 10);
	};

	// strip formatting - currently doesn't support 2006-W05
	var endpos = t.indexOf('T');
	if (endpos == -1) endpos = t.length;

	var dstr = t.substr(0, endpos).replace(/\-/g, '');
	var tstr;

	if (endpos != t.length) tstr = t.substr(endpos+1).replace(/:/g, '');
	else tstr = '1200';

	t = dstr + 'T' + tstr;

	var d = new Date();
	d.setFullYear(num(dstr, 0, 4), num(dstr, 4, 2) - 1, num(dstr, 6, 2));
	d.setHours(num(t, 9, 2), num(t, 11, 2), 0); //  + offset
	var m = d.getMilliseconds();

	var offset = num(t, 14, 2) * 60 + num(t, 16, 2); // damn this is noddy.
	if (isNaN(offset) == false) {
		if (t.substr(13, 1) != '-') offset *= -1;
		m = m + (offset * 60 * 1000);
	}

	d.setMilliseconds(m);

	this.formatted = function(){
		var s = d.getFullYear().toString();
		s += pad((d.getMonth()+1).toString());
		s += pad(d.getDate().toString()) + 'T';
		s += pad(d.getHours().toString());
		s += pad(d.getMinutes().toString());
		s += pad(d.getSeconds().toString());
		if (offset) s += 'Z';
		return s;
	};

	this.toString = function() {
		return d.toString();
	};

	return this;
};

$.mf.import_microformat = function(type, method, context)
{
    if (!context) context = document;
    $('.' + type, context).each( function(){ method(this).show(); });
    $('iframe', context).each(function () {
        try {
            var f = this.contentWindow.document || this.contentDocument;
            $.mf.import_microformat(type, method, f);
        } catch (e) {} // can't see inside the iframe - so skip it
    });
}




