var _DEBUG = true;
/**
 * Init debug, grabs console object if accessible, or makes dummy debugger
 * Use this to debug js in firefox console
 * eg: fb.log('Message %o', variable);
 */
var fb = _DEBUG && 'undefined' != typeof(console) ? console : {
    log         : function(){},
    debug       : function(){},
    info        : function(){},
    warn        : function(){},
    error       : function(){},
    assert      : function(){},
    dir         : function(){},
    dirxml      : function(){},
    trace       : function(){},
    group       : function(){},
    groupEnd    : function(){},
    time        : function(){},
    timeEnd     : function(){},
    profile     : function(){},
    profileEnd  : function(){},
    count       : function(){},
    msg         : function(){}
};
// Application namespace
function App(){};
//
//  GENERAL FUNCTIONS
//
/**
 * Open find zip popup
 */
App.findZip = function(url)
{
    var win = window.open(url, "Find a zip", 'height=500,width=500,scrollbars=1');
    if ('undefined' == typeof win.opener) {
        win.opener = this.window;
    }
};
/**
 * Updates zip inputs in parent window from popup
 */
App.useSelectedZip = function(id)
{
    var zip_id = '#' + id;
    var zip = $(zip_id).find('#zip-value option:selected').val();
	if (zip > 0) {
        window.opener.document.getElementById('zip').value = zip;
        self.close();
    }
};
App.changeState = function(dialogId, state)
{
	if (state != "") {
		$("#" + dialogId + " #state_text").html(state);
		$("#" + dialogId + " #letter_list").show();
	} else {
		$("#" + dialogId + " #letter_list").hide();
	}
	$("#" + dialogId + " #zip_list").hide();
}
App.changeLetter =	function(dialogId, zipFormId, letter)
{
	var state = $("#" + dialogId + " #state").val();
	if (state != "") {
		$.get(AJAX_URL + "/place/ajax-get-zip/letter/" + letter + "/state/" + state + "/dialogId/" + dialogId + "/zipFormId/" + zipFormId, function(data){
			$("#" + dialogId + " #zip_title").show();
			$("#" + dialogId + " #zip_additional").show();
			$("#" + dialogId + " #zip_list").html(data);
			$("#" + dialogId + " #zip_list").show();
		});
	}
}
App.selectZip =	function(dialogId, zipFormId, zipCode)
{
	$("#" + dialogId).dialog('close');
    //hack
    var areaZip = $('#' + zipFormId + ' #area_zip');
    var zip = $('#' + zipFormId + ' #zip');
    var el = areaZip.length ? areaZip : zip;
    el.val(zipCode);
}
App.zipshow = function(dialogId, thezip)
{
	thezip.parent().find('li').css('background','#fff').css('color','#000');
	thezip.css('background','#3399ff').css('color','#fff');
}
/**
 * Sort functionality on photos page
 */
App.dragDrop = function(url) {
    $('#sort-photos').find('li').css({cursor: 'move'});
    $("#sort-photos").sortable({
        stop: function(event, ui) {
            // do drag-drop
            var $ = jQuery;
            var elm = $(ui.item);
            var source = '#'+$(elm).attr('id').replace('mini_', '');
            var siblings = {
                prev: $(elm).prev(),
                next: $(elm).next()
            }
            if (siblings.next.length != 0) {
                var target = '#' + $(siblings.next).attr('id').replace('mini_', '');
                App.switchPhotos(target, source, 'before');
            }
            if (siblings.prev.length != 0) {
                var target = '#' + $(siblings.prev).attr('id').replace('mini_', '');
                App.switchPhotos(target, source);
            }
            // ajax do sorting
            var orderedIds = [];
            $(this).find('.mini-preview').each(function(i, o) {
                orderedIds[orderedIds.length++] = $(o).attr('id').replace('mini_photo_', '');
            });
            $.post(url, {'orderedIds': orderedIds}, function(response){
                if (response.errors) {
                    if ($('#photos_are_sorted_error').length > 0) {
                        $('#photos_are_sorted_error').dialog({
                            autoOpen: false,
                            title: 'Categories are not sorted',
                            width: 300
                        });
                        $('#photos_are_sorted_error').dialog('open');
                        $('#photos_are_sorted_error').text(response.errors);
				    } else {
					    alert(response.errors);
				    }
                } else {
                   // $('#photos_are_sorted').dialog('open');
                }
            });
        },
        axis: 'y'
    });
    $("#sort-photos").disableSelection();
};
/**
 * Sort functionality on category page
 */
App.categoryDragDrop = function(url) {
    $("#sort-photos").sortable({
        stop: function(event, ui) {
            // do drag-drop
            var $ = jQuery;
            var elm = $(ui.item);
            var source = '#'+$(elm).attr('id').replace('mini_', '');
            var siblings = {
                prev: $(elm).prev(),
                next: $(elm).next()
            }
            if (siblings.next.length != 0) {
                var target = '#' + $(siblings.next).attr('id').replace('mini_', '');
                App.switchPhotos(target, source, 'before');
            }
            if (siblings.prev.length != 0) {
                var target = '#' + $(siblings.prev).attr('id').replace('mini_', '');
                App.switchPhotos(target, source);
            }
            // ajax do sorting
            var categoryIds = new Array();
            $(this).find('.edit_menu').each(function(i, o) {
            	categoryIds[categoryIds.length++] = $(o).attr('id').replace('mini_photo_', '');
            });
//            alert(categoryIds + " " + url);
            $.post(url, {'categoryIds': categoryIds}, function(response){
                if (response.errors == true)
                {
                  $('#photos_are_sorted_error').dialog({
						autoOpen: false,
						title: 'Categories are not sorted',
						width: 300
					});
					 $('#photos_are_sorted_error').dialog('open');
				  $('#photos_are_sorted_error').text(response.msg);

                }
                else {
                	$('#photos_are_sorted_error').dialog({
						autoOpen: false,
						title: 'Categories are sorted',
						width: 300
					});
					 $('#photos_are_sorted_error').dialog('open');
				  $('#photos_are_sorted_error').text(response.msg);
				}
            });
        },
        axis: 'y'
    });
    $("#sort-photos").disableSelection();
};
/**
 * Replace two photodom elements with its positions
 */
App.switchPhotos = function(target,source, position) {
    var $ = jQuery;
    position == 'before' ? $(target).before($(source)) : $(target).after($(source));
};
/**
 * Autocomplete for registration, country selection
 */
App.registrationAutocomplete = function(url, cityInputId, conutryInputId){
    jQuery(cityInputId).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: url,
                type: 'post',
                dataType: "json",
                data: {
                    word: request.term,
                    country: jQuery(conutryInputId).val()
                },
                success: function( data ) {
                     response( $.map( data, function( item ) {
                         return {
                             label: item,
                             value: item
                         }
                    }));
                }
            });
        },
        minLength: 2
    });
};
/**
 * ajax delete album
 */
App.deleteAlbum = function(url, id)
{
    var confirmed = confirm('Are you sure?');
    if (!confirmed) {
        return;
    }
    $.getJSON(url, {}, function(reply){
        if (reply.errors) {
            alert('Album cannot be deleted');
        } else {
            $('#' + id).html('<p>Deleted</p>');
            setTimeout(function(){
                $('#'+id).remove();
            }, 1500);
        }
    });
};
/**
 * Save order positions of photos
 */
App.savePhotoOrder = function(url) {
};
/**
 * Autocompleter for search form. Autocompletes with proposed city + state
 */
/*App.Page.Registration.autocompleteCityWithState = function(url){
    jQuery("#city-state")
    .autocomplete(url, {
        dataType: 'json',
        parse:    function(data) {
            var parsed = [];
            for (key in data) {
                parsed[parsed.length] = {
                    data: [ data[key], key ],
                    value: data[key],
                    result: data[key]
                };
            }
            return parsed;
        }
    })
    .result(function(event, data) {
        var result = data ? data[1] : null;
        jQuery("#city-state").val(result);
    })
}*/
/**
 * ajax delete photo
 */
App.photoDelete = function(url) {
    //if (confirm("Are you sure to delete this photo?")) {
        jQuery.getJSON(url, {}, function(reply){
            if (reply.result) {
                jQuery('#photo_is_deleted').dialog('open');
            } else {
                jQuery('#photo_error').dialog('open');
            }
        });
    //}
    return false;
};
/**
 * ajax setting main photo
 */
App.photoSetMain = function(url) {
    jQuery.getJSON(url, {}, function(reply){
        if (!reply.errors) {
            jQuery('#photo_marked_main').dialog('open');
        } else {
            alert(reply.errors);
        }
    });
    return false;
};
/** crop photo ****************************************************************************/
App.jcrop_apis = new Array();
App.currentPid = '';
App.initJcrop = function(photoId, photoParams) {
    var updateCoords = function(coords) {
        jQuery('#x_' + photoId).val(coords.x);
        jQuery('#y_' + photoId).val(coords.y);
        jQuery('#w_' + photoId).val(coords.w);
        jQuery('#h_' + photoId).val(coords.h);
    }
    App.currentPid = photoId;
    if (App.jcrop_apis[App.currentPid]) {
        App.jcrop_apis[App.currentPid].destroy();
    }

    var jp = jQuery.Jcrop('#cropbox_' + App.currentPid);
    App.jcrop_apis[App.currentPid] = jp;
    jp.setOptions({
        onChange: updateCoords,
        minSize: [ photoParams[4], photoParams[4] ],
        aspectRatio: 1
    });

    var x1 = photoParams[0];
    var y1 = photoParams[1];
    var x2 = photoParams[2];
    var y2 = photoParams[3];
    jp.setSelect([x1, y1, x2, y2]);
};
App.cropPhotoSubmit = function(pid) {
    var jp = App.jcrop_apis[pid];
    if (jp && jp.tellSelect().w) {
        $('#crop_form_' + pid).submit();
    }
    return false;
};
/** register ********************************************************************/
/**
 * format birthdate
 */
App.dateFormat = function() {
    var ys = $('#year').val();
    var ms = $('#month').val();
    var ds = $('#day').val();
    if ( ms.length == 1 ) ms = "0" + ms;
    if ( ds.length == 1 ) ds = "0" + ds;
    var birthdate = ys + "-" + ms + "-" + ds;
    $('#birthdate').val(birthdate);
    $('#birthdate').valid();
};
App.addUserFavorite = function(key, userId, url) {
    if (!url) {
        url = AJAX_URL + '/profile/ajax-user-favorite';
    }
	$.getJSON(url,
		{type : 'add', user_id : userId},
		function(response){
			if (!response.errors) {
				$('#link_add_favorite_' + key).hide();
				$('#link_member_added_' + key).show();
			} else {
				alert('please try again');
				return;
			}
		}
	);
};
/** notification message ********************************************************************/
// function to close the tips
App.closeNotification = function(id) {
    $.cookie(id, '1');
    $('#'+id).remove();
}
// function to check whether to show the tip
App.checkNotification = function(id) {
    if (!$.cookie(id)) {
        $('#'+id).show();
    }
}
//$.cookie('quick_tip_21', null);
/**
 * Append html with in place editor
 * Hide html original element
 *
 * note: If there is value set in _EValues[id]
 * update in place edit area with this value
 * @var _ETpls in place editors templates holder
 * @param id // dom element's id
 */
 App.editInPlace = function(id) {
    var expr = '#'+id;
    fb.log(expr);
    $(expr).hide();
    $(expr + '_edit').remove();
    $('.trigger-'+id).hide();
    $(expr).after(_ETpls[id]);
    if('undefined' != typeof _EValues[id]) {
        $(expr + '_edit').find('.value:first').val(_EValues[id]);
    }
}
/**
 * Remove html with in place editor
 * Restore previous html element
 * @param id // dom element's id
 */
  App.cancelEditInPlace = function(id) {
    var expr = '#'+id;
    $(expr).show();
    $(expr + '_edit').remove();
    $('.trigger-'+id).show();
}
  App.updateInPlaceReviewable = function(id, model, item_id, key){
    var expr = '#'+id;
    var new_value = '';
    new_value = $(expr + '_edit').find('.value:first').val();
    $(expr).text(new_value);
    App.cancelEditInPlace(id);
    _EValues[id] = new_value;
    App.Ajax.request('updateReviewableItem', {
        'model': model,
        'id': item_id,
        'new_value': new_value,
        'key': key
    }, function(reply){
        if(!reply.result) {
            alert(reply.message);
        }else{
            updatedHint(id);
        }
    });
}
  App.updateInPlaceUserText = function(id, model, item_id, key){
    var expr = '#'+id;
    var new_value = '';
    new_value = $(expr + '_edit').find('.value:first').val();
    $(expr).text(new_value);
    App.cancelEditInPlace(id);
    _EValues[id] = new_value;
    App.Ajax.request('updateItemText', {
        'model': model,
        'id': item_id,
        'new_value': new_value,
        'key': key
    }, function(reply){
        if(!reply.result) {
            alert(reply.message);
        }else{
            updatedHint(id);
        }
    });
}
  App.updateInPlacePlaceText = function(id, model, item_id, key){
    var expr = '#'+id;
    var new_value = '';
    new_value = $(expr + '_edit').find('.value:first').val();
    $(expr).text(new_value);
    App.cancelEditInPlace(id);
    _EValues[id] = new_value;
    App.Ajax.request('updateItemText', {
        'model': model,
        'id': item_id,
        'new_value': new_value,
        'key': key
    }, function(reply){
        if(!reply.result) {
            alert(reply.message);
        }else{
            updatedHint(id);
        }
    });
}
/**
 * Save edited in place element
 * @uses cancelEditInPlace()
 *
 * @param string id // dom element's id
 * @param string model // model name (DbTable_*)
 * @param int item_id // referenced object id (id of changing object)
 * @param string key // field key of object, that will be changed
 */
   App.saveInPlace = function(id, model, item_id, key){
    var expr = '#'+id;
    var new_value = '';
    new_value = $(expr + '_edit').find('.value:first').val();
    $(expr).text(new_value);
    App.cancelEditInPlace(id);
    _EValues[id] = new_value;
    App.Ajax.request('updateItem', {
        'model': model,
        'id': item_id,
        'new_value': new_value,
        'key': key
    }, function(reply){
        if(!reply.result) {
            alert(reply.message);
        }else{
            updatedHint(id);
        }
    });
}
/**
 * Save photo in place element
 * @uses cancelEditInPlace()
 *
 * @param string id // dom element's id
 * @param string type // photo type (user / place)
 * @param int item_id // referenced object id (id of changing object)
 * @param string op // caption / comment
 */
    App.updatePhotoComment = function(id, type, item_id, op, u_id){
    var expr = '#'+id;
    var new_value = '';
    new_value = $(expr + '_edit').find('.value:first').val();
    $(expr).text(new_value);
    App.cancelEditInPlace(id);
    _EValues[id] = new_value;
    $.ajax({
      url: AJAX_URL+'/photo/ajax-update-photo-text/type/'+type+'/id/'+u_id,
      type: "POST",
      dataType: 'json',
      data: ({photo_id : item_id, type: type, op : op, value: new_value}),
      success: function(data) {
        if(data.errors) {
            alert(data.errors);
        }
        else {
            App.cancelEditInPlace(id);
        }
      }
    });
}
/**
 * Shows hint message, that changes have been applied
 * Message is faded out and removed after 1500ms timeout
 */
     App.updatedHint = function(id){
    $('#'+id).append('<p id="'+id+'_hint">Updated</p>');
    setTimeout(function(){
        $('#'+id+'_hint').fadeOut('normal', function() {
            $('#'+id+'_hint').remove();
        });
    }, 1500);
}

App.htmlspecialchars = function (string, quote_style, charset, double_encode) {
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}
/** For caption edit in photo page - start **/
App.showCaptionEdit = function(id) {
	$('#caption_'+id+'_link').hide();
	$('#caption_'+id+'_edit').show();
}
App.saveCaptionEdit = function(id) {
	if ($('#caption_'+id+'_form').valid()) {
		$.post(
			AJAX_URL + '/photo/ajax-update-photo-text/',
			$('#caption_'+id+'_form').serialize(),
			function(data){
				if (data.errors != '') {
					$('#caption_'+id+'_form .value').after('<label class="error" for="value" generated="true">'+data.errors+'</label>');
				} else {
					$('#caption_'+id+'_link').html(App.htmlspecialchars($('#caption_'+id+'_form .value').val()));
					$('#caption_'+id+'_link').show();
					$('#caption_'+id+'_edit').hide();
				}
			}
		);
	}
}
App.cancelCaptionEdit = function(id) {
	$('#caption_'+id+'_edit').find('label.error').remove();
	$('#caption_'+id+'_link').show();
	$('#caption_'+id+'_edit').hide();
}
/** For caption edit in photo page - end **/
/** Referer Functions **/
App.setReferer = function(url, referUrl, action) {
	$.cookie('is_referred', true, {path: '/'});
	$.cookie('refer_action', action, {path: '/'});
	$.cookie('refer_url', referUrl, {path: '/'});
	location.href = url;
}
/** Referer Functions End **/

App.deletePlaceReview = function(id, dialogId)
{
	var url = AJAX_URL + '/review/ajax-delete-review/id/' + id;
	$(dialogId + ' .error').html('').hide();
    /*var confirmed = confirm('Are you sure to delete this review?');
    if (!confirmed) {
        return false;
    } else {
		$('.place_review_'+id).fadeOut("slow");
	}*/
    $.getJSON(url, {}, function(reply){
        if (reply.errors) {
            //alert('Review cannot be deleted!');
			$(dialogId + ' .error').html('Review cannot be deleted!').show();
        } else {
			$(dialogId).dialog('close');
            $('.place_review_'+id).fadeOut("slow");
        }
    });
};

