function toggleDiv(divid)
{
    var mainpunkt = document.getElementById(divid+'_arr');
    if($('#'+divid).css('display') == 'block')
    {
        $('#'+divid).css('display','none');
        $('#arr_'+divid).css('background-position','right -457px');

    }
    else
    {
        $('#'+divid).css('display','block');
        $('#arr_'+divid).css('background-position','right -1253px');
    }
}

function changePoint(a)
{
    document.getElementById("point").innerHTML = a.innerHTML;
}

function subitem(a,li_block_id)
{
  if(a.href==window.location.protocol+'//'+window.location.hostname+window.location.hash.substr(1))
  return false;
  $("#subitem").html(a.innerHTML);
    $('#incurrent').attr('id','');
    a.parentNode.id = 'incurrent';
    getCenterContent(a.href, false);
    $('#yapanel_adminmenu_ul > li').attr('class','');
    $('#yapanel_adminmenu_ul > li > div').hide();
    $('#yapanel_adminmenu_li_'+li_block_id).attr('class','current');
    $('#yapanel_adminmenu_li_'+li_block_id+' > div').show();
    return false;
}

function init(id) {
  var obj = document.getElementById(id);
  if (obj) {
    obj.state = 0;
    obj.timer = null;
    obj.maxVert = obj.scrollWidth - obj.offsetWidth;
    obj.maxVert2 = obj.scrollHeight - obj.offsetHeight;
  }
}

$(document).ready(function(){
    $("#scrollme_block.flight-w table td:even").addClass("bg_none");
  });

function scroll_right2(id,timer) {
  var obj = document.getElementById(id);

  if (!obj.maxVert) {init(id)};
  if (timer == undefined) {obj.state = 1};

  if ((obj.maxVert > obj.scrollLeft) && (obj.state == 1))
  {
    obj.scrollLeft = obj.scrollLeft + 340;
    elem = document.getElementById("scroll_left");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }

  if(!(obj.maxVert > obj.scrollLeft))
  {
       elem = document.getElementById("scroll_right");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("scroll_left");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }
}

function scroll_default(id,left) {
  var obj = document.getElementById(id);
  if (!obj.maxVert) {init(id)};
  if(left==undefined) {left = 0;}

  if (obj.maxVert > obj.scrollLeft && left > 0)
  {
    obj.scrollLeft = obj.scrollLeft + left;
  }

  if(!(obj.scrollLeft > 0))
  {
       elem = document.getElementById("scroll_left");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("scroll_right");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }

  if(!(obj.maxVert > obj.scrollLeft))
  {
       elem = document.getElementById("scroll_right");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("scroll_left");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }
}

function scroll_left2(id,timer) {
  var obj = document.getElementById(id);
  if (!obj.maxVert) {init(id)};
  if (timer == undefined) {obj.state = -1};

  if ((obj.scrollLeft > 0) && (obj.state == -1))
  {
    obj.scrollLeft = obj.scrollLeft > 10 ? obj.scrollLeft - 340 : 0;
    elem = document.getElementById("scroll_right");
    elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }

  if(!(obj.scrollLeft > 0))
  {
       elem = document.getElementById("scroll_left");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("scroll_right");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }
}

//------Scroll eMenu------

function scroll_down(id,timer) {
  var obj = document.getElementById(id);
  if (!obj.maxVert2) {init(id)};
  if (timer == undefined) {obj.state = 1};

  if ((obj.maxVert2 > obj.scrollTop) && (obj.state == 1))
  {
    obj.scrollTop = obj.scrollTop + 120;
    elem = document.getElementById("change_up");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }

  if(!(obj.maxVert2 > obj.scrollTop))
  {
       elem = document.getElementById("change_down");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("change_up");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }
}


function scroll_up(id,timer) {
  var obj = document.getElementById(id);
  if (!obj.maxVert2) {init(id)};
  if (timer == undefined) {obj.state = -1};

  if ((obj.scrollTop > 0) && (obj.state == -1))
  {
    obj.scrollTop = obj.scrollTop > 10 ? obj.scrollTop - 120 : 0;
    elem = document.getElementById("change_down");
    elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }

  if(!(obj.scrollTop > 0))
  {
       elem = document.getElementById("change_up");
       elem.style.opacity = 0.6;
       elem.style.cursor = "default";

       elem = document.getElementById("change_down");
       elem.style.opacity = 1.0;
       elem.style.cursor = "pointer";
  }
}
//------End Scroll eMenu------
/*for more info*/

function gif_over(img){
    if(img.src.substr(-6)=='_a.gif'){
        return false;
    }
    img.src=img.src.replace('_n.gif','_r.gif');
    img.src=img.src.replace('_a.gif','_r.gif');
}
function gif_out(img, forced){
    if(!forced  && img.src.substr(-6)=='_a.gif'){
        return false;
    }
    img.src=img.src.replace('_r.gif','_n.gif');
    img.src=img.src.replace('_a.gif','_n.gif');
}
function gif_click(img){
    img.src=img.src.replace('_r.gif','_a.gif');
    img.src=img.src.replace('_n.gif','_a.gif');
}

function onLoad() {
    timerCookie = window.setTimeout(onTick, 200);
}

function onTick() {
    timerCookie = null;
    if(window.location.hash != '#'+history_link && history_link.length > 5)
    {
        if(window.location.hash.substr(0,8) == '#/_ajax/')
        getCenterContent(window.location.hash.substr(1), false);
    }
    timerCookie = window.setTimeout(onTick, 200);
}

function onUnload() {
    if (timerCookie != 'undefined' && timerCookie) {
        window.clearTimeout(timerCookie);
    }
}

var history_link = '';
var history_link2 = '';
var current_li_id = '';
var historyBackObject={url:'',params:{}};
var IS_FRONTEND=true;
var is_first = true;
function getCenterContent(url, confirm_action, is_frontend)
{
    if(is_frontend)
        IS_FRONTEND=true;
    else
        IS_FRONTEND=false;
    //alert(is_frontend);
    if(url != '')
    {
        index = url.indexOf(location.hostname);
        if(index > -1)
        {
            index = index+location.hostname.length;
            url = url.substr(index);
        }

        if(confirm_action == true){
            if(confirm('Are you sure?')==false){return;}
        }
        var hObject=historyBackObject;
        $("#c_content").unbind()
        var bNeedFav = (location.hash.indexOf('#') == -1) || is_first;
        is_first = false;
        $("#c_content").html('<div align="center"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');
        $.get(url+'/'+Math.random(),
            function(data){
                // TODO: figure out how to backup current document.ready stack
                // smth like
                //      var e = $(document).getEvent('ready');
                //      $(document).unbind('ready');
                if(bNeedFav) data = '<link rel="shortcut icon" href="'+$('link[rel=icon]').attr('href')+'" type="image/x-icon" /> <link rel="icon" href="'+$('link[rel=icon]').attr('href')+'" type="image/x-icon" />' + data;
                $("#c_content").html(data);
                jQuery.ready();
                //      $(document).bind('ready', e);

                if(typeof(setHistoryBackParams)=='function')
                {
                    setHistoryBackParams(hObject.params);
                }

                if(typeof(historyBackObject.url)!='undefined' && historyBackObject.url.length>0)
                {
                    $('#get_history_back_container').show();
                }else{
                    $('#get_history_back_container').hide();

                }
            }
        );

        regexp = /\//g;
        $('#incurrent').attr('id','');

        domId = $('#'+url.replace(regexp,'_')).get(0);
        if(domId){
            domId.parentNode.id = 'incurrent';
        }

        location.hash = url;
        if(url != history_link){history_link2 = history_link;history_link = url;}
    }
}
function checkHistoryBackCenterContent(url, params, is_frontend)
{
    if(typeof(params)=='undefined')
    {
        historyBackObject={url:'',params:{}};
        return false;
    }
    var obj={};
    if(typeof(params.use_this_params)!='undefined' && historyBackObject.url!='')
    {
        obj.url=historyBackObject.url;
        obj.params=historyBackObject.params;
    }else{
        obj.url=url;
        obj.params=params;
    }
    historyBackObject=obj;
}
function getHistoryBackCenterContent(is_frontend)
{
        if(historyBackObject.url.length>0)
        {
            if(is_frontend)
            location.href=historyBackObject.url;
            else{
                historyBackObject.params.use_this_params=true;
                getCenterContent(historyBackObject.url, false, is_frontend);
            }

        }else if(is_frontend){
            history.back();
        }else{
            getCenterContent(history_link2);
        }

}

function ShowHideById(id)
{
    /*
        Travmatolog: see http://docs.jquery.com/Effects/toggle
        $('#id').toggle();
    */
    if($('#'+id).css('display') == 'none')
    {
        $('#'+id).css('display', 'block');
    }
    else
    {
        $('#'+id).css('display', 'none');
    }
}

function trim(str) {
    return ltrim(rtrim(str));
}
function ltrim(str, chars) {
    return str.replace(new RegExp("^[\\s]+", "g"), "");
}
function rtrim(str, chars) {
    return str.replace(new RegExp("[\\s]+$", "g"), "");
}

var list_blocks = new Array();
var refreshedContainers=new Array();
function refreshCrollPanels(l_id,type){
    var r=$('#scrollme2.notsetuped', $('#container_'+l_id+'_'+type));
   if(r.get(0)){
       $(r).removeClass('notsetuped');
       $(r).jScrollPane({showArrows:true, scrollbarWidth:13, dragMaxHeight:13});
   }
}
function more_info(l_id,type,url,post_params, callback)
{
    var container = document.getElementById('container_'+l_id);
    var img = document.getElementById('img_'+l_id+'_'+type);
    var tmp;
    var divs = new Array('free_call','video','menu','photos','advert','map','web','email','coupon','save_share','reviews','social','products','faq','info','qrcode');
    for(var div_i = 0; div_i < 50; div_i++)
    {
        divs[div_i + 15] = 'video_container_' + div_i;
    }

    // TO DO - refactor later - all function should be refactored
	//alert(1);
    /* send http request */
    if(url!=null && $('#container_'+l_id+'_'+type).html()=='')
    {
    	$('#container_'+l_id+'_'+type).html(Yabsta.featureLoadingHTML);
        if(post_params!=null)
        {
            $.post(url, post_params, function(data){
                $('#container_'+l_id+'_'+type).html(data);
                refreshCrollPanels(l_id,type);

            });
        }
        else
        {
            $.post(url, function(data){
                $('#container_'+l_id+'_'+type).html(data);
                refreshCrollPanels(l_id,type);
            });
        }
    }

    if($('#block_'+l_id).css('display')=='none')
    {
    	//img.onmouseover = function(){return false;};
        //img.onmouseout = function(){return false;};
        gif_click(img);
        list_blocks[l_id] = type;
        for(var i=0; i<divs.length; i++)
        {
            $('#container_'+l_id+'_'+divs[i]).css('display','none');
        }
        $('#container_'+l_id+'_'+type).css('display','block');
        if(!Yabsta.isIE)
        {
            $('#block_'+l_id).slideDown("slow",function(){
				if(typeof(callback)=='function'){
					callback();
				}
                                refreshCrollPanels(l_id,type);
                                if(type=='map' ){
                                    $('div[id^=gMap]',$('#block_'+l_id)).each(function(){
                                      if(typeof(refreshedContainers[this.id])=='undefined'){
                                        $.GMapQueue.refreshMap('#'+this.id,0.1);
                                        refreshedContainers[this.id]=1;
                                      }
                                    });
                                }
			});
        }
        else
        {
            $('#block_'+l_id).css('display','block');
				if(typeof(callback)=='function'){
					callback();
				}
                                refreshCrollPanels(l_id,type);

                                if(type=='map'){
                                    $('div[id^=gMap]',$('#block_'+l_id)).each(function(){
                                       if(typeof(refreshedContainers[this.id])=='undefined'){
                                        $.GMapQueue.refreshMap('#'+this.id,0.1);
                                        refreshedContainers[this.id]=1;
                                      }
                                    });
                                }
        }
    }
    else
    {
    	if(list_blocks[l_id]!=type)
        {
            //img.onmouseover = function(){return false;};
            //img.onmouseout = function(){return false;};
            gif_click(img);

            /*alert('img_'+l_id+'_'+list_blocks[l_id]);*/
            tmp = document.getElementById('img_'+l_id+'_'+list_blocks[l_id]);
            /*alert(tmp);*/
            gif_out(tmp, true);
            /*alert('normal');*/

            tmp.onmouseover = function(){gif_over(this);};
            tmp.onmouseout = function(){gif_out(this);};
            list_blocks[l_id] = type;
            if(!Yabsta.isIE)
            {
                $('#block_'+l_id).slideUp("slow", function(){
                    for(var i=0; i<divs.length; i++)
                    {
                        $('#container_'+l_id+'_'+divs[i]).css('display','none');
                    }
                    $('#container_'+l_id+'_'+type).css('display','block');
                    $('#block_'+l_id).slideDown("slow", function(){

                        if(type=='map'){
                                    $('div[id^=gMap]',$('#block_'+l_id)).each(function(){
                                       if(typeof(refreshedContainers[this.id])=='undefined'){
                                        $.GMapQueue.refreshMap('#'+this.id,0.1);
                                        refreshedContainers[this.id]=1;
                                      }
                                    });
                                }

                    });



                });
            }
            else
            {
                $('#block_'+l_id).css('display','none');
                for(var i=0; i<divs.length; i++)
                {
                    $('#container_'+l_id+'_'+divs[i]).css('display','none');
                }
                $('#container_'+l_id+'_'+type).css('display','block');
                $('#block_'+l_id).css('display','block');
                if(type=='map'){
                                    $('div[id^=gMap]',$('#block_'+l_id)).each(function(){
                                       if(typeof(refreshedContainers[this.id])=='undefined'){
                                        $.GMapQueue.refreshMap('#'+this.id,0.1);
                                        refreshedContainers[this.id]=1;
                                      }
                                    });
                                }

            }
        }
        else
        {
          // alert(5);
        	gif_out(img, true);
            img.onmouseover = function(){gif_over(this);};
            img.onmouseout = function(){gif_out(this);};
            if(!Yabsta.isIE)
            {
                $('#block_'+l_id).slideUp("slow");
            }
            else
            {
                $('#block_'+l_id).css('display','none');
            }
        }
    }
}

function delete_review(location_id,id,user_id,listing_id, inline)
{
    if(confirm('Are you sure?'))
    {
        $('#review_'+location_id+'_'+id+'_delete_span').html('<img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" />');
        $.post('/_ajax/listings/delete_review/'+Math.random(), {
           location_id: location_id,
           id: id,
           user_id: user_id,
           listing_id: listing_id,
           inline: inline
        }, function(data){
            $('#review_'+location_id+'_'+id+'_div').hide(300,function(){$('#review_'+location_id+'_'+id+'_div').html('<p class="marg7b">Your review deleted</p>');$('#review_'+location_id+'_'+id+'_div').show(300)});
        });
    }
}
function preloadingImages(){
	var __img_preload__ = new Array();
	var __tmp__ = 0;
	__img_preload__[__tmp__] = new Image();
	__img_preload__[__tmp__].src = Yabsta.Location.themeDir+'i/loadinfo.gif';
	var _preload_features=new Array('advert','coupon','email','epage','faq','free_call','info','map','menu','photos','products','qrcode','reviews','social','save_share','video','web', 'related');
	for(k in _preload_features){
		__img_preload__[++__tmp__] = new Image();
		__img_preload__[__tmp__].src = Yabsta.Location.themeDir+'i/info/'+_preload_features[k]+'_a.gif';
		__img_preload__[++__tmp__] = new Image();
		__img_preload__[__tmp__].src = Yabsta.Location.themeDir+'i/info/'+_preload_features[k]+'_n.gif';
		__img_preload__[++__tmp__] = new Image();
		__img_preload__[__tmp__].src = Yabsta.Location.themeDir+'i/info/'+_preload_features[k]+'_r.gif';
	}
}

/* unitpngfix.js
var clear=Yabsta.Location.themeDir+"i/clear.gif";
function pngfix(){
    if(Yabsta.isIE){
        var els=document.getElementsByTagName('*');var ip=/\.png/i;var i=els.length;while(i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';var elkids=el.getElementsByTagName('*');if (elkids){var j=elkids.length;if(el.currentStyle.position!="absolute")es.position='static';while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}
    }
}*/

function strip_tags(str)
{
    return str.replace(/<\/?[^>]+>/gi, '');
}

function preg_quote(str)
{
    return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}

function explode( delimiter, string )
{
    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return false;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return false;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}

function in_array(needle, haystack, strict) {

    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

function htmlspecialchars (string, quote_style) {
    if(string==undefined || typeof(string)==undefined) return false;
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'

    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();

    if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }

    return tmp_str;
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}

    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');

    /* Translate arguments*/
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    /*Map numbers to strings for compatibilty with PHP constants*/
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }

    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }

    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        /* ascii decimals for better compatibility*/
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        /* ascii decimals for better compatibility*/
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }

    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }

    return histogram;
}

function substr( f_string, f_start, f_length ) {    // Return part of a string
    //
    // +     original by: Martijn Wieringa
    
    if ('string' != typeof f_string)
        return '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}

function isValidPhoneTel(phone, format)
{
    format = preg_quote(format);
    var reg = new RegExp('^'+format.replace(/(#)/g,'\\d')+'$');
    return reg.test(phone);
}


function MakeActive()
    {activeButton.style.display = 'block';};
function UnMakeActive()
    {activeButton.style.display = 'none';};

function MakeActive1()
    {activeButton1.style.display = 'block';};
function UnMakeActive1()
    {activeButton1.style.display = 'none';};

function MakeActive2()
    {activeButton2.style.display = 'block';};
function UnMakeActive2()
    {activeButton2.style.display = 'none';};

function MakeActive3()
    {activeButton3.style.display = 'block';};
function UnMakeActive3()
    {activeButton3.style.display = 'none';};

var list_blocks2 = new Array();

function more_info2(l_id,type,url,post_params)
{
    var img = document.getElementById('img_'+l_id+'_'+type);
    //alert('img_'+l_id+'_'+type+ ' '+img);
    var tmp;
	if(img){
		//img.onmouseover = function(){return false;};
		//img.onmouseout = function(){return false;};
		gif_click(img);
	}
    /* send http request */
    if(url!=null && $('#container_'+l_id+'_'+type).html()=='')
    {
        $('#container_'+l_id+'_'+type).html(Yabsta.featureLoadingHTML);
        if(post_params!=null)
        {
            $.post(url, post_params, function(data){
                $('#container_'+l_id+'_'+type).html(data);
                                refreshCrollPanels(l_id,type);

            });
        }
        else
        {
            $.post(url, function(data){
                $('#container_'+l_id+'_'+type).html(data);
                                refreshCrollPanels(l_id,type);


            });
        }
    }

    var divs = new Array('free_call','video','menu','photos','advert','map','web','email','coupon','save_share','reviews','social','products','faq','info','qrcode', 'related');
    for(var div_i = 0; div_i < 50; div_i++)
    {
        divs[div_i + 15] = 'video_container_' + div_i;
    }

    for(var i=0; i<divs.length; i++)
    {
        $('#container_'+l_id+'_'+divs[i]).hide();
    }
    $('#container_'+l_id+'_'+type).show();
                   refreshCrollPanels(l_id,type);

    if(type=='map' ){
        $('div[id^=gMap]',$('#block_'+l_id)).each(function(){
          if(typeof(refreshedContainers[this.id])=='undefined'){
            $.GMapQueue.refreshMap('#'+this.id,0.1);
            refreshedContainers[this.id]=1;
          }
        });
    }
    if(type=='related' ){
        $('.epage_bord1 .scroll-pane').jScrollPane({showArrows:true, scrollbarWidth:13, dragMaxHeight:13});
    }
    if(list_blocks2[l_id]!=undefined)
    {
        tmp = document.getElementById('img_'+l_id+'_'+list_blocks2[l_id]);
        if(tmp)
        gif_out(tmp, true);
    }
    list_blocks2[l_id] = type;
}

function img_over(img,type){
    img.src=Yabsta.Location.themeDir+'i/info/'+type+'r.gif';
}
function img_out(img,type){
    img.src=Yabsta.Location.themeDir+'i/info/'+type+'.gif';
}
function img_click(img,type){
    img.src=Yabsta.Location.themeDir+'i/info/'+type+'a.gif';
}

function nl2br( str ) {
    return str.replace(/([^>])\n/g, '$1<br />');
}

function sendEmail(location_id,listing_id)
{
    var name = $('#epage_email_name_'+listing_id).val();
    if (name.length>0)
    {
        $('#err_epage_email_name_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_name_'+listing_id).empty().append('Empty name');
        return false;
    }

    var email = $('#epage_email_email_'+listing_id).val();
    if (email.match(/(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/))
    {
        $('#err_epage_email_email_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_email_'+listing_id).empty().append('Invalid or empty e-mail');
        return false;
    }

    var message = $('#epage_email_message_'+listing_id).val();
    if (message.length>0)
    {
        $('#err_epage_email_message_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_message_'+listing_id).empty().append('Empty message');
        return false;
    }

    $.post('/_ajax/listings/send_email/'+Math.random(), {
            "name": name,
            "email": email,
            "message": message,
            "location_id": location_id,
            "listing_id": listing_id
        },
        function(data){
            $('#container_'+listing_id+'_email').html(data);
        }
    );
}

function sendEmailFromSite(location_id, site_id, site_page_id)
{
	listing_id = 1;
    var name = $('#epage_email_name_'+listing_id).val();
    if (name.length>0)
    {
        $('#err_epage_email_name_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_name_'+listing_id).empty().append('Empty name');
        return false;
    }

    var email = $('#epage_email_email_'+listing_id).val();
    if (email.match(/(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/))
    {
        $('#err_epage_email_email_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_email_'+listing_id).empty().append('Invalid or empty e-mail');
        return false;
    }

    var message = $('#epage_email_message_'+listing_id).val();
    if (message.length>0)
    {
        $('#err_epage_email_message_'+listing_id).empty();
    }
    else
    {
        $('#err_epage_email_message_'+listing_id).empty().append('Empty message');
        return false;
    }

    $.post('/_ajax/websitebuilder/send_email/'+Math.random(), {
            "name": name,
            "email": email,
            "message": message,
            "location_id": location_id,
			"site_id":site_id,
			"site_page_id":site_page_id

        },
        function(data){
            $('#container_'+listing_id+'_email').html(data);
        }
    );
}


/*Table_Grid*/
function tabGrid() {
    $("table.tablesorter tbody td:nth-child(1)").addClass("backg_ad2");
    /*$("div.adminka_bordtop table tbody tr:odd").addClass("backg_ad");*/
    $("table.tablesorter tbody tr:nth-child(even)").addClass("backg_ad");
    $("table.tablesorter tbody tr").hover(function () {$(this).addClass("tr_hover");}, function () {$(this).removeClass("tr_hover");});
}

/*My Grid*/
function myGrid() {
    $("table.hours_operation tbody th:even").addClass("day_bg2");
    /*$("table.hours_operation tbody th:not(:first)").wrapInner("<span></span>");*/
    $("table.hours_operation tbody td:nth-child(1)").addClass("first");
	$("table.hours_operation tbody th:nth-child(1)").addClass("first-child");
    $('table.hours_operation').wrap('<div class="hours_operation_foot clearfix float_left"></div>');
}

/*Shadow for small map preview*/
function mapShadow() {
    $("#small_main_container").dropShadow({left:-1, top:-1, blur: 2, color: "#525252", opacity: "0.5"});
}

/*My Pop-up*/
function myPopup() {
    var myPopup = $("span.my_popup");
    $(myPopup).hide();
       $(myPopup).wrapInner('<span class="popup_body"></span>');
       $("span.popup_body").after('<span class="hvostik"></span>');

    $(".parent_popup span.popup_body").before('<span class="close_popup"></span>');

    $(".question img.click_circle").hover(function() {
        var popupHeight = $(this).next(myPopup).height();
        var parentWidth = $(this).prev("strong").width() - 34;
        var paddingTop = $(this).parent($(".question")).css('paddingTop');
        var questionTop = parseInt(paddingTop,10);
        var basicHeight = popupHeight - questionTop + 15;

        $(this).next(myPopup).animate({opacity: "show", top: "-" + basicHeight, left: parentWidth}, 400);
        $("span.popup_body",$(this).parent()).dropShadow({left:-1, top:-1, blur: 2, color: "#525252", opacity: "0.5"});
    }, function() {
        $(this).next(myPopup).animate({opacity: "hide"}, 50);
        $("span.popup_body",$(this).parent()).removeShadow();
    });

    $(".parent_popup img.click_circle").click(function() {
        var popupHeight = $(this).next(myPopup).height();
        var hvostikMargin = $("span.hvostik",$(this).parent()).css('marginLeft');
        var MarginLeft = parseInt(hvostikMargin,10);
        var basicWidth = MarginLeft - ($(this).width()) + 20 + ($(this).width())/2;
        var basicHeight = popupHeight - $(this).height() + 23;

        $(this).next(myPopup).animate({opacity: "show", top: "-" + basicHeight, left: "-" + basicWidth}, 400);
        $("span.popup_body",$(this).parent()).dropShadow({left:-1, top:-1, blur: 2, color: "#525252", opacity: "0.5"});
    });
    $("span.my_popup span.close_popup").click(function () {
        $(this).parent().animate({opacity: "hide"}, 50);
        $("span.popup_body",$(this).parent()).removeShadow();
    });
}

var tipMouseCoord = {x: 0, y: 0};
$(document).ready(
    function()
    {
        $(document).bind('mousemove.tips', function(e){tipMouseCoord = {x: e.pageX, y:e.pageY};});
    }
);

function showTip(alias, section, obj, path)
{
    path = Yabsta.Location.themeDir;
    var toolTipClass = 'YabstaTip';
    var toolTipContent = '<div align="center"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>';

    obj = $(obj);

    $.ajax(
    {
        type: 'POST',
        async: true,
        url: '/_ajax/tips/get',
        data: {alias: alias, section: section},
        dataType: 'json',
        success: function (data, textStatus)
        {
            toolTipContent = '<strong>'+data.title+'</strong><br/>'+data.description;

            obj.unbind('mouseover', showTip);

            $('.' + toolTipClass).stop().fadeOut(0, function(){$('.' + toolTipClass).remove();});
        	obj.attr({title: ''});
        //			$('body').append("<div class='"+ toolTipClass +"'><p class='aToolTipContent'>"+ toolTipContent +"</p></div>");
        	$('body').append('<div class="'+toolTipClass+'" style="display:none; overflow: hidden; width: 382px;"><div style="position: relative; top: 0px; text-align: left; opacity: 1; width: 382px;"><table style="margin: 0px; padding: 0px; position: relative; left: 0px; top: 0px; line-height: normal; width: auto;" cellpadding="0"><tbody style="border-width: 0px; margin: 0px; padding: 0px; position: relative; left: 0px; top: 0px; line-height: normal; width: auto;"><tr><td style="border-width: 0px; margin: 0px; padding: 0px; position: relative; left: 0px; top: 0px; line-height: normal; width: auto; color: rgb(0, 0, 0); font-family: Verdana,Geneva,sans-serif; font-size: 8pt; font-weight: normal; text-align: left;"><table style="margin: 0pt; padding: 0pt; width: 350px; left: 0pt; top: 0pt;" cellpadding="0"><tbody><tr><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; width: 16px; line-height: 0pt; vertical-align: bottom;" valign="bottom"><img src="'+path+'i/tip_balloon/lt.png" style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; line-height: 0pt;" height="16" width="16"></td><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; line-height: 0pt;" valign="bottom"><div style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; z-index: 0; top: 0pt; line-height: 0pt; width: 350px; height: 16px; background-image: url('+path+'i/tip_balloon/t.png);"></div></td><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; width: 16px; line-height: 0pt; vertical-align: bottom;" valign="bottom"><img src="'+path+'i/tip_balloon/rt.png" style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; line-height: 0pt;" height="16" width="16"></td></tr><tr><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; background-repeat: repeat; line-height: 0pt; width: 16px; background-image: url('+path+'i/tip_balloon/l.png);">&nbsp;</td><td style="padding: 4px; position: relative; line-height: normal; background-repeat: repeat; background-image: url('+path+'i/tip_balloon/background.png); color: rgb(0, 0, 0); font-family: Verdana,Geneva,sans-serif; font-size: 8pt; font-weight: normal; text-align: left; width: auto;"><span id="tip_'+alias+'_'+section+'">'+toolTipContent+'</td><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; background-repeat: repeat; line-height: 0pt; width: 16px; background-image: url('+path+'i/tip_balloon/r.png);">&nbsp;</td></tr><tr><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; width: 16px; line-height: 0pt; vertical-align: top;" valign="top"><img src="'+path+'i/tip_balloon/lb.png" style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; line-height: 0pt;" height="16" width="16"></td><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; line-height: 0pt;" valign="top"><div style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; left: 0pt; top: 0pt; line-height: 0pt; width: 350px; height: 16px; background-image: url('+path+'i/tip_balloon/b.png);"></div><img style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; top: -4px; left: 2px; z-index: 1; display: inline; line-height: 0pt;" src="'+path+'i/tip_balloon/stemb.png" height="18" width="34"></td><td style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; position: relative; width: 16px; line-height: 0pt; vertical-align: top;" valign="top"><img src="'+path+'i/tip_balloon/rb.png" style="border: 0pt none ; margin: 0pt; padding: 0pt; overflow: hidden; line-height: 0pt;" height="16" width="16"></td></tr></tbody></table></td></tr></tbody></table></div></div>');

            $(document).bind('mousemove.tips',
            	function(e)
            	{
        			$('.' + toolTipClass).css({
						top: (e.pageY - $('.' + toolTipClass).outerHeight() - 5),
						left: (e.pageX + -35)
        			});

            		// getting mouse relative coordinates
            	    var relativeX = e.pageX - obj.offset().left;
            	    var relativeY = e.pageY - obj.offset().top;
            	    if (
            	    		(relativeX - obj.width()) > 0
            	    		|| (relativeX - obj.width()) < -obj.width()
            	    		|| (relativeY - obj.height()) > 0
            	    		|| (relativeY - obj.height()) < -obj.height()
            	    )
            	    {
            	        $('.' + toolTipClass).stop().hide(0, function(){$('.' + toolTipClass).remove();});
            	    	$(document).unbind('mousemove.tips');
            	    }
            	}
            );


        	$('.' + toolTipClass).css({
        		position: 'absolute',
        		display: 'none',
        		zIndex: '50000',
				top: (obj.offset().top - $('.' + toolTipClass).outerHeight() - 5 - tipMouseCoord.y) + 'px',
				left: (obj.offset().left + obj.outerWidth() + -35 - tipMouseCoord.x) + 'px'
        	})
        	.stop().show();

            $(document).bind('scroll.tips',
                function(e)
                {
        	        $('.' + toolTipClass).stop().hide(0, function(){$('.' + toolTipClass).remove();});
        	    	$(document).unbind('scroll.tips');
                }
            );

            obj.unbind('mouseover', showTip);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.responseText);
            return;
        }
    }
    );


    return;


//    path = Yabsta.Location.themeDir;
//    var tipText = '<div align="center"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>';
//
//    $.ajax(
//        {
//            type: 'POST',
//            async: true,
//            url: '/_ajax/tips/get',
//            data: {alias: alias, section: section},
//            dataType: 'json',
//            success: function (data, textStatus)
//            {
//                tipText = '<strong>'+data.title+'</strong><br/>'+data.description;
//                $('#tip_'+alias+'_'+section).html(tipText);
//            },
//            error: function (XMLHttpRequest, textStatus, errorThrown) {
//                alert(XMLHttpRequest.responseText);
//                return;
//            }
//        }
//    );
//
//    $.getScript(
//        "/js/tip_balloon/wz_tooltip.js",
//        function()
//        {
//            $.getScript(
//                "/js/tip_balloon/tip_balloon.js",
//                function()
//                {
//                    config. BalloonImgPath = path+'i/tip_balloon/';
//                    config. Delay			= 0		// Time span in ms until tooltip shows up
//                    config. Duration		= 0			// Time span in ms after which the tooltip disappears; 0 for infinite duration, < 0 for delay in ms _after_ the onmouseout until the tooltip disappears
//                    config. FadeIn			= 0		// Fade-in duration in ms, e.g. 400; 0 for no animation
//                    config. FadeOut			= 0
//                    config. FadeInterval	= 0		// Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load
//                    Balloon_PreCacheDefImgs();
//                    Tip('<span id="tip_'+alias+'_'+section+'">'+tipText+'</span>', BALLOON, true, OFFSETX, -30);
//                    $(obj).mouseout(function(){
//                        UnTip();
//                    });
//                    // bingind mouse move event
//                    $(document).bind('mousemove.tips',
//                    	function(e)
//                    	{
//                    		// getting mouse relative coordinates
//                    	    var relativeX = e.pageX - $(obj).offset().left;
//                    	    var relativeY = e.pageY - $(obj).offset().top;
//                    	    if (
//                    	    		(relativeX - $(obj).width()) > 0
//                    	    		|| (relativeX - $(obj).width()) < -$(obj).width()
//                    	    		|| (relativeY - $(obj).height()) > 0
//                    	    		|| (relativeY - $(obj).height()) < -$(obj).height()
//                    	    )
//                    	    {
//                    	    	UnTip();
//                    	    	$(document).unbind('mousemove.tips');
//                    	    }
//                    	}
//                    );
//                }
//            );
//        }
//    );
//
//    return;
}

function showTipModal(alias, section, obj, path)
{
        var atitle = '';

        //alert(id);
        $('#dialog').html('<div class="shadow_right"><div class="backg_white" id="content">Please wait. Loading...</div></div>');
        $('#dialog').dialog({
                bgiframe: true,
                resizable:false,
                close:function(){
                        $(this).dialog('destroy');
                },
                open:function(){
                        $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                        $('button',$(this).parent()).each(function(i){
                            /*if (i==0) {
                                $(this).attr({'class':'save'});
                            }else if(i==1){
                                $(this).attr({'class':'save'});
                            }
*/
                            $(this).hide();
                        });

                            $.ajax(
                            {
                                type: 'POST',
                                async: true,
                                url: '/_ajax/tips/get',
                                data: {alias: alias, section: section},
                                dataType: 'json',
                                success: function (data, textStatus)
                                {
                                    toolTipContent = data.description;
                                    $('#content',$('#dialog')).html(toolTipContent);
                                    $('.ui-dialog-title').text(data.title);
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    alert(XMLHttpRequest.responseText);
                                    return;
                                }
                            }
                            );

                },
                height:350,
                width:550,
                modal: true,
                closeText:'',
                overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                },
                title: atitle,
                buttons: {
                    'c': function() {
                        $(this).dialog('destroy');
                    }

                }
        });
}



function findUser(form_id,name,format)
{
    if(name!=undefined && name.length>0)
    {
        $('#'+form_id+'_findUser_results').css('display','none');
        $('#'+form_id+'_findUser_button').css('display','none');
        $('#'+form_id+'_findUser_results_loading').css('display','inline');

        if($('input[@name=\''+form_id+'_findUser_option\']:checked'))
        {
            option = $('input[@name=\''+form_id+'_findUser_option\']:checked').val();

            if(option==undefined)
            {
                option = 0;
            }
        }
        else
        {
            option = 0;
        }

        $.post('/_ajax/user/find_user/'+Math.random(), {
            "name": name,
            "option": option,
            "format": format
            },
            function(data){
                $('#'+form_id+'_findUser_results_loading').css('display','none');
                $('#'+form_id+'_findUser_button').css('display','inline');
                $('#'+form_id+'_findUser_results').html(data).css('display','inline');
            });
    }
    else
    {
        $('#'+form_id+'_findUser_results').html('<option disabled="disabled">Please type first letters of user name</option>');
    }
}



//function findUserBusiness(form_id,name,format)
//{
//    if(name!=undefined && name.length>0)
//    {
//        $('#'+form_id+'_findUserBusiness_results').css('display','none');
//        $('#'+form_id+'_findUserBusiness_button').css('display','none');
//        $('#'+form_id+'_findUserBusiness_results_loading').css('display','inline');
//
//        if($('input[@name=\''+form_id+'_findUserBusiness_option\']:checked'))
//        {
//            option = $('input[@name=\''+form_id+'_findUserBusiness_option\']:checked').val();
//
//            if(option==undefined)
//            {
//                option = 0;
//            }
//        }
//        else
//        {
//            option = 0;
//        }
//
//        $.post('/_ajax/business/find_user_business/'+Math.random(), {
//            "name": name,
//            "option": option,
//            "format": format
//            },
//            function(data){
//                $('#'+form_id+'_findUser_results_loading').css('display','none');
//                $('#'+form_id+'_findUser_button').css('display','inline');
//                $('#'+form_id+'_findUser_results').html(data).css('display','inline');
//            });
//    }
//    else
//    {
//        $('#'+form_id+'_findUser_results').html('<option disabled="disabled">Please type first letters of user name</option>');
//    }
//}

function findUserIMS(form_id,name,format)
{
    if(name!=undefined && name.length>0)
    {
        $('#'+form_id+'_findUser_results').css('display','none');
        $('#'+form_id+'_findUser_button').css('display','none');
        $('#'+form_id+'_findUser_results_loading').css('display','inline');

        if($('input[@name=\''+form_id+'_findUser_option\']:checked'))
        {
            option = $('input[@name=\''+form_id+'_findUser_option\']:checked').val();

            if(option==undefined)
            {
                option = 0;
            }
        }
        else
        {
            option = 0;
        }

        $.post('/_ajax/user/find_user_ims/'+Math.random(), {
            "name": name,
            "option": option
            },
            function(data){
                $('#'+form_id+'_findUser_results_loading').css('display','none');
                $('#'+form_id+'_findUser_button').css('display','inline');
                $('#'+form_id+'_findUser_results').html(data).css('display','inline');
            });
    }
    else
    {
        $('#'+form_id+'_findUser_results').html('<option disabled="disabled">Please type first letters of user name</option>');
    }
}
function findUserFilter(form_id,name,format)
{
    if(name!=undefined && name.length>0)
    {
        $('#'+form_id+'_findUser_results').css('display','none');
        $('#'+form_id+'_findUser_button').css('display','none');
        $('#'+form_id+'_findUser_results_loading').css('display','inline');

        if($('input[@name=\''+form_id+'_findUser_option\']:checked'))
        {
            option = $('input[@name=\''+form_id+'_findUser_option\']:checked').val();

            if(option==undefined)
            {
                option = 0;
            }
        }
        else
        {
            option = 0;
        }

        $.post('/_ajax/user/find_user_filter/'+Math.random(), {
            "name": name,
            "option": option
            },
            function(data){
                $('#'+form_id+'_findUser_results_loading').css('display','none');
                $('#'+form_id+'_findUser_button').css('display','inline');
                $('#'+form_id+'_findUser_results').html(data).css('display','inline');
            });
    }
    else
    {
        $('#'+form_id+'_findUser_results').html('<option disabled="disabled">Please type first letters of user name</option>');
    }
}
function findSalesUser(form_id,name,format,location_id, rbac_id, role_id)
{
    if(name!=undefined && name.length>0)
    {
        $('#'+form_id+'_findSalesUser_results').css('display','none');
        $('#'+form_id+'_findSalesUser_button').css('display','none');
        $('#'+form_id+'_findSalesUser_results_loading').css('display','inline');

        if($('input[@name=\''+form_id+'_findSalesUser_option\']:checked'))
        {
            option = $('input[@name=\''+form_id+'_findSalesUser_option\']:checked').val();

            if(option==undefined)
            {
                option = 0;
            }
        }
        else
        {
            option = 0;
        }

        $.post('/_ajax/user/find_sales_user/'+Math.random(), {
            "name": name,
            "option": option,
            "format": format,
            "location_id": location_id,
            "rbac_id": rbac_id,
            "role_id": role_id
            },
            function(data){
                $('#'+form_id+'_findSalesUser_results_loading').css('display','none');
                $('#'+form_id+'_findSalesUser_button').css('display','inline');
                $('#'+form_id+'_findSalesUser_results').html(data).css('display','inline');
            });
    }
    else
    {
        $('#'+form_id+'_findSalesUser_results').html('<option disabled="disabled">Please type first letters of user name</option>');
    }
}

function findUser_Select(form_id,option,callback)
{

    if(!(option!=undefined && option>0))
    {
        option = 1;
    }

    if($('#'+form_id+'_findUser_results').val()!=null)
    {
        var user_id = $('#'+form_id+'_findUser_results').val();

        if (typeof(user_id) == 'string' && user_id == 'Please type first letters of user name') return false;
        if (typeof(user_id) == 'string' && user_id == 'Empty :-(') return false;

        if(option==1)
        {
            text = '<div class="user_results">' + $('#'+form_id+'_findUser_results option:selected').text() + '</div>';
        }
        else
        {
            text = '<div class="user_results">' +  $('#'+form_id+'_findUser_results option:selected').text() + '</div>';
        }
        text += '<button type="submit" value="Change user1" class="change float_right" onClick="return findUser_ChangeUser(\''+form_id+'\');"></button>';

        $('#'+form_id+'_findUser_div').css('display','none');
        $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
        $('#'+form_id+'_userid').attr('value',user_id);
		/*if(form_id=='addedit_ad'){
			$.post('/_ajax/business/find_user_businesses/'+Math.random(), {
	            "user_id": user_id
            },
            function(data){
            	 $('#ad_business_container_div').html(data);
            });
		}*/
        if(callback)
        {
            callback(user_id);
        }
    }
    else return false;
}

function findSalesUser_Select(form_id,option,callback, location_id, rbac_id, role_id)
{
    if(!(option!=undefined && option>0))
    {
        option = 1;
    }

    if($('#'+form_id+'_findSalesUser_results').val()!=null)
    {
        var user_id = $('#'+form_id+'_findSalesUser_results').val();

        if (typeof(user_id) == 'string' && user_id == 'Please type first letters of user name') return false;
        if (typeof(user_id) == 'string' && user_id == 'Empty :-(') return false;

        if(option==1)
        {
            text = '<div class="float_left wid265 pad5r">' + $('#'+form_id+'_findSalesUser_results option:selected').text() + '</div>';
        }
        else
        {
            text = '<div class="user_results">' +  $('#'+form_id+'_findSalesUser_results option:selected').text() + '</div>';
        }
        text += '<button type="submit" value="Change user1" class="change float_right" onClick="return findSalesUser_ChangeUser(\''+form_id+'\');"></button><button type="submit" value="Clear user3" class="clear float_right" onClick="$(\'#'+form_id+'_salesuserid\').attr(\'value\',0); return findSalesUser_ChangeUser(\''+form_id+'\'); ;"></button>';

        $('#'+form_id+'_findSalesUser_div').css('display','none');
        $('#'+form_id+'_findSalesUser_resultdiv').html(text).css('display','inline');
        $('#'+form_id+'_salesuserid').attr('value',user_id);

        if(callback)
        {
            callback(user_id);
        }
    }
    else return false;
}


function findUser_SelectIMS(form_id)
{



    if($('#'+form_id+'_findUser_results').val()!=null || $('#address_book_select').val()!=null)
    {
        if($('#'+form_id+'_findUser_results option').size() > 1)
        {
            var user_login = $('#'+form_id+'_findUser_results').val();
            text = '<div class="float_left pad5r" style="width:305px;padding:5px 0;">' + $('#'+form_id+'_findUser_results option:selected').text() + '</div>';
        }
        else
        {
            var user_login =  $('#address_book_select').val();
            text = '<div class="float_left pad5r" style="width:305px;padding:5px 0;">' + $('#address_book_select option:selected').text() + '</div>';
        }


        text += '<button type="submit" value="Change user 4" class="change float_righ" onClick="return findUser_ChangeUser(\''+form_id+'\');"></button>';

        $('#'+form_id+'_findUser_div').css('display','none');
        $('#address_book_select').css('display','none');

        $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
        $('#message_user_login').attr('value',user_login);
    }
}

function findUser_SelectFilter(form_id)
{

    if($('#'+form_id+'_findUser_results').val()!=null)
    {
        var user_login = $('#'+form_id+'_findUser_results').val();

        text = '<div class="float_left pad5r" style="width:305px;padding:5px 0;">' + $('#'+form_id+'_findUser_results option:selected').text() + '</div>';
        text += '<button type="submit" value="Change user 4" class="change float_righ" onClick="return findUser_ChangeUserFilter(\''+form_id+'\');"></button>';

        $('#'+form_id+'_findUser_div').css('display','none');
        $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
        $('#'+form_id+'_message_user_login').attr('value',user_login);
    }
}
function findUser_ChangeUser(form_id)
{
	/*if(form_id=='addedit_ad'){

		 //$('#ad_business_container_div').empty().css('display','none');
		 $('#ad_business_container_div').html('<select name="ad[business]" id="ad_business" size="1" ><option value="0">Empty</option></select>');
	}*/

    $('#'+form_id+'_findUser_resultdiv').empty().css('display','none');
    $('#'+form_id+'_findUser_username').attr('value','');
    findUser(form_id,'');
    $('#'+form_id+'_findUser_div').css('display','inline');
    $('#address_book_select').css('display','inline');


    return false;
}
function findUser_ChangeUserFilter(form_id)
{
	/*if(form_id=='addedit_ad'){

		 //$('#ad_business_container_div').empty().css('display','none');
		 $('#ad_business_container_div').html('<select name="ad[business]" id="ad_business" size="1" ><option value="0">Empty</option></select>');
	}*/

    $('#'+form_id+'_findUser_resultdiv').empty().css('display','none');
    $('#'+form_id+'_findUser_username').attr('value','');
    findUser(form_id,'');
    $('#'+form_id+'_findUser_div').css('display','inline');
	$('#'+form_id+'_message_user_login').attr('value','');
    return false;
}
function findSalesUser_ChangeUser(form_id)
{
    $('#'+form_id+'_findSalesUser_resultdiv').empty().css('display','none');
    $('#'+form_id+'_findSalesUser_username').attr('value','');
    findSalesUser(form_id,'');
    $('#'+form_id+'_findSalesUser_div').css('display','inline');
    return false;
}


function findUser_UserKnown(form_id,user_id,user_text)
{

    text = '<div class="user_results">' + user_text + '</div><button type="submit" value="Change user3" class="change float_right" onClick="return findUser_ChangeUser(\''+form_id+'\');"></button>';

    $('#'+form_id+'_findUser_div').css('display','none');
    $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
    $('#'+form_id+'_userid').attr('value',user_id);
    return false;
}

function findSalesUser_UserKnown(form_id,user_id,user_text)
{
    text = '<div class="user_results">' + user_text + '</div><button type="submit" value="Change user3" class="change float_right" onClick="return findSalesUser_ChangeUser(\''+form_id+'\');"></button>&nbsp;&nbsp;&nbsp;<button type="submit" value="Clear user3" class="clear float_right" onClick="$(\'#'+form_id+'_salesuserid\').attr(\'value\',0); return findSalesUser_ChangeUser(\''+form_id+'\'); ;"></button>';

    $('#'+form_id+'_findSalesUser_div').css('display','none');
    $('#'+form_id+'_findSalesUser_resultdiv').html(text).css('display','inline');
    $('#'+form_id+'_salesuserid').attr('value',user_id);
    return false;
}

function findUser_UserKnownIMS(form_id,user_login,user_text)
{
    text =  '<div class="float_left pad5r" style="width:305px;padding:5px 0;">' + user_text + '</div><button type="submit" value="Change user2" class="change float_left" onClick="return findUser_ChangeUser(\''+form_id+'\');"></button>';

    $('#'+form_id+'_findUser_div').css('display','none');
    $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
    $('#message_user_login').attr('value',user_login);
    return false;
}

function findUser_UserKnownFilter(form_id,user_login,user_text)
{
    text =  '<div class="float_left pad5r" style="width:305px;padding:5px 0;">' + user_text + '</div><button type="submit" value="Change user2" class="change float_left" onClick="return findUser_ChangeUser(\''+form_id+'\');"></button>';

    $('#'+form_id+'_findUser_div').css('display','none');
    $('#'+form_id+'_findUser_resultdiv').html(text).css('display','inline');
    $('#'+form_id+'message_user_login').attr('value',user_login);
    return false;
}

function bookmark_this_page()
{
    if (window.sidebar)
    {
        window.sidebar.addPanel(document.title, self.location, "");
    }
    else if(window.opera && window.print)
    {
        var elem = document.createElement('a');
        elem.setAttribute("href",self.location);
        elem.setAttribute("title",document.title);
        elem.setAttribute("rel","sidebar");
        elem.click();
    }
    else if(document.all)
    {
        window.external.AddFavorite(self.location, document.title);
    }
}

function check_browser()
{
    if(window.sidebar || (window.opera && window.print) || document.all)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function duplicate_listing(location_id, listing_id)
{

    if(confirm('Are you sure you wish to duplicate this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/listings/duplicate_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id
            },
            function(data){
                if(data=='1')
                {
                    $("#listing_"+location_id+"_"+listing_id+"_duplicate").html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Listing was successfully duplicated.</div>');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id+"_duplicate").html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when duplicating the listing.</div>');
                }
            });
    }
    return false;
}

function delete_listing(location_id, listing_id)
{

    if(confirm('Are you sure you wish to delete this listing? All listing data will be lost.') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/listings/delete_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id
            },
            function(data){
                if(data=='1')
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Listing was successfully deleted.</div>');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the listing.</div>');
                }
            });
    }
    return false;
}


function delete_classified(location_id,classified_id)
{

	if(confirm('Are you sure you wish to delete this classified? All classified data will be lost.') == false)
	{
		return false;
	}

	if(location_id!=undefined && classified_id!=undefined)
	{
		$("#classified_id_"+location_id+"_"+classified_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

	    $.post('/_ajax/classifieds/delete_classified/'+Math.random(), {
	        "location_id": location_id,
	        "classified_id": classified_id
	        },
	        function(data)
	        {
	        	if(data=='1')
	        	{
					$("#classified_id_"+location_id+"_"+classified_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Classified was successfully deleted.</div>');
				}
				else
				{
					$("#classified_id_"+location_id+"_"+classified_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the classified.</div>');
				}
	        });
	}
	return false;
}

function delete_blog(location_id,id)
{

	if(confirm('Are you sure you wish to delete this blog?') == false)
	{
		return false;
	}

	if(location_id!=undefined && id!=undefined)
	{
		$("#blog_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

	    $.post('/_ajax/cp_blogs/delete_posts/'+Math.random(), {
	        "location_id": location_id,
	        "posts": id
	        },
	        function(data)
	        {
	        	if(data=='')
	        	{
					$("#blog_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Blog was successfully deleted.</div>');
				}
				else
				{
					$("#blog_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the blog.</div>');
				}
	        });
	}
	return false;
}

function delete_event(location_id,id)
{
	if(confirm('Are you sure you wish to delete this event?') == false)
	{
		return false;
	}

	if(location_id!=undefined && id!=undefined)
	{
		$("#event_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

	    $.post('/_ajax/cp_events/delete_events/'+Math.random(), {
	        "location_id": location_id,
	        "events": id
	        },
	        function(data)
	        {
	        	if(data=='')
	        	{
					$("#event_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Event was successfully deleted.</div>');
				}
				else
				{
					$("#event_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the event.</div>');
				}
	        });
	}
	return false;
}

/**
 * Delete an event which is owned to the current user. In other words the user can
 * remove only his own events.
 *
 */
function delete_current_user_event(locationId, id)
{
    if(!confirm('Are you sure you wish to delete this event?')) {
        return false;
    }

    if((locationId != undefined) && (id != undefined)) {
        $("#event_" + locationId + "_" + id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="' + Yabsta.Location.themeDir + 'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        var eventService = jQuery.Zend.jsonrpc({url: '/api/jsonrpc/event'});
        var isEventDeleted = eventService.deleteCurrentUserEvent(id);

        if (isEventDeleted) {
            $("#event_" + locationId + "_" + id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Event was successfully deleted.</div>');
        } else {
            $("#event_" + locationId + "_" + id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the event.</div>');
        }
    }
    return false;
}

function delete_news(location_id,id)
{
	if(confirm('Are you sure you wish to delete this news?') == false)
	{
		return false;
	}

	if(location_id!=undefined && id!=undefined)
	{
		$("#news_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

	    $.post('/_ajax/cp_news/delete_news/'+Math.random(), {
	        "location_id": location_id,
	        "news": id
	        },
	        function(data)
	        {
	        	if(data=='')
	        	{
					$("#news_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">News was successfully deleted.</div>');
				}
				else
				{
					$("#news_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the news.</div>');
				}
	        });
	}
	return false;
}

function delete_blog_comment(location_id,id)
{

	if(confirm('Are you sure you wish to delete this blog comment?') == false)
	{
		return false;
	}

	if(location_id!=undefined && id!=undefined)
	{
		$("#blog_comment_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

	    $.post('/_ajax/cp_blogs/delete_comments/'+Math.random(), {
	        "location_id": location_id,
	        "comments": id
	        },
	        function(data)
	        {
	        	if(data=='')
	        	{
					$("#blog_comment_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Blog comment was successfully deleted.</div>');
				}
				else
				{
					$("#blog_comment_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the blog comment.</div>');
				}
	        });
	}
	return false;
}

function delete_discussion(location_id, id)
{

    if(confirm('Are you sure you wish to delete this discussion post?') == false)
    {
        return false;
    }

    if(location_id!=undefined && id!=undefined)
    {
        $("#discussion_post_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/cp_discussions/delete_posts/'+Math.random(), {
            "location_id": location_id,
            "posts": id
            },
            function(data){

                if(data=='1')
                {

                    $("#discussion_post_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Discussion post was successfully deleted.</div>');
                }
                else
                {
                    $("#discussion_post_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured while deleting this post.</div>');
                }
            });
    }
    return false;
}



function delete_reply(location_id, id)
{

    if(confirm('Are you sure you wish to delete this discussion reply?') == false)
    {
        return false;
    }

    if(location_id!=undefined && id!=undefined)
    {
        $("#discussion_reply_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/cp_discussions/delete_replies/'+Math.random(), {
            "location_id": location_id,
            "replies": id
            },
            function(data){
                if(data=='1')
                {
                    $("#discussion_reply_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Discussion reply was successfully deleted.</div>');
                }
                else
                {
                    $("#discussion_reply_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured while deleting this comment.</div>');
                }
            });
    }
    return false;
}


function delete_website(site_id, location_id)
{
    if(confirm('Are you sure you wish to delete this website? All website data will be lost.') == false)
    {
        return false;
    }

    if(location_id!=null && location_id != 'undefiend' && site_id!=null && site_id != 'undefined')
    {
        $("#website_"+site_id+"_"+location_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/websitebuilder/delete_website/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
                if(data=='1')
                {
                    $("#website_"+site_id+"_"+location_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Website was successfully deleted.</div>');
                }
                else
                {
                    $("#website_"+site_id+"_"+location_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the website.</div>');
                }
            });
    }
    return false;
}

function publish_website(site_id, location_id)
{
    if (confirm('Are you sure you want to publish this website?') == false)
    {
        return false;
    }
    if(location_id>-1 && site_id>0)
    {
        $.post('/_ajax/websitebuilder/publish_website/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
                $("#website_"+site_id+"_"+location_id).replaceWith(data);
            });
    }
    return false;
}

function turnon_website(site_id, location_id)
{
    if (confirm('Are you sure you want to turn on this website?') == false)
    {
        return false;
    }
    if(location_id>-1 && site_id>0)
    {
        $.post('/_ajax/websitebuilder/turnon_website/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
                $("#website_"+site_id+"_"+location_id).replaceWith(data);
            });
    }
    return false;
}

function turnoff_website(site_id, location_id)
{
    if (confirm('Are you sure you want to turn off this website?') == false)
    {
        return false;
    }
    if(location_id>-1 && site_id>0)
    {
        $.post('/_ajax/websitebuilder/turnoff_website/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
                $("#website_"+site_id+"_"+location_id).replaceWith(data);
            });
    }
    return false;
}

function duplicate_website(site_id, location_id)
{
    if (confirm('Are you sure you want to create copy of this website?') == false)
    {
        return false;
    }
    if(location_id!=null && location_id != 'undefiend' && site_id!=null && site_id != 'undefined')
    {
        $.post('/_ajax/websitebuilder/duplicate_website/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
                $("#website_"+site_id+"_"+location_id).after(data);
            });
    }

    return false;
}

function setprice_website(site_id, curr_price, location_id)
{
    if(location_id!=null && location_id != 'undefiend' && site_id!=null && site_id != 'undefined')
    {
        var d = document.getElementById('dialog');
        if (d == null || d == 'undefiend')
        {
            $('body').append('<div id="dialog" style="display:none;"></div>');
        }
		$('#dialog').html('<div class="shadow_right"><div class="backg_white" id="content"><input type="text" name="website_price" id="website_price" value="'+curr_price+'" class="wid150" /></div></div>');
		$('#dialog').dialog({
			bgiframe: true,
			resizable:false,
			close:function(){
				$(this).dialog('destroy');
			},
			open:function(){
				$('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
				$('button',$(this).parent()).each(function(i){
					if (i==0) {
						$(this).attr({'class':'save'});
					}
					else if(i==1){
						$(this).attr({'class':'cancel'});
					}
				});

			},
			height:50,
			width:185,
			modal: true,
			closeText:'',
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			title: 'Setting website price',
			buttons: {
				'e': function() {
				    if ($('#website_price').val() == '')
				    {
				        return false;
				    }
                    $.post('/_ajax/websitebuilder/setprice_website/'+Math.random(), {
                        "location_id": location_id,
                        "site_id": site_id,
                        "price": $('#website_price').val()
                        },
                        function(data){
                            $("#website_"+site_id+"_"+location_id).replaceWith(data);
                        });
                    $(this).dialog('destroy');
				},
				'c': function() {
					$(this).dialog('destroy');
				}
			}
		});
    }

    return false;
}


function get_temporary_url_website(site_id, curr_url, location_id)
{
    if(location_id!=null && location_id != 'undefiend' && site_id!=null && site_id != 'undefined')
    {
        $.post('/_ajax/websitebuilder/get_temporary_url/'+Math.random(), {
            "location_id": location_id,
            "site_id": site_id
            },
            function(data){
//                $("#website_"+site_id+"_"+location_id).replaceWith(data);

                var d = document.getElementById('dialog');
                if (d == null || d == 'undefiend')
                {
                    $('body').append('<div id="dialog" style="display:none;"></div>');
                }
        		$('#dialog').html('<div class="shadow_right"><div class="backg_white" id="content"><input type="text" name="temporary_url" id="temporary_url" value="http://'+curr_url+'/?t='+data+'" class="wid98per" /></div></div>');
        		$('#dialog').dialog({
        			bgiframe: true,
        			resizable:false,
        			close:function(){
        				$(this).dialog('destroy');
        			},
        			open:function(){
        			    $('#temporary_url').focus();
        			    $('#temporary_url').select();
        				$('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
        				$('button',$(this).parent()).each(function(i){
        					if (i==0) {
        						$(this).attr({'class':'cancel'});
        					}
        				});

        			},
        			height:20,
        			width:400,
        			modal: true,
        			closeText:'',
        			overlay: {
        				backgroundColor: '#000',
        				opacity: 0.5
        			},
        			title: 'Website Temporary URL',
        			buttons: {
        				'c': function() {
        					$(this).dialog('destroy');
        				}
        			}
        		});
            });
    }

    return false;
}

function delete_business(location_id,business_id)
{
    if(confirm('Are you sure you wish to delete this business? Business information and all its listings will be lost.') == false)
    {
        return false;
    }

    if(location_id!=undefined && business_id!=undefined)
    {
        $("#business_"+location_id+"_"+business_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/business/delete_business/'+Math.random(), {
            "location_id": location_id,
            "business_id": business_id
            },
            function(data){
                if(data=='1')
                {
                    $("#business_"+location_id+"_"+business_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Business was successfully deleted.</div><script type="text/javascript">setTimeout("location.href = \'/user/business/\';",3000);</script>');
                }
                else
                {
                    $("#business_"+location_id+"_"+business_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when deleting the business.</div>');
                }
            });
    }
    return false;
}
function turnon_ad(location_id, ad_id, element_id, user_id)
{
    if(location_id>-1 && ad_id>0)
    {
        $.post('/_ajax/ad/turnon_ad/'+Math.random(), {
            "location_id": location_id,
            "ad_id": ad_id,
            "user_id" : user_id
            },
            function(data){
                if(parseInt(data)==1)
                {
                    $('#user_ad_'+element_id).css('opacity','1');
                    $('#user_ad_'+element_id).css('filter','alpha(opacity=100)');

                    $('#status_container_'+ad_id).text('active');
                    $('#user_ad_turnoff_'+element_id).html('Turn off').attr('onClick','turnoff_ad(\''+location_id+'\',\''+ad_id+'\',\''+element_id+'\', \''+user_id+'\'); return false;');
                    $('#user_ad_turnoff_'+element_id).toggleClass('turnon',0);
                    $('#user_ad_turnoff_'+element_id).toggleClass('turnoff',1);
                    return true;
                }
            });
    }
}

function turnoff_ad(location_id, ad_id, element_id, user_id)
{
    if(location_id>-1 && ad_id>0)
    {
        if(confirm('Are you sure you want to turn off this banner advertisment?') == false)
        {
            return false;
        }

        $.post('/_ajax/ad/turnoff_ad/'+Math.random(), {
            "location_id": location_id,
            "ad_id": ad_id,
            "user_id":user_id
            },
            function(data){
                if(parseInt(data)==1)
                {
                    $('#user_ad_'+element_id).css('opacity','0.5');
                    $('#user_ad_'+element_id).css('filter','alpha(opacity=50)');

                    $('#status_container_'+ad_id).text('turned off');
                    $('#user_ad_turnoff_'+element_id).html('Turn on').attr('onClick','turnon_ad(\''+location_id+'\',\''+ad_id+'\',\''+element_id+'\', \''+user_id+'\'); return false;');
                    $('#user_ad_turnoff_'+element_id).toggleClass('turnoff',0);
                    $('#user_ad_turnoff_'+element_id).toggleClass('turnon',1);
                    return true;
                }
            });
    }
}

function turnoff_listing(location_id, listing_id, element_id)
{

    if(confirm('Are you sure you want to turn off this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');
        $.post('/_ajax/listings/turnoff_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id

            },
            function(data){
                if(data=='1')
                {
                            $("#"+element_id).css('opacity','0.5');
                                        $("#"+element_id).css('filter','alpha(opacity=50)');
                    $("#listing_"+location_id+"_"+listing_id+"_turn_off").html('<a href="#" onClick="return turnon_listing(\''+location_id+'\',\''+listing_id+'\',\''+'0'+location_id+'0'+listing_id+'\');"  title="Turn on" class="turnon">Turn on</a>');
                    $("#listing_"+location_id+"_"+listing_id+"_status").html('turned off');
                    $("#listing_"+location_id+"_"+listing_id+"_pay").html('');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when turning off the listing.</div>');
                }
            });
    }

    return false;
}

function turnon_listing(location_id, listing_id, element_id)
{
    if(confirm('Are you sure you want to turn on this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');

        $.post('/_ajax/listings/turnon_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id

            },
            function(data){
                if(data=='1'){
                                        //alert($("#"+element_id).attr('class'));

                                        $("#"+element_id).css('opacity','1');
                                        $("#"+element_id).css('filter','alpha(opacity=100)');
                    $("#listing_"+location_id+"_"+listing_id+"_turn_off").html('<a href="#" onClick="return turnoff_listing(\''+location_id+'\',\''+listing_id+'\',\''+'0'+location_id+'0'+listing_id+'\');"  title="Turn off" class="turnoff">Turn off</a>');
                    $("#listing_"+location_id+"_"+listing_id+"_status").html($("#listing_"+location_id+"_"+listing_id+"_active").val());
                    if($("#listing_"+location_id+"_"+listing_id+"_pay_show").val() == 1){

                        $("#listing_"+location_id+"_"+listing_id+"_pay").html('<span class="grey_dashed" ><a href="/user/checkoutlisting/'+location_id+':'+listing_id+'" class="pay" title="Pay">Pay</a></span>');
                    }

                    //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Listing was successfully turned on.</div>');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when turning on the listing.</div>');
                }
            });
    }

    return false;
}

function publish_listing(location_id,listing_id)
{

    if(confirm('Are you sure you want to publish this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');
        $.post('/_ajax/listings/publish_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id

            },
            function(data){
                if(data=='1')
                {

                    $("#listing_"+location_id+"_"+listing_id+"_publish").html('');
                    $("#listing_"+location_id+"_"+listing_id+"_status").html('not approved');
                    //$("#listing_"+location_id+"_"+listing_id+"_pay").html('');
                    //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Success.</div>');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when turning off the listing.</div>');
                }
            });
    }

    return false;
}

function inline_approve(location_id, id, title)
{

    if(confirm('Are you sure you want to approve this '+title+'?') == false)
    {
        return false;
    }

    if(location_id!=undefined && id!=undefined)
    {
    	var controller_title = title;
    	if(title =='reply'){
    		controller_title = 'discussion_reply';
    	}
    	var post_title = "post";
    	if(title == 'website'){
    		post_title = "site_id";
    	}
    	if(title != 'website'){
    		  $.post('/_ajax/cp_moderation/approve_'+controller_title+'/'+Math.random(), {
            "location_id": location_id,
            "post": id

            },
            function(data){

                if(data=='')
                {

                    $("#"+title+"_"+location_id+"_"+id+"_approve").html('');
                    $("#"+title+"_"+location_id+"_"+id+"_decline").html('');
                }
                else
                {
                    $("#"+title+"_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when approve the '+title+'.</div>');
                }
            });
    	}else{
    		  $.post('/_ajax/cp_moderation/approve_'+controller_title+'/'+Math.random(), {
            "location_id": location_id,
            "site_id": id

            },
            function(data){

                if(data=='')
                {

                    $("#"+title+"_"+location_id+"_"+id+"_approve").html('');
                    $("#"+title+"_"+location_id+"_"+id+"_decline").html('');
                }
                else
                {
                    $("#"+title+"_"+location_id+"_"+id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when approve the '+title+'.</div>');
                }
            });
    	}

    }

    return false;
}


function add_to_user_favorites(location_id,item_id,item_type,refresh,container)
{
    if(typeof(container)=='undefined'){
        container='#addtouserfav_'+location_id+'_'+item_id;
    }
    $(container).empty().append('Loading...');

    $.post('/_ajax/user/add_to_user_favorites/'+Math.random(), {
        "location_id":  location_id,
        "item_id":      item_id,
        "item_type":    item_type,
        "refresh":      refresh,
        "container": container
        },
        function(data)
        {
            $(container).empty().append(data);
        }
        );
}

function set_trial_listing(location_id,listing_id)
{

    if(confirm('Are you sure you want to set trial for this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined)
    {
        //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;"><img src="'+Yabsta.Location.themeDir+'i/loadinfo.gif" width="16" height="16" alt="Loading..." title="Loading..." class="c_marg6" align="absmiddle" /> Loading, please wait.</div>');
        $.post('/_ajax/listings/set_trial_listing/'+Math.random(), {
            "location_id": location_id,
            "listing_id": listing_id
            },
            function(data){
                if(data=='1')
                {

                    $("#listing_"+location_id+"_"+listing_id+"_trial").html('');
                    $("#listing_"+location_id+"_"+listing_id+"_pending").html('');
                    $("#listing_"+location_id+"_"+listing_id+"_status").html('trial');
                    //$("#listing_"+location_id+"_"+listing_id+"_pay").html('');
                    //$("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">Success.</div>');
                }
                else
                {
                    $("#listing_"+location_id+"_"+listing_id).html('<div align="center" style="padding-top:120px; padding-bottom:120px;">An error occured when turning off the listing.</div>');
                }
            });
    }

    return false;
}

function getDocumentHeight()
{
  var ua = navigator.userAgent.toLowerCase();
  var isOpera = (ua.indexOf('opera')  > -1);
  var isIE = (!isOpera && ua.indexOf('msie') > -1);
  return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight );
}

function delete_ad(location_id, ad_id, element_id)
{
    if(location_id>-1 && ad_id>0)
    {
        if(confirm('Are you sure you want to delete this banner advertisment?') == false)
        {
            return false;
        }

        $.post('/_ajax/ad/delete_ad/'+Math.random(), {
            "location_id": location_id,
            "ad_id": ad_id
            },
            function(data){
                if(parseInt(data)==1)
                {
                    $('#user_ad_'+element_id).remove();
                    return true;
                }
                else
                {
                    alert(parseInt(data));
                }
            });
    }
}

function order_ad_error(errors, ad_id, location_id) {
    var out = '';
    for(var i in errors) {
        out = out + '<br />' + errors[i];
    }
    $('#dstart').after('<div id="dialog_payment_type_error_' + ad_id + '"><div style="margin : 0px 10px;">' + out + '</div></div>');


        $('#dialog_payment_type_error_'+ad_id).dialog({

            open:function(){
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                    $('button',$(this).parent()).each(function(i){
                       if (i==1) {
						$(this).attr({'class':'edit-btn'});
					   }
					   else if(i==0){
						$(this).attr({'class':'cancel'});
					   }
                    });
           },

            //height:500,
            //width:500,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Banner package not available',
            buttons: {
                'c': function()
                {
                    $(this).dialog('destroy');
                },
                'e': function()
                {
                    document.location.href = '/user/edit_ad/' + location_id + ':' + ad_id;
                    $(this).dialog('destroy');

                }

            }
        });
}
function order_ad(location_id, ad_id, pt)
{

    if(location_id>-1 && ad_id>0)
    {
      var preview_content = '';
      for(value in pt){
       if(value == 1){
           preview_content += '<tr><td><input type="radio" style="margin:2px 0;" name="payment_type_'+ad_id+'" value="'+value+'" checked="checked" /></td><td>&nbsp;&nbsp;'+pt[value]+'</td></tr>';
       }else{
           preview_content += '<tr><td><input type="radio" style="margin:2px 0;" name="payment_type_'+ad_id+'" value="'+value+'" /></td><td>&nbsp;&nbsp;'+pt[value]+'</td></tr>';
       }
      }


        $('#dstart').after('<div id="dialog_payment_type_' + ad_id + '"><table style="margin:10px 0 0 12px;">' + preview_content + '</table></div>');


        $('#dialog_payment_type_'+ad_id).dialog({

            open:function(){
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                    $('button',$(this).parent()).each(function(i){
                       if (i==0) {
						$(this).attr({'class':'submit'});
					   }
					   else if(i==1){
						$(this).attr({'class':'cancel'});
					   }
                    });
           },

            //height:500,
            //width:500,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Select payment type',
            buttons: {
                'e': function()
                {
                   var res = $('input:radio:checked').val();
                   // alert(res);
                    $.post(
                           '/_ajax/orders/order_banner/'+Math.random(),
                            {
                              "ad_id": ad_id,
                              "location_id" : location_id,
                              "payment_type": res
                            },
                            function(data)
                            {
                                if(data.errors) {
                                     order_ad_error(data.errors, ad_id, location_id);

                                }
                                if (data.redirect_url){
                                    document.location.replace(data.redirect_url);
                                }
                            },
                            'json'
                       );
                    $(this).dialog('destroy');



                },
                 'c': function()
                {
                    $(this).dialog('destroy');
                }

            }
        });


    }

}

function show_banners(location_id,section,client_height)
{
    if(location_id!=undefined && location_id>-1 && section!=undefined && section>-1 && client_height!=undefined && client_height>240)
    {
        $('#c_rightcolum').empty();
        $.post('/_ajax/ad/generate/'+Math.random(), {
            "location_id":   location_id,
            "section":       section,
            "client_height": client_height
            },
            function(data)
            {
                $('#c_rightcolum').html(data.content);
                statistics = data.statistics;
                if(typeof(statistics) != "undefined" && statistics != null && statistics != '')
			 	{
                    for(var i = 0; i < statistics.length; i++){
                        $.YF_Stat.add(statistics[i]);
                    }
			 	}

            },
            "json"
        );
    }
}

function getPhone(phone, format)
{

	if(typeof(phone)=='string')
    {
    	if(phone.length>0){
        var phone_clear = '';

        for(i=0; i<=(phone.length-1); i++)
        {
            if(!isNaN(phone[i]))
            {
                phone_clear += phone[i];
            }
        }

        var c = phone_clear.length-1;
        var format_length = format.length-1;
        var phone_format = '';

        for(i=format_length; i>=0; i--)
        {
            if(format[i]=='#')
            {
                if(phone_clear[c]!=undefined && c>=0)
                {
                    phone_format = phone_clear[c]+phone_format;
                    c--;
                }
            }
            else
            {
                phone_format = format[i]+phone_format;
            }
        }
        return phone_format;
    	}
    	else{
    		return '';
    	}
    }
    else
    {
        if(phone['tel'].length>0)
        {
            return (phone['sfix'].length>0 ? phone['sfix'] : 'Phone: ')+' '+phone['tel']+' '+phone['pfix'];
        }
        return '';
    }
}

function getAddress(address, format)
{
	var i;
    var matches = format.toString().match(/\[([^\]]*)\]/g);
    var parts = new Array();
    //var items_keys = new Array();
    var items_values = new Array();

    if(matches)
    {
        /*
        items_keys[items_keys.length] = '%B';
        items_keys[items_keys.length] = '%ST';
        items_keys[items_keys.length] = '%PO';
        items_keys[items_keys.length] = '%T';
        items_keys[items_keys.length] = '%S';
        items_keys[items_keys.length] = '%C';
        items_keys[items_keys.length] = '%PC';
        */
        items_values['%L'] = address['name']!='' ? htmlspecialchars(address['name']) : false;
        items_values['%B'] = address['building']!='' ? htmlspecialchars(address['building']) : false;
        items_values['%ST'] = address['addr']!='' ? htmlspecialchars(address['addr']) : false;
        items_values['%PO'] = address['po_box']!='' ? htmlspecialchars(address['po_box']) : false;
        items_values['%T'] = address['city']!='' ? htmlspecialchars(address['city']) : false;
        items_values['%S'] = address['state']!='' ? htmlspecialchars(address['state']) : false;
        items_values['%C'] = address['country']!='' ? htmlspecialchars(address['country']) : false;
        items_values['%PC'] = address['zip']!='' ? htmlspecialchars(address['zip']) : false;

        for(i in matches)
        {
            tmp = matches[i].toString().match(/%(L|B|ST|PO|T|S|C|PC)/);
            if(tmp /*&& in_array(tmp[0],items_keys)*/ && !!items_values[tmp[0]])
            {
                parts[matches[i]] = substr(matches[i].toString().replace(tmp[0],items_values[tmp[0]]), 1, -1 );
            }
            else
            {
                parts[matches[i]] = '';
            }
        }
        for(i in parts)
        {
            format = format.toString().replace(i, parts[i]);
        }
    }

    return format;
}

function previewPhone(label,number,extension)
{
    var ret = '';

    if(label!=undefined && label.length>0)
    {
        ret += label+': ';
    }
    if(number!=undefined && number.length>0)
    {
        ret += getPhone(number,'(###) ###-####');
    }
    if(extension!=undefined && extension.length>0)
    {
        ret += ' Ext: '+extension;
    }

      return ret;
}
(function($) {

    $.fn.filestyle = function(options) {

        /* TODO: This should not override CSS. */
        var settings = {
            width : 250
        };

        if(options) {
            $.extend(settings, options);
        };

        return this.each(function() {

            var self = this;
            
            if($(this).width()) {
                settings.width = $(this).width();
            }
        
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "left -91px",
"margin-left": settings.width+"px",
"margin-top": "-32px",
                                "display": "inline",
                                /*"float": "right",*/
                                "position": "absolute",
                                "overflow": "hidden"
                            });

      //  alert(settings.width);
            var filename = $('<div class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                                "display": "block",
                                /*"float": "left",*/
                                "font-style":"italic",
                                "height":"30px",
                                "margin-left" : "70px",
                                "font-size":'11px',
                                "width": settings.width + "px"
                               /* "width": "200px"*/
                             }).html(settings.value);

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "relative",
                        "height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        "display": "inline",
                        "cursor": "pointer",
                        "opacity": "0.0"
                    });

            if ($.browser.mozilla) {

                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-122px");
                } else {

                    $(self).css("margin-left", "-148px");
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");
            };
             //$(self).css("margin-left", "0px");
            $(self).bind("change", function() {
                filename.html($(self).val());
            });

        });


    };

})(jQuery);

function setCustomFiles1(force_set){

	if(force_set)
	{
		$(".customFile1").each(function(){
	            if($(this).hasClass('setup'))return;
	            var val='';
	            if(typeof($(this).prev()[0])!='undefined'&&$(this).prev()[0].tagName=='SPAN'){
	                val=$(this).prev().html();
	                $(this).prev().remove();
	            }
	            $(this).addClass('setup');
	            $(this).filestyle({
	              image: "/themes/1/i/buttons.png",
	              imageheight : 21,
	              imagewidth : 66,
	              width : 240,
	              value    : val
	           });
	        });
	}
	else
	{
		$(document).ready(function() {
    			$(".customFile1").each(function(){
	                if($(this).hasClass('setup'))return;
	                var val='';
	                if(typeof($(this).prev()[0])!='undefined'&&$(this).prev()[0].tagName=='SPAN'){
	                    val=$(this).prev().html();
	                    $(this).prev().remove();
	                }
	                $(this).addClass('setup');
	                $(this).filestyle({
	                  image: "/themes/1/i/buttons.png",
	                  imageheight : 21,
	                  imagewidth : 66,
	                  width : 240,
	                  value    : val
	               });

	        });
    	});
	}
}

function setCustomFiles(force_set)
{
	if(force_set)
	{
		setCustomFiles1(force_set);
	    	$(".customFile")
	               .each(function (){
	               	   		if(typeof($('.FileName',$(this).parent()[0])[0])=='undefined'){
	                            $d=$('<div>').attr({className:'FileName'}).insertAfter(this);
	                            if(typeof($(this).prev()[0])!='undefined'&&$(this).prev()[0].tagName=='SPAN'){
	                                $d.html($(this).prev().html());
	                                $(this).prev().remove();
	                            }
	                            $('<div>').attr({className:'fakeButton activeBrowseButton'}).insertAfter(this);
	                            $('<div>').attr({className:'blocker'}).insertAfter(this);
	                            $('<div>').attr({className:'fakeButton'}).insertAfter(this);
	                        }
	                }).change(function(){
	                    var fileNameEl=$('.FileName',$(this).parent()[0]);
	                    file = $(this).val();

	                    reWin = /.*\\(.*)/;
	                    var fileTitle = file.replace(reWin, "$1");
	                    reUnix = /.*\/(.*)/;
	                    fileTitle = fileTitle.replace(reUnix, "$1");
	                    fileNameEl.html(fileTitle);

	                    var RegExExt =/.*\.(.*)/;
	                    var ext = fileTitle.replace(RegExExt, "$1");

	                    var pos;

	                    if (ext){
	                        fileNameEl.show();
	                    };
	                });
	}
	else
	{
		$(document).ready(function() {
    		setCustomFiles1();
	    	$(".customFile")
	                   .each(function (){
                   	   			if(typeof($('.FileName',$(this).parent()[0])[0])=='undefined'){
	                                $d=$('<div>').attr({className:'FileName'}).insertAfter(this);
	                                if(typeof($(this).prev()[0])!='undefined'&&$(this).prev()[0].tagName=='SPAN'){
	                                    $d.html($(this).prev().html());
	                                    $(this).prev().remove();
	                                }
	                                $('<div>').attr({className:'fakeButton activeBrowseButton'}).insertAfter(this);
	                                $('<div>').attr({className:'blocker'}).insertAfter(this);
	                                $('<div>').attr({className:'fakeButton'}).insertAfter(this);
	                            }
	                    }).change(function(){
	                        var fileNameEl=$('.FileName',$(this).parent()[0]);
	                        file = $(this).val();

	                        reWin = /.*\\(.*)/;
	                        var fileTitle = file.replace(reWin, "$1");
	                        reUnix = /.*\/(.*)/;
	                        fileTitle = fileTitle.replace(reUnix, "$1");
	                        fileNameEl.html(fileTitle);

	                        var RegExExt =/.*\.(.*)/;
	                        var ext = fileTitle.replace(RegExExt, "$1");

	                        var pos;

	                        if (ext){
	                            fileNameEl.show();
	                        };
	                    });
	         });
	}
}



/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('r.5=w(k,d,a){4(m d!=\'H\'){a=a||{};4(d===p){d=\'\';a.3=-1}2 g=\'\';4(a.3&&(m a.3==\'n\'||a.3.u)){2 f;4(m a.3==\'n\'){f=G E();f.C(f.B()+(a.3*z*s*s*v))}o{f=a.3}g=\'; 3=\'+f.u()}2 b=a.7?\'; 7=\'+(a.7):\'\';2 e=a.9?\'; 9=\'+(a.9):\'\';2 l=a.t?\'; t\':\'\';6.5=[k,\'=\',K(d),g,b,e,l].I(\'\')}o{2 h=p;4(6.5&&6.5!=\'\'){2 c=6.5.F(\';\');D(2 i=0;i<c.8;i++){2 j=r.A(c[i]);4(j.q(0,k.8+1)==(k+\'=\')){h=y(j.q(k.8+1));x}}}J h}};',47,47,'||var|expires|if|cookie|document|path|length|domain|||||||||||||typeof|number|else|null|substring|jQuery|60|secure|toUTCString|1000|function|break|decodeURIComponent|24|trim|getTime|setTime|for|Date|split|new|undefined|join|return|encodeURIComponent'.split('|'),0,{}))

rval = 0;
function grid_pager(url,table_id,page,order_field,order_direction){if(rval == 0){rval=10;}$.get(url+table_id+':'+page+':'+order_field+':'+order_direction+':'+rval, {},function(data){$('#'+table_id).empty().append(data);});}
function grid_filter(url,table_id,text){$.get(url+table_id+':filter:'+text,{},function(data){$('#'+table_id).empty().append(data);});}
function getTableIds(){s = new String();$(':checkbox').each(function(i){if(this.checked){if(s.length > 0){s = s+':';}s = s+this.name;}});return s;}

function grid_selected_del(link){s=getTableIds();if(s.length>0){if(confirm('Are you sure?')==false){return;}getCenterContent(link+s);}}

function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

setCustomFiles();

function file_uploader(item_id, upload_url, content_type, session_key, file_post_name, files_types, file_types_description, file_upload_limit, debug)
{
    var swf_obj;

    swf_obj = new SWFUpload({
        upload_url: upload_url,
        file_post_name: file_post_name,
        post_params: {'CONTENT_TYPE' : content_type, 'SESSION_KEY' : session_key},

        file_size_limit : "5 MB",
        file_types : files_types,
        file_types_description : file_types_description,
        file_upload_limit : file_upload_limit,

        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_progress_handler : uploadProgressOld,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadCompleteImage,

        // Button Settings
        button_image_url : "/themes/1/i/button_upload.gif",
        button_placeholder_id : "spanImageFileButtonPlaceholder"+item_id,
        button_width: 72 ,
        button_height: 22,
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_cursor: SWFUpload.CURSOR.HAND,

        // Flash Settings
        flash_url : "/js/swfupload/swfupload.swf",

        custom_settings : {
            upload_target : "divImageFileProgressContainer"+item_id,
            progressTarget : "divImageFileProgressContainer"+item_id
        },

        // Debug Settings
        debug: false
    });
}
function printImage(img_id)
{
var iamgeId = document.getElementById(img_id);
var imagObject = new Image();
imagObject = iamgeId;
var originalImage = '<div style="vertical-align:middle;text-align:center"><img align="middle" valign="middle" id="imageViewer" src="'+imagObject.src+'" height="'+imagObject.height+'" width="'+imagObject.width+'" /></div>';

popup = window.open('','coupon','toolbar=no,menubar=no,width='+imagObject.width+',height='+imagObject.height+'');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
popup.document.close();
} 
var pwin;
function image_print(id) {
    pwin = window.open(document.getElementById(id).src,"_blank");
    setTimeout("pwin.print(); pwin.close();",20);
}

function incFeatureClick(statistics, is_search, link, feature)
{
    var _ret = true;
	if(is_search == 1 && statistics)
	{

        $.post('/stat/content/', {
                'statistics' : statistics
            },
            function() {
                if(feature == 1)
                {
                    location.href = link;
                }
            }
        );
        _ret = false;
	}
    else if(feature == 1)
    {
        location.href = link;
    }
    if(feature == 7)
    {
        window.open(link, '');
    }
	return _ret;
}
function photo_impression_ajax(statistics)
{
    $.post('/stat/content/', {
                    'statistics' : statistics
            }, function(data){
                }
                );
}
function video_impression(video_id, stats_info)
{

    $.post('/stat/content/', {
                    'statistics' : stats_info
            }, function(data){
                }
                );
}
function incRelatedClick(statistics, link)
{

	    $.post('/stat/content/', {
	        	'statistics[]' : statistics
	        }, function(data){

		   	location.href = link;
		  }
	    );
}
function changeLocation(location_id, url)
{
	$.blockUI({message: '<h3>Please, wait...</h3>'});
	location.href = '/user/toloc/'+location_id+'/'+encodeURIComponent(url);

}
function changeLocationForm(location_id, url, sublocation_id)
{
	if($('#'+sublocation_id).val() == null)
	{
		changeLocation(location_id, url)
	}
}


function aSwap(arr, key1, key2){
    if(arr[key1]==undefined || arr[key2]==undefined) return arr;
    var v1 = arr[key1];
    var v2 = arr[key2];
    var narr = new Array();
    var k_prev = null;
    var k1 = null;
    var k2 = null;
    for(var k in arr){
        if(key1 == k){
            k1 = k_prev;
        }
        if(key2 == k){
            k2 = k_prev;
        }
        k_prev = k;
    }

    if(k1 == null){
        narr[key2]=v2;
    }

    if(k2 == null){
        narr[key1]=v1;
    }

    for(var k in arr){
        if(!(k==key1 || k==key2)) {
         narr[k] = arr[k];
        }
        if(k1==k){
            narr[key2]=v2;
        }
        if(k2==k){
            narr[key1]=v1;
        }
    }
    return narr;
}
function serialize (mixed_value) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'

    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {
                    continue;
                }

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}
function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function errorImage(event,queueID,fileObj,errorObj)
{
    alert(errorObj.type + ' ' + errorObj.info);
}
function  cropImage2(location_id, photo_id){
     var config={};
    config.dataSource='/_ajax/multimedia/cropPhoto';
    config.dataParams={id:photo_id, 'thumb':0, 'edit_mode':0,location : location_id};
    cropImage(config)
}
function  cropThumbImage2(location_id, photo_id){
     var config={};
    config.dataSource='/_ajax/multimedia/cropPhoto';
    config.dataParams={id:photo_id, 'thumb':1, 'edit_mode':0,location : location_id};
    cropThumbImage(config)
}
function cropImage(config){

     var edit_mode=($('#lf_photos_photo_'+config.dataParams.id+'_image_cropinfo_hidden').val()=='')?0:1;

     var btn_crop=function() {

                         $('#viewCropDialog').html('<div class="shadow_right"><div class="backg_white" id="content"><img src="/themes/1/i/loadinfo.gif"  align="center"></div></div>');
                         var _this=$(this);
                         $.post('/_ajax/multimedia/croppingPhoto',{crop_area:$('#lf_photos_photo_'+config.dataParams.id+'_image_cropinfo_hidden').val(),index:config.dataParams.id,thumb:0, location_id:config.dataParams.location,edit_mode:edit_mode},function(data){
                            _this.dialog('destroy');
                            $('body').css('overflow','visible');
                         });
                    };
    var btn_revert=function() {
                        $('#lf_photos_photo_'+config.dataParams.id+'_image_cropinfo_hidden').val('');

                        var _this=$(this);
                         $.post('/_ajax/multimedia/revertCroppingPhoto',{index:config.dataParams.id,thumb:0, location_id:config.dataParams.location},function(data){
                             $('#lf_photos_photo_'+config.dataParams.id+'_upload_image').get(0).src=data;
                            _this.dialog('close');
                         });


                    };
    var btn_close=function() {
                        $(this).dialog('close');

                    };
    if(edit_mode==1){
        var buttons={'crop':btn_crop,'revert':btn_revert,'close':btn_close};
    }else{
        var buttons={'crop':btn_crop,'close':btn_close};
    }
    $('#viewCropDialog').YDialog({container:'viewCropDialog',buttons:buttons,height:600, width:800,title:'Crop Image',dataSource:config.dataSource, dataParams:config.dataParams});
}
function cropThumbImage(config){
    var edit_mode=($('#lf_photos_photo_'+config.dataParams.id+'_image_thumbcropinfo_hidden').val()=='')?0:1;
    var btn_crop=function() {

                         $('#viewThumbCropDialog').html('<div class="shadow_right"><div class="backg_white" id="content"><img src="/themes/1/i/loadinfo.gif"  align="center"></div></div>');
                         var _this=$(this);
                         //alert($('#lf_photos_photo_'+config.dataParams.id+'_image_cropinfo_hidden').get(0));
                         //alert(config.dataParams.id+'_'+$('#lf_photos_photo_'+config.dataParams.id+'_image_thumbcropinfo_hidden').val());
                         $.post('/_ajax/multimedia/croppingPhoto',{crop_area:$('#lf_photos_photo_'+config.dataParams.id+'_image_thumbcropinfo_hidden').val(),index:config.dataParams.id,thumb:1, location_id:config.dataParams.location,edit_mode:edit_mode},function(data){
                            $('#lf_photos_photo_'+config.dataParams.id+'_upload_image').get(0).src=data;
                            _this.dialog('destroy');
                            $('body').css('overflow','visible');

                         });
                    };
  var btn_revert=function() {
                        $('#lf_photos_photo_'+config.dataParams.id+'_image_thumbcropinfo_hidden').val('');

                        var _this=$(this);
                         $.post('/_ajax/multimedia/revertCroppingPhoto',{index:config.dataParams.id,thumb:1, location_id:config.dataParams.location},function(data){
                             $('#lf_photos_photo_'+config.dataParams.id+'_upload_image').get(0).src=data;
                            _this.dialog('close');
                         });


                    };
    var btn_close=function() {
                        $(this).dialog('close');

                    };
    if(edit_mode==1){
        var buttons={'crop':btn_crop,'revert':btn_revert,'close':btn_close};
    }else{
        var buttons={'crop':btn_crop,'close':btn_close};
    }

    $('#viewThumbCropDialog').YDialog({container:'viewThumbCropDialog',height:600, width:800,buttons:buttons,title:'Thumbnail Crop Image',dataSource:config.dataSource, dataParams:config.dataParams});
}
function videoView(location_id, video_id){
    var btn_close=function() {
                        $(this).dialog('close');

                    };
    var buttons={'close':btn_close};
    var config={};
    config.dataSource='/_ajax/multimedia/viewVideo';
    config.dataParams={id:video_id,  location_id : location_id};
    $('#viewVideoDialog').YDialog({container:'viewVideoDialog',width:395,height:362, buttons:buttons,title:'Video View',dataSource:config.dataSource, dataParams:config.dataParams});
}
function sendToFriend(url, content_type){

    var btn_close=function() {
        $(this).dialog('close');
    };
    var btn_send=function() {
        $('form#sendToFriend').trigger('submit');
    };
    var buttons={'close':btn_close,'send':btn_send};
    var config={};
    config.dataSource='/common/sendtofriend_index/index/';
    config.dataParams={url:url,  content_type : content_type};
    $('#sendToFriendDialog').YDialog({container:'sendToFriendDialog', width:640,height:450,buttons:buttons,title:'Send to Friend',dataSource:config.dataSource, dataParams:config.dataParams});
}

function sendToFriend_onSubmitHundler(){
    $('#sendToFriendDialog').dialog('close');
}
function bannerPreview(ad_id){

    preview_content = $('#ad_preview_'+ad_id).html();
    dialog_height = parseInt($('#ad_preview_'+ad_id).attr('height')) + 120;
    dialog_width = parseInt($('#ad_preview_'+ad_id).attr('width')) + 120;

    $('#dstart').after('<div id="dialog_' + ad_id + '"><div class="shadow_right"><div class="backg_white" id="preview_content">' + preview_content + '<br /></div></div></div>');

    $('#dialog_'+ad_id).dialog({

            open:function(){
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                    $('button',$(this).parent()).each(function(i){

                        $(this).hide();
                    });
            },

            height:dialog_height,
            width:dialog_width,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Banner preview',
            buttons: {
                'c': function()
                {
                    $(this).dialog('destroy');
                }
            }
        });

}

function toggleKeywords(kid)
{
    if($('#k'+kid).is(":visible"))
    {
        $('#k'+kid).toggle();
        $('#kb'+kid).text(" [more]");
    }
    else
    {
        $('#k'+kid).toggle();
        $('#kb'+kid).text(" [less]");
    }
}


function setPhotoTitleListing(obj)
{
    id = $(obj).parent().parent()
           .find('img').attr('id')
           .replace('lf_photos_photo_','')
           .replace('_upload_image','');

    $('#infobar_'+id).remove();

    currentTitle = $('#lf_photos_photo_' + id + '_image_title_hidden').val();


    $('#schema_lf_photos_photo')
        .after(
        '<div id="dialog_'+ id +'">' +
            '<div class="shadow_right">' +
                '<div class="backg_white pad15_l" id="preview_content">' +
                    '<br /><table class="c_table2"><tr><th>Title:</th><td><input id="photo_title_'+id+'" class="wid220" type="text" value="'+currentTitle+'" /></td></tr>' +
                    '<tr><th></th><td align="right"><a href="javascript://" style="color:#666;" onclick="setPhotoTitleListingRequest(this,'+id+')" class="set-title-btn">Set Title</a></td></tr></table> ' +
                    '<br /><center><span align="center" id="infobar_'+ id +'"></span></center>' +
                '</div>' +
            '</div>' +
        '</div>');

    $('#dialog_' + id).dialog(
            {

                open:function(){
                        $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                        $('button',$(this).parent()).each(function(i){

                            $(this).hide();
                        });
                },

                height:200,
                width:300,
                modal: true,
                closeText:'',
                overlay: {
                    backgroundColor: '#000',
                    opacity: 5
                },
                title: 'Set photo title',
                buttons: {
                    'c': function()
                    {
                        $(this).dialog('destroy');
                    }
                }
            });




}


function setPhotoTitleListingRequest(obj,id)
{
    title = $(obj).parent().parent().parent().find('input').val();
    $('#lf_photos_photo_' + id + '_image_title_hidden').val(title);
   // $('#dialog_' + id).dialog('destroy');
    $('#dialog_' + id).remove();
    //$('#infobar_'+id).text('Success! Title updated!').fadeOut(3000);
}



function setPhotoTitle(photo_id)
{

    currentTitle = $('#hidden_photo_title_' + photo_id).val();
    $('#infobar_'+photo_id).remove();
    $('#photo_' + photo_id)
        .after(
        '<div id="dialog_'+ photo_id +'">' +
            '<div class="shadow_right">' +
                '<div class="backg_white pad15_l" id="preview_content">' +
                    '<br /><table class="c_table2"><tr><th>Title:</th><td><input id="photo_title_'+photo_id+'" class="wid220" type="text" value="'+currentTitle+'" /></td></tr>' +
                    '<tr><th></th><td align="right"><a href="javascript://" style="color:#666;" onclick="setPhotoTitleRequest('+photo_id+', this)" class="set-title-btn">Set Title</a></td></tr></table> ' +
                '<br /><center><span align="center" id="infobar_'+ photo_id +'"></span></center>' +
                '</div>' +
            '</div>' +
        '</div>');

    $('#dialog_' + photo_id).dialog(
            {

                open:function(){
                        $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                        $('button',$(this).parent()).each(function(i){

                            $(this).hide();
                        });
                },

                height:200,
                width:300,
                modal: true,
                closeText:'',
                overlay: {
                    backgroundColor: '#000',
                    opacity: 5
                },
                title: 'Set photo title',
                buttons: {
                    'c': function()
                    {
                        $(this).dialog('destroy');
                    }
                }
            });

}

function setPhotoTitleRequest(photo_id, obj)
{

    $('#infobar_'+photo_id).text('Updating...');

    title = $(obj).parent().parent().parent().find('input').val();

    $(obj).parent().parent().parent().parent().after();

    $('#hidden_photo_title_' + photo_id).val(title);


    if(title)
    {
        $('#hidden_photo_title_' + photo_id).val(title);

        $.post(
            '/_ajax/multimedia/set_photo_title',
            {
               id    : photo_id,
               title : title
            },
            function(data)
            {
                $('#infobar_'+photo_id).text('Success! Title updated!');
            }

        );
    }
}

function order_site(location_id, s_id, pt)
{

    if(location_id>-1 && s_id>0)
    {
      var preview_content = '';
      for(value in pt){
       if(value == 1){
           preview_content += '<tr><td><input type="radio" style="margin:2px 0;" name="payment_type_'+s_id+'" value="'+value+'" checked="checked" /></td><td>&nbsp;&nbsp;'+pt[value]+'</td></tr>';
       }else{
           preview_content += '<tr><td><input type="radio" style="margin:2px 0;" name="payment_type_'+s_id+'" value="'+value+'" /></td><td>&nbsp;&nbsp;'+pt[value]+'</td></tr>';
       }
      }


        $('#dstart').after('<div id="dialog_payment_type_' + s_id + '"><table style="margin:10px 0 0 12px;">' + preview_content + '</table></div>');


        $('#dialog_payment_type_'+s_id).dialog({

            open:function(){
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                    $('button',$(this).parent()).each(function(i){
                       if (i==0) {
						$(this).attr({'class':'submit'});
					   }
					   else if(i==1){
						$(this).attr({'class':'cancel'});
					   }
                    });
           },

            //height:500,
            //width:500,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Select payment type',
            buttons: {
                'e': function()
                {
                   var res = $('input:radio:checked').val();
                    document.location.replace('/user/pay_website/'+location_id+':'+s_id+':'+res);

                    $(this).dialog('destroy');

                },
                 'c': function()
                {
                    $(this).dialog('destroy');
                }

            }
        });


    }

}

function pose_discount_listing(location_id,listing_id, mode, old_value, old_type)
{
    if(confirm('Are you sure you want to pose discount for this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined )
    {
        var preview_content = '';
        preview_content = '<table class="c_table2 marg12_l"><tr><td>Discount&nbsp;</td><td><input type="text" class="wid100" name="listing_'+location_id+'_'+listing_id+'_discount_value_" id="listing_'+location_id+'_'+listing_id+'_discount_value_" value=""/></td><td>&nbsp;<input type="radio" id="listing_'+location_id+'_'+listing_id+'_discount_type_" name="listing_'+location_id+'_'+listing_id+'_discount_type_" value="1" checked /> % <input type="radio" id="listing_'+location_id+'_'+listing_id+'_discount_type_" name="listing_'+location_id+'_'+listing_id+'_discount_type_" value="2" /> Flat</td></tr></table>';

        $('#dstart').after('<div class="ldiscount" id="dialog_listing_discount_' + listing_id + '"><div _class="shadow_right">' + preview_content + '<br /></div></div>');

        $('#dialog_listing_discount_'+listing_id).dialog({
            open:function(){

                 $(this).dialog('refresh');
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                     $(this).dialog('refresh');
                    $('button',$(this).parent()).each(function(i){
                       $(this).dialog('refresh');
                         if (i==0) {
						$(this).attr({'class':'set-btn'});
					   }
					   else if(i==1){
						$(this).attr({'class':'cancel'});
					   }
                    });
           },

            //height:500,
            //width:500,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Set Listing Discount',
            buttons: {
                'e': function()
                {
                       var discount_type = $('input[name=listing_'+location_id+'_'+listing_id+'_discount_type_]:radio:checked').val();
                       //var discount = $('#listing_'+location_id+'_'+listing_id+'_discount_value_').val();
                       //var discount = $('.bbb').val();
                       var discount = $(this).parent('div').find('input[type=text]:first').val();
                       //alert(discount);
                       //alert(discount_type);
                       var check = 1;
                        if(discount == ''){
                           alert('Please enter a valid discount value');
                           check = 0;
                           $(this).dialog('refresh');
                        }else{
                            var val = parseFloat(discount);
                            if (!(val >0)){
                                alert('Please enter a valid discount value');
                                check = 0;
                                $(this).dialog('refresh');
                            }
                        }
                        if(check != 0){
                            $('.ldiscount').append('<center><img id="discounts_loader" src="/themes/1/i/loadinfo.gif" height="16" width="16" /></center>');
                            discount_service = jQuery.Zend.jsonrpc({url: '/api/jsonrpc/discount'});
                            var out = discount_service.poseDiscount(listing_id, discount, discount_type, mode);
                           // alert(out);

                            $('#listing_'+location_id+'_'+listing_id+'_pose_discount').hide();
                            $('#listing_'+location_id+'_'+listing_id+'_change_discount').html('<a class="pay" href="#"  onClick="return change_discount_listing('+location_id+','+listing_id+', '+discount+', '+discount_type+', '+out+');" title="Change Discount" >Discount</a>');
                            $('#listing_'+location_id+'_'+listing_id+'_discount_message').html('Your discount is on moderation');
                             if(out){
                                $('#listing_'+location_id+'_'+listing_id+'_trial').hide();
                             }else{

                             }

                            $(this).dialog('destroy');
                        }


                },
                 'c': function()
                {
                    $(this).dialog('destroy');
                }

            }
        });


    }

    return false;
}

function change_discount_listing(location_id,listing_id,  old_value, old_type, mode)
{
    if(confirm('Are you sure you want to change discount for this listing?') == false)
    {
        return false;
    }

    if(location_id!=undefined && listing_id!=undefined &&  old_value!=undefined && old_type!=undefined && mode!=undefined)
    {
        var preview_content = '';
        var checked_1 = '';
        var checked_2 = '';
        if(old_type == 1){
            checked_1 = 'checked';
        }else{
            checked_2 ='checked';
        }
        preview_content = '<table class="c_table2 marg12_l"><tr><td>Discount&nbsp;</td><td><input type="text" class="wid100" name="listing_'+location_id+'_'+listing_id+'_discount_value_" id="listing_'+location_id+'_'+listing_id+'_discount_value_" value="'+old_value+'"/></td><td>&nbsp;<input type="radio" id="listing_'+location_id+'_'+listing_id+'_discount_type_" name="listing_'+location_id+'_'+listing_id+'_discount_type_" value="1" '+checked_1+' /> % <input type="radio" id="listing_'+location_id+'_'+listing_id+'_discount_type_" name="listing_'+location_id+'_'+listing_id+'_discount_type_" value="2" '+checked_2+'/> Flat</td></tr></table>';

        $('#dstart').after('<div class = "ldiscount" id="dialog_listing_discount_' + listing_id + '"><div _class="shadow_right">' + preview_content + '<br /></div></div>');


        $('#dialog_listing_discount_'+listing_id).dialog({
            open:function(){
                 $(this).dialog('refresh');
                    $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                     $(this).dialog('refresh');
                    $('button',$(this).parent()).each(function(i){
                       $(this).dialog('refresh');
                         if (i==0) {
						$(this).attr({'class':'set-btn'});
					   }
					   else if(i==1){
						$(this).attr({'class':'cancel'});
					   }
                    });
           },

            //height:500,
            //width:500,
            autoSize: true,
            modal: true,
            closeText:'',
            overlay: {
                backgroundColor: '#000',
                opacity: 5
            },
            title: 'Set Listing Discount',
            buttons: {
                'e': function()
                {
                       var discount_type = $('input[name=listing_'+location_id+'_'+listing_id+'_discount_type_]:radio:checked').val();
                       var discount = $(this).parent('div').find('input[type=text]:first').val();
                       //alert(discount);
                      // alert(discount_type);

                       var check = 1;
                        if(discount == ''){
                           alert('Please enter a valid discount value');
                           check = 0;
                           $(this).dialog('refresh');
                        }else{
                            var val = parseFloat(discount);
                            if (!(val >0)){
                                alert('Please enter a valid discount value');
                                check = 0;
                                $(this).dialog('refresh');
                            }
                        }
                        if(check != 0){
                            $('.ldiscount').append('<center><img id="discounts_loader" src="/themes/1/i/loadinfo.gif" height="16" width="16" /></center>');
                            discount_service = jQuery.Zend.jsonrpc({url: '/api/jsonrpc/discount'});
                            var out = discount_service.poseDiscount(listing_id, discount, discount_type, mode);
                           // alert(out);
                            $('#listing_'+location_id+'_'+listing_id+'_change_discount').html('<a class="pay" href="#"  onClick="return change_discount_listing('+location_id+','+listing_id+', '+discount+', '+discount_type+', '+out+');" title="Change Discount" >Discount</a>');
                            $('#listing_'+location_id+'_'+listing_id+'_discount_message').html('Your discount is on moderation');
                             if(out){
                                $('#listing_'+location_id+'_'+listing_id+'_trial').hide();
                             }else{

                             }

                            $(this).dialog('destroy');
                        }


                },
                 'c': function()
                {
                    $(this).dialog('destroy');
                }

            }
        });

    }

    return false;
}



function tip_test(location_id, l_id)
{
    if(location_id>-1 && l_id>0)
    {
 		var atitle = '';

        $('#dialog_social_'+l_id).html('<div class="shadow_right"><div class="backg_white" id="content">Please wait. Loading...</div></div>');

        $('#dialog_social_'+l_id).dialog({

                bgiframe: true,
                resizable:false,
               // position:[30,50],
                close:function(){
                        $(this).dialog('destroy');
                },
                open:function(){
                        $('.ui-dialog-buttonpane',$(this).parent()).append('<div class="corner_bottom_right"><div class="corner_bottom_left"></div></div>');
                        $('button',$(this).parent()).each(function(i){
                      
                            $(this).hide();
                        });

                         
                                    toolTipContent = $('#container_'+l_id+'_social').html();
                                    $('#content',$('#dialog_social_'+l_id)).html(toolTipContent);
                                    //$('.ui-dialog-title').text(data.title);
                               
                },
               // height:350,
                width:100,
                modal: false,
                closeText:'',
                overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                },
                title: atitle,
                buttons: {
                    'c': function() {
                        $(this).dialog('destroy');
                    }

                }});


    }

}
