var CopyrightMarket = {
	init	: function() {
		$('#projects-create').click(this.showCreateProject);

		if ($('#fast-feedback').length>0) {
			this.setFeedbackCallback();
		}

		if ($('#content_text').length>0) {
			$('#content_text').keyup(this.calculateChars);
		}

		if ($('#content_preview').length>0) {
			$('#content_preview').keyup(this.calculateChars_preview);
		}

		if ($("#tabs").length>0) {
			$("#tabs").tabs();
		}

		if ($('#project_id_switcher')) {
			$('#project_id_switcher').change(this.changeProject);
		}
		if ($('#project_id_switcher_closed')) {
			$('#project_id_switcher_closed').change(this.changeProjectClosed);
		}

//		$('#inner-content').find('button').each(function(){
//			$(this).addClass('btn');
//			$(this).html('<span><span>'+$(this).text()+'</span></span>');
//		});
		$('label.required').after('<span class="req">*</span>');
        $('.opinion-img').click(CopyrightMarket.openResponse);
        if ($('textarea.resizable').length > 0) {
            $('textarea.resizable:not(.processed)').TextAreaResizer();
        }
        $('.sortable tr').hover(function(){
           $(this).find('.options div').show();
        }, function() {
            $(this).find('.options div').hide();
        });
	},

	calculateChars: function(){
		var chars=$('#content_text').val();

		var chars_preview = $('#content_preview').val();
		if (chars_preview) chars += chars_preview;

		chars = strip_html_tags(chars);
		chars = chars.replace(/\s/g, '');
		var count = chars.length;

		if (typeof(needChars) != "undefined") {
		  if (count<needChars){
			var status = 'status-bad';
		  } else {
			var status = 'status-good';
		  }
		}
		$('#chars_amount').html('<span class="'+status+'">'+count+'</span>');
	},
	calculateChars_preview: function(){
		var chars="";
		var chars_preview = $('#content_preview').val();
		if (chars_preview) chars += chars_preview;

		chars = strip_html_tags(chars);
		chars = chars.replace(/\s/g, '');
		var count = chars.length;

		if (count<needChars_preview){
			var status = 'status-bad';
		} else {
			var status = 'status-good';
		}
		$('#chars_preview_amount').html('<span class="'+status+'">'+count+'</span>');
	},
	setFeedbackCallback : function(){
		$('#fast-feedback').submit(function(e){
			var backup = $('#fast-feedback').html();
			e.preventDefault();
			var options = {
				url		: '/?mode=front-gateway&module=copyright_market&controller=api&action=send_feedback&format=json',
				type	: "post",
				dataType: "json",
				success	: function (data, textStatus) {
					$('#fast-feedback').html(backup);
					if (data.success){
						$('#fast-feedback textarea').val('');
				   		alert(data.messages);
				    }  	else {
				    	alert(data.errors[0]);
					}
				}
			}
			$('#fast-feedback').ajaxSubmit(options);
			$('#fast-feedback').html('<img class="preloader" src="/common/preloaders/orange_hor_2.gif">');
		});
	},
	showCreateProject : function(){
		var form = $('#create-project-form').clone();
		form.dialog({
			title		: 'Создание группы.',
			width		: 320,
			minHeight	: 100,
			modal		: true,
			autoResize	: true,
			resizable	: false,
			buttons		: {
				'Закрыть' : function(){
					form.dialog('destroy');
				},
				'Создать' : function(){
					form.submit();
				}
			}
		});
		return false;
	},

	showReasonBlock : function(id){
		var win = $('#reason-'+id).clone();
			win.dialog({
				title		: 'Причина отправки на доработку.',
				width		: 300,
				modal		: true,
				autoResize	: true,
				resizable	: false,
				buttons		: {
					'Закрыть' : function(){
						win.dialog('destroy');
					}
				}
			});
			return false;
	},
	changeInPortfolioStatus: function(order_id, set_status) {
		$('#in_portfolio').attr("disabled", true);
		jQuery.get('/?', {
			mode		: 'front-gateway',
			module		: 'copyright_market',
			controller	: 'api',
			action		: 'change_in_portfolio_status',
			format		: 'json',
			order		: order_id,
			set_status	: (set_status?1:0)
			},
			function(result) {
				$('#in_portfolio').removeAttr("disabled");
					alert('Статус сохранен!');
				}, 'json'
		);
	},
	changeProject : function(){
		var value = $('#project_id_switcher option:selected').val()
        if (value == '#add#') {
            CopyrightMarket.showCreateProject();
        } else {
            var url = '/user/workspace/projects/orders?project_id=';
            url += value;
            document.location = url;
        }
	},
	changeProjectClosed : function(){
		var url = '/user/workspace/works?action=closed&project_id=';
		url += $('#project_id_switcher_closed option:selected').val();
		document.location = url;
	},
	checkUser : function(val){
		$('#writer-checker').removeClass('silk-accept');
		$('#writer-checker').removeClass('silk-delete');
		$('#writer-checker').removeClass('preloaders-grey-circle');
		if ($('#writer_login').val() != '') {
			$('#writer-checker').addClass('preloaders-grey-circle');
			jQuery.get('/',{
					mode		: 'front-gateway',
					module		: 'copyright_market',
					controller	: 'api',
					action		: 'check_writer_exists',
					login	: $('#writer_login').val()
				},
				function (result){
					$('#writer-checker').removeClass('silk-accept');
					$('#writer-checker').removeClass('silk-delete');
					$('#writer-checker').removeClass('preloaders-grey-circle');
					if (result.exists > 0) {
						$('#writer-checker').addClass('silk-accept');
					} else {
						$('#writer-checker').addClass('silk-delete');
					}
				}, 'json'
			);
		}
	},
	//@todo
	confirmOfferByOwnder : function(id) {
		if (confirm('Вы уверены что хотите взять на выполнение этот заказ?')){
			jQuery.get('/',{
					mode		: 'front-gateway',
					module		: 'copyright_market',
					controller	: 'api',
					action		: 'confirm_offer_by_writer',
					id			: id
				},
				function (result) {

					if (result.id > 0) {

					} else {

					}
				}, 'json'
			);
		}
	},
	//@todo
	confirmOfferByWriter : function(id) {
		if (confirm('Вы уверены что хотите взять на выполнение этот заказ?')) {
			$('#offer-'+id).html('<img class="preloader" src="/common/preloaders/grey_hor.gif" />');
			jQuery.get('/',{
					mode		: 'front-gateway',
					module		: 'copyright_market',
					controller	: 'api',
					format		: 'json',
					action		: 'confirm_offer_by_writer',
					id			: id
				},
				function (result) {
					if (result.success){
						$('#offer-'+id).replaceWith(result.messages[0]);
					} else {
						$('#offer-'+id).replaceWith(result.errors[0]);
					}

				}, 'json'
			);
		}
		return false;
	},
	deleteOfferByWriter : function(id) {
		if (confirm('Отказаться от заказа?')) {
			$('#offer'+id).html('<img class="preloader" src="/common/preloaders/grey_hor.gif" />');
			jQuery.get('/',{
					mode		: 'front-gateway',
					module		: 'copyright_market',
					controller	: 'api',
					format		: 'json',
					action		: 'delete_offer_by_writer',
					id			: id
				},
				function (result) {
					if (result.success){
						$('#offer'+id).html(result.messages[0]);
					} else {
						$('#offer'+id).html(result.errors[0]);
					}

				}, 'json'
			);
		}
		return false;
	},
	checkCopyscape : function(id, cost, recheck){
		var div = $('<div>Проверка с помощью сервиса www.copyscape.com платная и стоит $'+cost+'. <br /><br />Вы согласны оплатить?</div>');
		div.dialog({
				title		: 'Copyscape.',
				width		: 400,
				modal		: true,
				autoResize	: true,
				resizable	: false,
				buttons		: {
					'Отмена' : function(){
						div.dialog('destroy');
					},
					'Да' : function(){
						self.location = '/user/workspace/works?action=copyscape_check&order_id='+id+'&recheck='+recheck;
					}
				}
		});
		return false;
	},
	openCopyscapeReport:function(id, cost){
		jQuery.get('/',{
				mode		: 'front-gateway',
				module		: 'copyright_market',
				controller	: 'api',
				format		: 'json',
				action		: 'get_copyscape_report',
				id			: id
			},
			function (result) {
				if (result.success){
					var div = $('<div>'+result.content+'</div>');
					div.dialog({
						title		: 'Отчет Copyscape',
						width		: 450,
						height		: 500,
						modal		: true,
						autoResize	: true,
						resizable	: true,
						buttons		: {
							'Закрыть' : function(){
								div.dialog('destroy');
							},
							'Повторная проверка' : function(){
								CopyrightMarket.checkCopyscape(id, cost, 1);
							}
						}
					});
				} else {
					alert(result.errors[0]);
				}
			}, 'json'
		);
	},

	confirm : function(question, url, width, height){
		if (!width){
			width = 400;
		}
		if (!height){
			height = 100;
		}
		var div = $('<div>'+question+'</div>');
		div.dialog({
			title		: '',
			width		: width,
			height		: height,
			modal		: true,
			autoResize	: true,
			resizable	: false,
			buttons		: {
				'Согласен' : function(){
					self.location = url;
				},
				'Отмена' : function(){
					win.dialog('destroy');
				}
			}
		});
		return false;
	},
	openResponse : function() {
        var id = $(this).attr('id').replace('item-','');
        $.get('/',{
				mode		: 'front-gateway',
				module		: 'copyright_market',
				controller	: 'api',
				format		: 'json',
				action		: 'get_response_text',
				id			: id
			},
			function (result) {
				if (result.success){
					var div = $('<div>'+result.content+'</div>');
					div.dialog({
						title		: 'Отзыв',
						width		: 300,
						height		: 200,
						modal		: true,
						autoResize	: true,
						resizable	: true,
						buttons		: {
							'Закрыть' : function(){
								div.dialog('destroy');
							}
						}
					});
				} else {
					alert(result.errors[0]);
				}
			}, 'json'
		);
    }
};

$(document).ready(function(){
 	CopyrightMarket.init();
});

function  strip_html_tags(str, allowed_tags) {
            var key = '', allowed = false;
            var matches = [];
            var allowed_array = [];
            var allowed_tag = '';
            var i = 0;
            var k = '';
            var html = '';

            var replacer = function(search, replace, str) {
                return str.split(search).join(replace);
            };

            // Build allowes tags associative array
            if (allowed_tags) {
                allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
            }

            str += '';
            str = str.replace(/<xml>(.*\n*)*?<\/xml>/igm, "");
            str = str.replace(/<style>(.*\n*)*?<\/style>/igm, "");

            // Match tags
            matches = str.match(/(<\/?[\S][^>]*>)/gi);

            // Go through all HTML tags
            for (key in matches) {
                if (isNaN(key)) {
                    // IE7 Hack
                    continue;
                }

                // Save HTML tag
                html = matches[key].toString();

                // Is tag not in allowed list? Remove from str!
                allowed = false;

                // Go through all allowed tags
                for (k in allowed_array) {
                    // Init
                    allowed_tag = allowed_array[k];
                    i = -1;

                    if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
                    if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
                    if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

                    // Determine
                    if (i == 0) {
                        allowed = true;
                        break;
                    }
                }

                if (!allowed) {
                    str = replacer(html, "", str); // Custom replace. No regexing
                }
            }

            return str.replace(/(^\s+)|(\s+$)/igm, "");;
        }


