(function($) {
if (!window.hizzou_core) { window.hizzou_core = {}; }

hizzou_core.ajax_url = '/hizzouapp/';
hizzou_core.viewsFolder = '/wp-content/mu-plugins/hizzou/views/';
hizzou_core.debug = false;

// Using For Selenium Tests.
if(window.location.href.match(/selenium/)) {
    hizzou_core.debug = true;
}

// @todo: test this feature more
var hizzouCurrentUserCookie = readCookie('hizzouCurrentUser');
var hizzouCurrentUserFeaturesCookie = readCookie('hizzouCurrentUserFeatures');
if (hizzouCurrentUserCookie && hizzouCurrentUserFeaturesCookie) {
    hizzou_core.current_user = JSON.parse(hizzouCurrentUserCookie);
    hizzou_core.current_user.userFeatures = JSON.parse(hizzouCurrentUserFeaturesCookie);
}

/***************************************
*  Additional functionality 
***************************************/

/**
* additional function for IE
*/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

/**
* extend jQuery object. Allow to fill select tag with states options
*/
jQuery.fn.fillStates = function (selected_value) {
    var html = '';
    for(var i=0;i<hizzou_core.states_list.length;i++){
        var current_state = hizzou_core.states_list[i];
        html += '<option value="'+current_state.abbreviation+'"'+(selected_value==current_state.abbreviation?' selected="selected"':'')+'>'+current_state.name+'</option>';
    }
    this.html(html);
}

/**
* extend jQuery object. Blocking jQuery object Element and open Modal Dialog by clicking on blocked Element
*/
jQuery.fn.dimContent = function (options) {

    var options = arguments[0] || {};
	var dialogTitle = options.dialogTitle || 'Upgrade Information';
	var dialogMessage = options.dialogMessage || 'You should upgrade to one of our premium plans to get this Service.';
    var showNow = options.showNow || false;

    if( !$('#blockdialog').length ) {
        var html = '<div id="blockdialog" class="ui-widget" style="display: none;">' +
                       '<div class="blockdialog-title ui-widget-header ui-corner-all"></div>' +
                       '<div class="blockdialog-content"></div>' +
                       '<div class="blockdialog-actions">' +
                           '<div class="blockdialog-close ui-state-default ui-corner-all">Close</div>' +
                           '<div class="blockdialog-upgrade ui-state-default ui-corner-all">Upgrade Now</div>' +
                           '<div class="hiz-clear"></div>' +
                       '</div>' +
                   '</div>';
        $('body').append(html);
        
        $('.blockdialog-close').live('click', function(){
            $.unblockUI();
        });
                    
        $('.blockdialog-upgrade').live('click', function(){
            window.location.href='admin.php?page=hizzouUpgradePlan';
        });
    }
    
    function showModalDialog () {
        $('.blockdialog-title').html(dialogTitle);
        $('.blockdialog-content').html(dialogMessage);
        $.blockUI({ 
            message: $('#blockdialog'),
            css: { top:'25%',
                   textAlign: 'left',
                   border: '3px solid #aaa', 
                   cursor: 'default' },
            showOverlay: false 
        });
    }
    
    this.block({
        message:null,
        overlayCSS:  {
            cursor: 'pointer',
            backgroundColor: '#000', 
            opacity: 0.6 
        }
    });
    
    this.click(function(){
        showModalDialog();
    });
    
    if(showNow) {
        showModalDialog();
    }
}

/**
  Simple versoin of jquery-ui-tabs. 
  Example:
    <div class="my-tabs">
        <ul class="tabs">
            <li><a href="#simpletabs-map">Map</a></li>
            <li><a href="#simpletabs-city">City</a></li>
        </ul>
        <div class="simpletabs simpletabs-map">MAAAPPP</div>
        <div class="simpletabs simpletabs-city">CIIIITYYY</div>        
    </div>
    <script>
        $('.my-tabs').simpleTabs();
    </script>
*/
jQuery.fn.simpleTabs = function () {
    var instance = this;
    instance.links = instance.children('ul').find('a');
    instance.divs = instance.children('div.simpletabs');
    instance.divs.hide();
    instance.links.each(function (i,link) {
        $(link).click(function(){
            instance.links.removeClass('simpletabs-active');
            $(this).addClass('simpletabs-active');
            instance.divs.hide();
            instance.children('div.'+$(link).attr('href').replace(/#/,'')).show();
        });
    });
    instance.links.eq(0).click();
    if(instance.css('display') == 'none') instance.show();
}

/**
 * This code allow easy create 'Favorites feature' for hissou elements.
 * Example:
 * <a href="javascript:;" propertyId="23" class="hizzou-save-favorite">Save</a>
 * <script>
 *    $('.hizzou-save-favorite').enableFavoritesFeature();
 * </script>
 */
jQuery.fn.enableFavoritesFeature = function () {
	
	var options = arguments[0] || {};
	var saveHTML = options.saveHTML || 'Save';
	var removeHTML = options.removeHTML || 'Remove';
	
    var elementsList = this;
    
    var setCurrentState = function (el) {
        if (hizzou_core.current_user && 
            hizzou_core.current_user.favoriteListingsListIDs.indexOf(parseInt(el.attr('propertyId')))>-1
        ) {//already in favorites
            el.html(removeHTML);
            el.data('isSaved',true);
        } else {
            el.html(saveHTML);
            el.data('isSaved',false);
        }
    }
    
    // set default states
    elementsList.each(function(){setCurrentState($(this));});
    
    elementsList.filter('[propertyId]')
        .click(function(){
            if (hizzou_core.current_user) {
                var el = $(this);
                el.append('<div class="loader"></div>');
                el.css('position','relative');
                el.find('.loader').css({'position':'absolute',
                                        'top':'0',
                                        'bottom':'0',
                                        'left':'0',
                                        'right':'0',
                                        'background':'url('+hizzou_core.hizzouPluginURL+'pw_loader.gif) center center no-repeat'
                                        });
                if ( el.data('isSaved') ) {// do remove
                    
                    if (!hizzou_core.debug) {
                        $.ajax({url:hizzou_core.ajax_url+'resources/favoriteListing/'+el.attr('propertyId'),type:'DELETE',async:false});
                    }
                    // remove id from related list. 
                    // @todo: possible need also remove item from hizzou_core.current_user.favoriteListingsList array
                    var indexOf = hizzou_core.current_user.favoriteListingsListIDs.indexOf(parseInt(el.attr('propertyId')));
                    if(indexOf>-1){
                        hizzou_core.current_user.favoriteListingsListIDs.splice(indexOf,1);
                    }
                } else {// do save
                    
                    if (!hizzou_core.debug) {
                        $.ajax({url:hizzou_core.ajax_url+'resources/favoriteListing/',type:'POST',data:{'hizzouId':el.attr('propertyId')},async:false});
                    }
                    // add id into related list. 
                    // @todo: possible need also add item into hizzou_core.current_user.favoriteListingsList array
                    hizzou_core.current_user.favoriteListingsListIDs.push(parseInt(el.attr('propertyId')));
                }
                el.remove('.loader');
                setCurrentState(el);
                if (options.onFinishAction) {options.onFinishAction(el.data('isSaved'));};
            }
        });
}

hizzou_core.loadingIndicator = function (action) {
    if (action=='show') {
        $('#hizzou-page-loading-spinner').show();
    } else {
        $('#hizzou-page-loading-spinner').hide();
    }
}

/**
* Function which convert serializeArray() results to JSON Object
* Convert [{name:'username',value:'Josh'},{name:'site',value:'google.com'}] to {username:'Josh',site:'google.com'}
*/
hizzou_core.paramsArrayToJSON = function (in_array) {
    var out_object = {};
    
    for( var i=0;i<in_array.length;i++) {
        if (out_object[in_array[i].name]) {
            if (typeof(out_object[in_array[i].name])=='object') {
                out_object[in_array[i].name].push(in_array[i].value);
            } else {
                out_object[in_array[i].name] = [out_object[in_array[i].name],in_array[i].value];                
            } 
        } else {
            out_object[in_array[i].name] = in_array[i].value;
        }        
    }
    return out_object;
}

/**
* Function which convert serializeArray() results to JSON Object
* Convert username=Josh&site=google.com to [{name:'username',value:'Josh'},{name:'site',value:'google.com'}]
*/
hizzou_core.urlParamsToArray = function (str) {
    var result = [];
    var vars = str.split('&');
    var tempUsedNames = [];
    for (var i=0; i<vars.length; i++) {
        var variableInfo = vars[i].split('=');
        var itemIndex = tempUsedNames.indexOf(variableInfo[0]);

        if (itemIndex==-1) {// so we don't have this key yet
            tempUsedNames.push(variableInfo[0]);
            result.push({name:variableInfo[0], value:variableInfo[1]});
        } else {
            if (typeof(result[itemIndex].value) == 'object') {
                result[itemIndex].value.push(variableInfo[1]);
            } else {
                result[itemIndex].value = [result[itemIndex].value,variableInfo[1]];
            }
        }
    }
    return result;
}

/** NOT USES YET
* Function which convert serializeArray() results to JSON Object
* Convert username=Josh&site=google.com to {username:'Josh',site:'google.com'}
*/
hizzou_core.urlParamsToJSON = function (str) {
    var result = {};
    var vars = str.split('&');
    for (var i=0; i<vars.length; i++) {
        var variable_info = vars[i].split('=');
        result[variable_info[0]] = variable_info[1];
    }
    return result;
}

/**
* retrive Property by id
*/
hizzou_core.getPropertyById = function (hizzouId) {
    hizzou_core.propertiesList = hizzou_core.getPropertiesListBackend();
    
    for (var i=0;i<hizzou_core.propertiesList.length;i++) {
        if (hizzou_core.propertiesList[i].hizzouId == hizzouId) {
            return hizzou_core.propertiesList[i];
        }
    }
    return null;
}

/**
* 
*/
hizzou_core.countLeadTypes = function(){
    var result = [0, 0, 0];
    for (var i = 0; i < hizzou_core.prospectsList.length; i++) {
        if (hizzou_core.prospectsList[i].leadType == 'Web') 
            result[0] += 1;
        else 
            if (hizzou_core.prospectsList[i].leadType == 'Phone') 
                result[1] += 1;
            else 
                if (hizzou_core.prospectsList[i].leadType == 'Text (SMS)') 
                    result[2] += 1;
    }
    return result;
}

/**
* 
*/
hizzou_core.countLeadTypesByHizzouId = function(hizzouId){
    var result = [0, 0, 0];
    for (var i = 0; i < hizzou_core.prospectsList.length; i++) {
        if (hizzou_core.prospectsList[i].leadType == 'Web' && hizzou_core.prospectsList[i].hizzouId == hizzouId) 
            result[0] += 1;
        else 
            if (hizzou_core.prospectsList[i].leadType == 'Phone' && hizzou_core.prospectsList[i].hizzouId == hizzouId) 
                result[1] += 1;
            else 
                if (hizzou_core.prospectsList[i].leadType == 'Text (SMS)' && hizzou_core.prospectsList[i].hizzouId == hizzouId) 
                    result[2] += 1;
    }
    return result;
}

hizzou_core.countSocialMediaLeadTypes = function(){
    hizzou_core.socialMediaPostsList = hizzou_core.getSocialMediaPostsListBackend();
    var result = [0, 0];
    for (var i = 0; i < hizzou_core.socialMediaPostsList.totals.length; i++) {
        if (hizzou_core.socialMediaPostsList.totals[i].alias == 'Twitter') 
            result[0] = hizzou_core.socialMediaPostsList.totals[i].count;
        if (hizzou_core.socialMediaPostsList.totals[i].alias == 'Facebook') 
            result[1] = hizzou_core.socialMediaPostsList.totals[i].count;
    }
    return result;
}

hizzou_core.countSocialMediaLeadTypesByHizzouId = function(hizzouId){
    hizzou_core.socialMediaPostsList = hizzou_core.getSocialMediaPostsListBackend();
    var result = [0, 0];
    for (var i = 0; i < hizzou_core.socialMediaPostsList.items.length; i++) {
        if (hizzou_core.socialMediaPostsList.items[i].alias == 'Twitter' && hizzou_core.socialMediaPostsList.items[i].listingId == hizzouId) 
            result[0] = hizzou_core.socialMediaPostsList.items[i].count;
        if (hizzou_core.socialMediaPostsList.items[i].alias == 'Facebook' && hizzou_core.socialMediaPostsList.items[i].listingId == hizzouId) 
            result[1] = hizzou_core.socialMediaPostsList.items[i].count;
    }
    return result;
}


hizzou_core.numberFormat = function (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  

    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}

/**
*  Simulates PHP's date function
*/
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};

Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};

})(jQuery);


/**
 * Functions for Cookies
 */
function createCookie(name,value,mins,path) {
	if (mins) {
		var date = new Date();
		date.setTime(date.getTime()+(mins*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
    
    var pathValue = path ? path : '/';
    
	document.cookie = name+"="+escape(value)+expires+"; path="+pathValue;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/* alternative - jQuery Cookie plugin */
//jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){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();}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{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/**
* End Cookies Fucntions
*/