/*global window, $, ajax, MAP, google, GLatLng */

var KROC = {};

function scrollDocumentUp() {
    var scroll_top = $(window).scrollTop(),
        new_scroll_top = 0;

    $(window).scrollTop(new_scroll_top);
    return scroll_top;
}

// these functions may be used in every other script

function getElement(id) {
    return document.getElementById(id);
}

var MKM = {};

// returns an array of DOM objects with class className
// className - class property of tags (eg: mandatory)
// where - DOM node, to start search from (can be null, then document is used)
// tagName - return only tags of this type (eg: input), can be null (for all tags)
MKM.getElementsByClass = function (className, where, tagName) {
    var matches = [],    // array for returned DOM nodes
        i = 0,           // loop counter
        j = 0,           // found element counter
        elements = null, // all descendants of where
        count = 0;       // number of the descendants

    if (!where) {
        where = document;
    }
    if (!tagName) {
        tagName = '*';
    }
    
    elements = where.getElementsByTagName(tagName);
    count = elements.length;
    for (i = 0; i < count; i += 1) {
        if (-1 !== elements[i].className.indexOf(className)) {
            matches[j] = elements[i];
            j += 1;
        }
    }
    return matches;
};

// return the value of the radio button that is checked
// return an empty string if none are checked
// return false if there are no radio buttons
MKM.getCheckedValue = function (radioObj) {
    if (!radioObj) {
        return false;
    }
    var radioLength = radioObj.length,
        i = 0;
    if (radioLength === undefined) {
        if (radioObj.checked) {
            return radioObj.value;
        } else {
            return '';
        }
    }
    for (i = 0; i < radioLength; i += 1) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return '';
};

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
MKM.setCheckedValue = function (radioObj, newValue) {
    if (!radioObj) {
        return;
    }
    var radioLength = radioObj.length,
        i = 0;
    if (radioLength === undefined) {
        radioObj.checked = (radioObj.value === newValue.toString());
        return;
    }
    for (i = 0; i < radioLength; i += 1) {
        radioObj[i].checked = false;
        if (radioObj[i].value === newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
};

// cross-browser event attacher
MKM.addEvent = function (obj, evType, fn) {
    var r = null;
    if (obj.addEventListener) {
        // false -> do not useCapture (cancel bubbling upward the DOM tree)
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent) {
        r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        return false;
    }
};


// check is an input node has any value set
MKM.isEmpty = function (node) {
    if (node.value === '') {
        return true;
    }
    return false;
};

// check a text input node if it's value is a valid email
MKM.isValidEmail = function (node) {
    if (-1 === node.value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) {
        return false;
    }
    return true;
};


// check a text input node, if it's value is a valid url
MKM.isValidUrl = function (node) {
    var r = new RegExp("^(ftp|http|https)://([a-zA-Z0-9-_]+[.])*[a-zA-Z0-9-_]+[.][a-zA-Z]{2,4}/?$", "i"),
        res = r.test(node.value);

    if (res) {
        return true;
    }
    return false;
};


// show validation error messages and focus on first unfilled required field
MKM.errorAfterFormCheck = function (form, input_name, error_msg) {
    if (-1 !== form[input_name].className.search('invalid')) {
        form[input_name].focus();
        window.alert(error_msg);
        return true;
    }
    return false;
};


// get window top left position
MKM.getWindowPosition = function () {
    var left = (window.screenX ? window.screenX : 0),
        top  = (window.screenY ? window.screenY : 0);
    return {'top': top, 'left': left};
};


// get x and y coordinates (cross-browser)
MKM.getPositions = function (obj) {
	var el = obj,
        left = 0,
        top = 0;
	do {
		left += el.offsetLeft || 0;
		top += el.offsetTop || 0;
		el = el.offsetParent;
	} while (el);
	return {'x': left, 'y': top};
};


// get window size (width and height)
// does not contain scrolled part of document
MKM.getWindowSize = function () {
    var myWidth = 0, myHeight = 0;
    if (typeof window.innerWidth === 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return {
        width: myWidth,
        height: myHeight
    };
};


// get document sizes
// it does contain scrollable part of document
MKM.getDocumentSizes = function () {
    var wh = MKM.getWindowSize(),
        xy = MKM.getScrollPositions(),
        w = 0,
        h = 0;

    if (document.body.clientHeight && document.documentElement.clientHeight) {
        w = Math.max(document.documentElement.clientWidth, document.body.clientWidth);
        h = Math.max(document.documentElement.clientHeight, document.body.clientHeight);
        return {
            width: w,
            height: h
        };
    }
    return {
        width: wh.width + xy.x,
        height: wh.height + xy.y
    };
};


// get scroll offsets
MKM.getScrollPositions = function () {
    var scrOfX = 0, scrOfY = 0;
    if (typeof window.pageYOffset === 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return {x: scrOfX, y: scrOfY};
};


// adds a classname to a Node (if not yet specified)
MKM.addClass = function (obj, className) {
    var oldClasses = obj.className,
        classes = oldClasses.split(' '),
        count = classes.length,
        hadClass = false,
        i = 0;

    for (i = 0; i < count; i += 1) {
        if (classes[i] === className) {
            hadClass = true;
        }
    }
    if (hadClass) {
        return;
    }
    obj.className = (obj.className ? obj.className + ' ' + className : className);
};


// removes a classname from a Node (if it has it now)
MKM.removeClass = function (obj, className) {
    var oldClasses = obj.className,
        classes = oldClasses.split(' '),
        count = classes.length,
        newClass = '',
        i = 0;

    for (i = 0; i < count; i += 1) {
        if (classes[i] !== className) {
            newClass += (newClass ? ' ' + classes[i] : classes[i]);
        }
    }
    obj.className = newClass;
};


// checks if a node has the given class
MKM.hasClass = function (obj, className) {
    var oldClass = obj.className;
    
    return (-1 === oldClass.indexOf(className) ? false : true);
};



function onAjaxFilterResponse(resp) {
    // some data saved in $_SESSION variable
    window.location = "http://hirdetes-reklam-reklamtabla.hu/" + resp;
}
function addFilter(filter_lvl, value)
{
    ajax.callFunctionWithResponse(MAP.ajax_url + '?page=' + 1 + '&mode=add' + '&filter_lvl=' + filter_lvl + '&value=' + value, 'get', onAjaxFilterResponse);
}
function removeFilter(filter_lvl, value)
{
    ajax.callFunctionWithResponse(MAP.ajax_url + '?page=' + 1 + '&mode=remove' + '&filter_lvl=' + filter_lvl + '&value=' + value, 'get', onAjaxFilterResponse);
}

function decreaseSize(value) {
    var results = getElement('results'),
        value_w = 0;

    value += 10;
    value_w = 540 - value;
    results.style.left = value + 'px';
    results.style.width = value_w + 'px';
    if (value <= 489) {
        window.setTimeout('decreaseSize(' + value + ')', 10);  
    } else {
        results.style.left = '489px';
        results.style.width = '51px';
    }
    return true;
}
function increaseSize(value) {
    var results = getElement('results'),
        value_w = 0;

    value -= 10;
    value_w = 540 - value; 
    results.style.left = value + 'px';
    results.style.width = value_w + 'px';
    if (value >= 270) {
        window.setTimeout('increaseSize(' + value + ')', 10);  
    } else {
        results.style.left = '270px';
        results.style.width = '270px';
    }
    return true;
}


function mapsHandler() {
    var cent = null,
        zoomlevel = 0,
        sw = null,
        ne = null,
        recenter = null,
        results = null,
        handler = null,
        factor = 0;
    
    cent = MAP.boundaries.getCenter();
    zoomlevel = MAP.map.getBoundsZoomLevel(MAP.boundaries) - 1;
    sw = MAP.boundaries.getSouthWest();
    ne = MAP.boundaries.getNorthEast();
    recenter = new google.maps.LatLng(cent.lat(), cent.lng());
    
    results = getElement('results');
    handler = getElement('mapsHandler');
    if (MKM.hasClass(handler, "open")) {
        MKM.removeClass(handler, "open");
        MKM.addClass(handler, "close");
        decreaseSize(270);
        handler.innerHTML = '«';
        
        MAP.map.setCenter(recenter, zoomlevel);
        factor = (ne.lng() - sw.lng()) * (1 / zoomlevel);
        MAP.map.panTo(new GLatLng(cent.lat(), cent.lng() + factor));    
    } else {
        MKM.removeClass(handler, "close");
        MKM.addClass(handler, "open");
        increaseSize(489);
        handler.innerHTML = '»';
        
        MAP.map.setCenter(recenter, zoomlevel);
        factor = (ne.lng() - sw.lng()) * (14 / zoomlevel);
        MAP.map.panTo(new GLatLng(cent.lat(), cent.lng() + factor)); 
    }
}


KROC.inputFocus = function () {
    $(this).removeClass('defaultValue');
};


KROC.inputBlur = function () {
    var ta = $(this);
    if (KROC.default_text === ta.val()) {
        ta.addClass('defaultValue');
    }
};


KROC.afterModalOpen = function () {
    var ta = $('#cf2_field_6');
    if (ta.length) {
        KROC.default_text = ta.html();
        ta.addClass('defaultValue');
        ta.focus(KROC.inputFocus);
        ta.blur(KROC.inputBlur);
    }
};


KROC.onModalOpen = function () {
    window.setTimeout(KROC.afterModalOpen, 1000);
};


// runs on page load
KROC.onPageLoad = function ()
{
    var button = $('a.modalInput[title="Ajánlatkérés"]'),
        main_page_table_count_span = $('.post-52 p span.hl'),
        real_count_holder = $('h2.green_title small');

    if (button.length) {
        button.click(KROC.onModalOpen);
    }
    // if we are on the main page, copy the real count into the top right text
    if (main_page_table_count_span.length && real_count_holder.length) {
        main_page_table_count_span = main_page_table_count_span[0];
        main_page_table_count_span.innerText = real_count_holder.html().slice(1, -1);
    }
};


$(KROC.onPageLoad);
