﻿jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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
        }
        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].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && 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 (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function() {
    if ($('#lefthandpanel').height() < $('#maincontent').height())
    {
        $('#lefthandpanel').css('height', $('#maincontent').height());
        $('#righthandpanel').css('height', $('#maincontent').height()); 
    }
    var sjc = $.cookie('JB');
    if (sjc == null || sjc == '')
        return;
    $("#jobresults > li span.sj").each(function() {
        var id = $(this).attr('id').replace('sj_', '');
        if (sjc.indexOf(id) > -1) {
            $(this).saved = true;
            $(this).html("<span class='saved'>saved to</span> <a href='jb'>basket</a>");
            $(this).css('text-decoration', 'none');
            showRemove(this, id);
        }
    });
});
function showAddMessage() {
    $('#oms').toggleClass('hide');
}
function sendEmailToFriend(query) {    
    //validate email
    if ($('#fe').val() == ''){
        $("#efer").addClass('error').css('display', 'block').html("Please enter your email");
        return;
    }
    if ($('#te').val() == ''){
        $("#efer").addClass('error').css('display', 'block').html("Please enter your friend email");
        return;
    }
    if (!($('#fe').val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i))) {
        $("#efer").addClass('error').css('display', 'block').html($('#fe').val() + " is not a valid email");
        return;
    }
    if (!($('#te').val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i))) {
        $("#efer").addClass('error').css('display', 'block').html($('#te').val() + " is not a valid email");
        return;
    }

    //email ok, send!
    $.ajaxSetup();
    $("#efer").ajaxStart(function() {
        $(this).css('display', 'block').removeClass('error').html("Sending alert...");
    });
    $.getJSON("/services/email", { q: query, emailfrom: $("#fe").val(), emailto: $("#te").val(), message: $("#message").val(), mode: "emailfriend" },
    function(data) {
        if (data.error == 'true') {
            $("#efer").addClass('error').html(data.message);
        } else {
        $('#efer').next().css('display', 'none');
        $('#sft').hide();
        $('#sfsp').html("<p> Your email to <b>" + $('#te').val() + "</b> has been sent.");
        $("#efer").html("");
        $('#sfs').show();
        }
    });
}
function showSendMailFriendForm() {
    $('#sfs').hide();
    $('#sft').show();
}
function hideFilterPanel() {
    $('#bd > div.yui-b').css({ display: 'none', width: '0em' });
    $('#yui-main > div.yui-b').css('margin-left', '0em');
    $('#fp').show();
    $('#frfc_v').hide();
    $('#frfc_h').show();
    $.cookie('SFP', 'false', { expires: 7,path:'/' });    
}
function showFilterPanel() {
    $('#bd > div.yui-b').css({ display: 'block', width: '13.8461em' });
    $('#yui-main > div.yui-b').css('margin-left', '14.8461em');
    $('#fp').hide();
    $('#frfc_v').show()
    $('#frfc_h').hide();
    $.cookie('SFP', 'true', { expires: 7, path: '/' }); 
}

function setMoreInfoPanel(e) {
    $(e).parent().next().toggleClass('hide')
    if ($(e).attr('class') == 'fano') {
        $(e).attr('class', 'fan');
    } else {
        $(e).attr('class', 'fano');
    }
}
function setFacetFilter(ml) {
    var more = "see more &#187;";
    var less = "&#171; see less";
    var hide = 1;
    var facetRows = $(ml).parent().prev().children();
    if ($(ml).html().indexOf('more')>=0) {
        $(ml).html(less);
        hide = 0;
    }
    else $(ml).html(more);

    var counter = 1;

    facetRows.each(function() {
        if (counter > 3 && hide==1)
            $(this).hide()
        else if (counter > 3)
            $(this).show()
        
        counter++;
    });    
}

function collapseFacet(fl, facetKey) {
    var facetRows = $(fl).next();
    var morelessRow = facetRows.next();

    //get facet cookies, facet control should use this cookies to hide or show facet
    //all facets are visible by default
    var fc = $.cookie('FC') != null ? $.cookie('FC'): 't,e,ct,jt,s,c,d,sc,r,';
    if ($(facetRows).css('display') == 'none') {
        //show facet rows
        $(fl).children().attr('class', 'fano');
        facetRows.css('display', 'block');
        //make sure show more/less row is shown
        morelessRow.css('display', 'block');
        //insert facet cookie for current facetKey
        if (!fc.indexOf(facetKey + ',') >= 0)
            fc = fc  + ',' + facetKey +',';
    } else {
        //hide facet rows
        $(fl).children().attr('class', 'fan');
        facetRows.css('display', 'none');
        //make sure show more/less row is hidden
        morelessRow.css('display', 'none');
        //remove cookie for current facekey
        if (fc.indexOf(facetKey + ',') == 0)
            fc = fc.replace(facetKey + ',', '');
        else if (',' + fc.indexOf(facetKey + ',') >= 0)
            fc =','+ fc.replace(',' + facetKey + ',', '');
        
    }

    //update cookies and expire date
    $.cookie('FC', null);
    $.cookie('FC', fc, { expires: 7, path: '/' });    
}

function showRemove(e, jid) {
    $(e).html("<span class='saved'>saved to</span> <a href='/jobbasket.html'>basket</a> - ");
    $(e).css('text-decoration', 'none');
    var rj = $("<span class='sl'>remove</span>").bind('click', function() {
        $.cookie('JB', $.cookie('JB').replace('|' + jid, ''), { expires: 30, path: '/' });
        $(this).remove();
        e.saved = false;
        $(e).html("save job");
        $(e).css('text-decoration', 'underline');
    });
    $(e).after(rj);
    e.saved = true;
}

function save(e, jid) {
    if (e.saved)
        return;
    var sj = $.cookie('JB') != null ? $.cookie('JB') : '';
    if (!sj.match(jid))
        sj = sj + '|' + jid;
    $.cookie('JB', sj, { expires: 30, path: '/' });
    showRemove(e, jid);
}



function showEmailForm() {
    if ($('#emailalert').attr('class') == 'close') {
        $('#jobalertform1').css('display', 'block');
        $('#emailalert').attr('class', 'open');
        $('#alert').toggleClass('open');
    } else {
        $('#jobalertform1').css('display', 'none');
        $('#emailalert').attr('class', 'close');
        $('#alert').toggleClass('open');
    }
}

function saveAlert(query,index) {
    if ($('#email'+ index).val() == '') {
        $("#jam" + index).addClass('error').css('display', 'block').html("Please enter your email");
        return;
    }
    if (!($('#email' + index).val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i))) {
        $("#jam" + index).addClass('error').css('display', 'block').html($('#email'+index).val() + " is not a valid email");
        return;
    }
    $.ajaxSetup();
    $("#jam"+index).ajaxStart(function() {
        $(this).css('display', 'block').removeClass('error').html("Saving alert...");
    });
    $.getJSON("/services/email", { q: query, f: $("#frequency" + index).val(), email: $("#email"+index).val(),mode:"emailalert" },
    function(data) {    
        if (data.error == 'true') {
            $("#jam"+index).addClass('error').html(data.message);
        } else {
            $('#jam'+index).next().css('display', 'none');
            $('#jam'+index).html("<b>" + data.message + " An confirmation email has been sent to your email. Please check your email to activate the alert!</b>").removeClass('error');
        }
    });
}

