/*jslint bitwise: true, browser: true, eqeqeq: true, onevar: true, plusplus: true */ 
/*global jQuery, urchinTracker */
var cookieCutter, top_ads, get_top_ads_by_category, get_top_ads_by_search_terms, activate_short_list, loadShortlist, clearShortlist;
var DEBUG = 0;
/*************************
 * Use http://jslint.com *
 *************************/


/*******************
 * Deal with cookies
 */
cookieCutter = function () {
    var getCookie, setCookie, expires;
    
    getCookie = function (key){
	var ck, i, j;
    if (DEBUG) alert("get_cookie for Key="+ key);
	ck = document.cookie;
	if (typeof(ck) === "undefined"){
        if (DEBUG) alert("No cookie found.");
	    return "";
	}
	if (DEBUG) alert("cookie="+ ck);

	i = ck.indexOf(key + "=");
	j = ck.indexOf(";", i);
    if (DEBUG) alert("indexOf("+ key +"=)="+ i);
    if (DEBUG) alert("indexOf(';', "+ i +")="+ j);
    
	if (i < 0) {
        if (DEBUG) alert("negative i="+ i);
	    return "";
	}
	
	if (j < 0) {
	    return ck.substring(i + key.length + 1);
	} else {
	    return ck.substring(i + key.length + 1, j);
	}
    };

    expires = function (d){
	var expiry = new Date();
	expiry.setTime (expiry.getTime() + d);
	return "; expires=" + expiry.toGMTString();
    };
    
    setCookie = function (key, value){
	if (value.length === 0){
	    document.cookie = key + "=" + expires(-1) + ";path=/;domain="+cookieCutter.domain;
	} else {
	    document.cookie = key + "=" + value + expires(365*24*60*60*1000) + ";path=/;domain=" + cookieCutter.domain;
	}
    };
 
    return {
	get: getCookie,
	set: setCookie,
	domain: undefined
    };
}();

/*********************
 * Handle display file input on replace radio button selected (in edit posting)
 */
(function () {
    var showFileInput = function () {
        var element_id   = this.id;
        var image_number = element_id.match(/image_(\d)_action_3/)[1];
        jQuery('#replace_image_' + image_number + ':file').slideDown();
    }
    
    var hideFileInput  = function () {
        var element_id   = this.id;
        var image_number = element_id.match(/image_(\d)_action_\d/)[1];
        jQuery('#replace_image_' + image_number + ':file').slideUp();
    }
    
    var determineInitVisibility = function () {
        var image_number = this.id.match(/replace_image_(\d)/)[1];
        if( !$('#image_' + image_number + '_action_3' ).is(':checked') ) {
            $(this).hide();
        }
    }
    
    jQuery(document).ready(function() {
        jQuery('[id^="replace_image_"]:file').each( determineInitVisibility );
        jQuery('[id$="_action_1"]:input').bind( 'click', hideFileInput ); 
        jQuery('[id$="_action_2"]:input').bind( 'click', hideFileInput ); 
        jQuery('[id$="_action_3"]:input').bind( 'click', showFileInput ); 
    });
 }());

/*********************
 * Handle image toggle
 */
(function () {
    var toggleImages, toggleImagesHandle;
    toggleImages = function (el) {
	var hideImages = (el.checked) ? '' : 'true';
	cookieCutter.set('listing_no_thumbs', hideImages);
	window.location.reload(true);
    };
    toggleImagesHandle = function () {
	var input;
	input = this;
	/* Internet Explorer can't time events on checkboxes correctly
	   This adds a delay so it can set its .checked property
	   before we try to read it */
	setTimeout(function () {
		toggleImages(input);
	    }, 800);
    };
    jQuery(document).ready(function() {
	jQuery('#listings-show-images').bind('change', toggleImagesHandle);
    });
}());


/*******************************
 * Handle search form posting id 
 */
(function () {
    var search_by_id = function () {
	document.location = this.href + '?posting_id=' + parseInt(document.forms.search.elements.search_terms.value, 10);
    };
    jQuery(document).ready(function (){
	jQuery('#search-by-id').click(search_by_id);
    });
}());

/*************************************
 * Handle thumbnails on listings pages 
 */

(function () {
    var expand_thumbnail = function () {
	document.images.mainImage.src = this.href; 
	return false;
    };
    jQuery(document).ready(function (){
	jQuery('.thumbnails a').click(expand_thumbnail);
    });
}());

/*************************************
 * Handle thumbnails on advert page
 */

(function () {
    var expand_thumbnail = function () {
	document.images.mainImage.src = this.href; 
	return false;
    };
    jQuery(document).ready(function (){
	jQuery('#thumbs a').click(expand_thumbnail);
    });
}());

/*************************
 * Handle Google Analytics 
 */
(function () {
    var link_tracking, get_urchin, track_link, i;
    link_tracking = [
		     { 
			 pattern: '.add-post a',
			 code: 'listing_post_new_click'
		     },
		     { 
			 pattern: '#also-in-this-category a',
			 code: 'similar_ads_click'
		     }
		     ];
    get_urchin = function (code) {
	return function () {
	    urchinTracker(code);
	};
    };
    track_link = function (data) {
	jQuery(data.pattern).click(get_urchin(data.code));
    };
    jQuery(document).ready(function (){
	for (i = 0; i < link_tracking.length; i = i + 1) {
	    track_link(link_tracking[i]);
        }
    });
}());

/*******************
 * Handle Short List
 */
activate_short_list = function () {
    var star, MAX_STARS, starCount, cookieName, add, remove, starSwitch, displayStarCount, shortlist, handler, add_short_list;
    
    star = {
	on: {
	    r: /_on/,
	    s: "_on"
	},
	off: {
	    r: /_off/,
	    s: "_off"
	}
    };

    MAX_STARS  = 100;
    starCount  = 0;

    add = function (postingID) {
        var s;
        if (starCount < MAX_STARS){
            s = cookieCutter.get(cookieName);
            cookieCutter.set(cookieName, s + '_' + postingID);
            starCount = starCount + 1;
            if (DEBUG) alert("added postingID:"+ postingID +"\nstar count:"+ starCount);
        }
    };

    remove = function (postingID) {
        var s, pos, pos2;
        s = cookieCutter.get(cookieName);
        pos = s.indexOf('_'+postingID);
        if (pos >=0 ){
            pos2 = pos + ('_'+postingID).length;
            s = s.substring(0, pos) + s.substring(pos2,s.length);
            cookieCutter.set(cookieName, s);
        }
        starCount = starCount - 1;
        if (DEBUG) alert("remove postingID:"+ postingID +"\nstar count:"+ starCount);
    };

    clearShortlist = function () {
        cookieCutter.set(cookieName, '');
        starCount=0;
        displayStarCount();
    };

    displayStarCount = function (){
        var i, t, m;
        t = document.getElementById("starcount");
        if (t) { 
            t.innerHTML = starCount;
            if (DEBUG) alert("display starcount="+ starCount);
        }
    };

    shortlist = function () {
        var postingID = this.className.match(/(^| )sl_([0-9]+)($| )/)[2];
        if (DEBUG) alert ("Got postingID="+ postingID);
        
        var isfav_class = new RegExp("(^| )isfav($| )");
        if (isfav_class.test(this.className)) {
            remove(postingID);
            jQuery(this).removeClass('isfav');
        } else {
            add(postingID);
            jQuery(this).addClass('isfav');
        }
        
        displayStarCount();
        return false;
    };

    loadShortlist = function (domain, siteID) {
        var s, starArray, id, img;

        if (DEBUG) alert("start loadshortlist...");
        cookieCutter.domain = domain;
        cookieName = "stars"+ siteID;
        s = cookieCutter.get(cookieName);
        if (DEBUG) alert("get cookie='"+ cookieName +"'\nDomain='"+ domain +"'\nReturned cookie='"+ s +"'");
        starArray = s.split("_");
        if (starArray.length > 0){
            starCount = starArray.length - 1;
        }
        displayStarCount();
    };

    add_short_list = function() {
        if (DEBUG) alert("add_short_list");
        jQuery('a.fav').click(shortlist);
    };

    jQuery(document).ready(add_short_list);

    return add_short_list;

}();

/*************************
 * Handle top ads
 */

top_ads = function () {
    var p, inject_top_ad, get_top_ads_by_category, get_top_ads_by_search_terms, handle_posting_ads, collect_ad_ids, no_top_ads, timer;
    
    p = 0;

    no_top_ads = function() {
        timer.end("Failed to get top ads");
    };

    inject_top_ad = function ( i, posting_id , ad_html_block ) {
		jQuery('#top_ads_block_' + i ).append(ad_html_block).show();
		activate_short_list();
    } ;

    handle_posting_ads = function (posting_ads) {
	var posting_id, i, url, insert_ad;
	
        posting_id = posting_ads.pop();
    
	if ( posting_id > 0 ) {
	    i = p;
	    p = p + 1;

	    url = "/top_ads/post_" + posting_id + ".ajax";

	    insert_ad = function (data, textStatus) {
                timer.checkpoint("Ad inserted");
	        jQuery(document).ready( function () {inject_top_ad(i, posting_id, data)});
	        if (posting_ads.length) {
	            handle_posting_ads(posting_ads);
	        } else {
		   activate_short_list();
                   timer.end("All ads inserted");
		}
	    };

            jQuery.ajax({
                         url: url,
                         data: {},
                         success: insert_ad,
                         error: no_top_ads,
                        });
	    
        } else {
            timer.end("All ads inserted");
            if (p === 0) {
                //jQuery("#topads_section_def_text").show();
            };
        }
    };

    collect_ad_ids = function (data, textStatus) {
        timer.checkpoint("Collecting ads");

        var posting_ids = data.split(",");
        if (posting_ids.length) {
            timer.checkpoint(posting_ids.length + " ads to collect");
	    handle_posting_ads(posting_ids);
        } else {
            timer.end("No ads to collect");
        };

        if (p > 0) {
	    jQuery(document).ready( function () {jQuery('#topads_section_def_text').remove();});
        } else {
	    jQuery(document).ready( function () {jQuery('#topads_section_def_text').show();});
        }
    
    };

    get_top_ads_by_category = function ( site_category_id, query_string ) {
	var url;

        DummyMetrics();

        url = "/top_ads/category_" + site_category_id + ".ajax";
	if (query_string) {
		url = url + query_string;
	}
        timer = new metrics.Timer('TopAdsByCategory');
        $.ajax({
                type: "GET",
                url: url,
                success: collect_ad_ids,
                error: no_top_ads
            });
    };

    get_top_ads_by_search_terms = function ( site_category_id, query_string ) {
        var url;

        DummyMetrics();
    
        url = "/top_ads/search.ajax";
        if (query_string) {
	    url = url + query_string;
        }
    
        if (site_category_id) {
	    url = url + '&site_category_id=' + site_category_id;
        }

        timer = new metrics.Timer('TopAdsBySearchTerms');
        $.ajax({
                type: "GET",
                url: url,
                success: collect_ad_ids,
                error: no_top_ads
            });
    };
    
    return {
	get_top_ads_by_category: get_top_ads_by_category,
	get_top_ads_by_search_terms: get_top_ads_by_search_terms
    };
}();

/* Compatibility Mode - deprecated, ensure these aren't called from anywhere
 * then remove
 */
get_top_ads_by_category = top_ads.get_top_ads_by_category;
get_top_ads_by_search_terms = top_ads.get_top_ads_by_search_terms;


/*************************
 * Handle modal dialogs (light boxes)
 */


(function () {
    var createDialog, populateDialog, activateDialog, handler, init, after_loading;

    createDialog = function () {
        var d = document.createElement('div');
        d.style.display = 'none';
        d.setAttribute("class", "modal_dialog");
        document.body.appendChild(d);
        return d;
    };

    populateDialog = function (d,uri,callback) {
        jQuery(d).load(uri, {}, callback);
    }

    activateDialog = function (d) {

        // default size;
        var h = '500';
        var w = '790';


        // window size for service boxes;
        if ( jQuery('div.servicebox', d).size() > 0) {
            w = '400';
            h = '400';
        }

        // set window size for region selector service box;
        if ( jQuery('div#regionlayover', d).size() > 0 ) {
            h = '570';
            w = '790';
        }

        // set window size for topads service box;
        if ( jQuery('div#topad_service_box', d).size() > 0 ) {
            h = '450';
        }

        // set window size for topads service box;
        if ( jQuery('div#reportad', d).size() > 0 ) {
            h = '460';
        }

        jQuery(d).dialog({
            'modal': true,
            'height': h+"px",
            'width': w+"px",
            'close': function(event, ui) { jQuery('.modal_dialog', document).empty(); },
            'overlay': {
                'opacity': 0.5,
                'background': "black"
            }
        });
        jQuery('div.close a#TB_closeWindowButton',
               jQuery(d)).bind('click', function(e){
                       e.stopPropagation();
                       e.preventDefault();
                       $('div').dialog( 'destroy' );
                       /* jQuery(d).dialog("close"); $('.modal_dialog', document).empty();*/
                   });
    };

    after_loading = function (target) {
        return function () {
            target.style.display = 'block';
            target.style.background = 'white';
            activateDialog(target);
        };
    };

    handler = function () {
//     alert(jQuery('.modal_dialog').size());
        jQuery('.modal_dialog').remove();
        var uri, element, target;

        element = this;
        uri = element.href + '&modal=1&rand='+Math.round(Math.random()*1000);

        target = createDialog();
        populateDialog(target, uri, after_loading(target));

        return false;
    };

    init = function () {
        jQuery('a.modal').click(handler);
    };

    jQuery(document).ready(init);

}());


// $('document').ready (
//
//
// );

function toggleCF(id, img_id) {
	$("#" + id).toggle("slow");
	
	if('/images/collapse.gif' == $('#' + img_id).attr('src')) {
		$('#' + img_id).attr('src' , '/images/expand.gif');
	} else {
		$('#' + img_id).attr('src' , '/images/collapse.gif');
	}
};

function UserListCheckAll () {
	$("input[type='checkbox']").attr('checked', 'true');
	return false;
}

function UserListUnCheckAll () {
	$("input[type='checkbox']").removeAttr('checked');
	return false;
}

/*************************
 * Handle select text in input box on user select or focus (view posting page)
 */
 (function () {
    var select_input = function(){
        // Select input field content
        this.select();
    };
    jQuery(document).ready(function(){
        $("#postinglink").click(select_input);
    });
}());

// Create a dummy metrics object if metrics are disabled, or couldn't be loaded for some reason.
function DummyMetrics() {
    if (!('metrics' in window)) {
        window.metrics = {
            lock: function() {},
            unlock: function() {},
            checkpoint: function() {},
            ready: function() {},
            load: function() {},
            Timer: function() { return metrics; },
            end: function() {}
        }
    }
}

$(document).ready(DummyMetrics);

/*
  Region links should be redirected to the relevant region

  We do this in JS rather than HTML because there's no search-engine-neutral way of telling bots to index the parameter-free URL.

  "nrk" stands for "navigation region key", as opposed to the URL region key we normally use.
 */
function handle_regional_links(target) {
    // Some regional links have one child, none have deeper nesting at the time of writing
    target = ( 'A' == target.target.nodeName ) ? target.target : target.target.parentNode;

    if (
        'A' == target.nodeName &&
        -1 != target.className.search(/(^|\s)regional_link($|\s)/) &&
        'http://' == target.href.substr(0, 7) &&
        -1 == target.href.search(/[&?]nrk=/) // the regional_link class *should* be removed when 'nrk=' is added, but better to have and not need...
        ) {

        target.className = target.className.replace(/(^|\s)regional_link($|\s)/, "$1$2");

        var hash = target.href.search('#'), region = document.getElementById('x-slando-region').content;
        if ( -1 == hash ) {
            target.href += [
                            (-1==target.href.search('\\?')
                             ?'?'
                             :'&'),
                            'nrk=',
                            region,
                            ].join('');
        } else {
            var href = target.href.substr(0, hash);
            target.href = [
                           href,
                           (-1==href.search('\\?')
                            ?'?'
                            :'&'),
                           'nrk=',
                           region,
                           target.href.substr(hash)
                           ].join('');

        };
    };
}

// Ensure the element is processed at the right time...
// Populate when the user hovers over the link
$(document).mouseover(handle_regional_links);
// Populate if the user somehow clicks without hovering (e.g. keyboard navigation)
// Note: IE doesn't generate a 'click' event when it opens a window in a new tab
$(document).click(handle_regional_links);

