﻿// JScript File
$(document).ready(function(){
$(".datepicker").datepicker();

$("#cmdsearch").click(function() {
          var _postText =$("#txtsearch").val();
          if (_postText!= "")
             {
                window.location.href ='results.aspx?keyword='+_postText;
              }
       });
         
$("#cmdfilter").click(function() {
          var _criteria =$("#txtsearch").val();
          if($("#txtsearch").val() == "" ){
               _criteria =" "
          } 
               $("#divloader").hide();   {
               ajaxJqueryPost("../websvr.aspx/getimglist", "{'_criteria':'"+_criteria+"'}","#divimg","getimglist");
               $("#txtsearch").val('');
              }
           $("#divloader").hide();
           $("#txtsearch").focus();   
       });

  $('#txtcomments').keyup(function(){   
        var limit = parseInt($(this).attr('maxlength'));   
        var text = $(this).val();   
        var chars = text.length;
        if (chars >0){
            $('#cmdsend').removeAttr("disabled");
        }
        
        if (chars >= (limit * .85)) 
        {   $('#counter').removeClass("span_title");
            $('#counter').addClass("span_red");
        }
           
        $('#counter').html(parseInt($(this).attr('maxlength'))-$(this).val().length );
        if(chars > limit){   
            var new_text = text.substr(0, limit);   
            $('#cmdsend').attr("disabled","disabled");
        }
        
    });   
  $('#cmdsend').click(function(){   
        var strErr="";
        var _valid = true;
        if ($('#txtname').val()==""){strErr="<span>Nombre es invalido</span><br>";_valid=false;}
        /*if (isemail($('#txtemail').val())==false){strErr= strErr+"<span>Email invalido</span><br>";_valid=false;}*/
        if ($('#txtcomments').val().length<5){strErr= strErr+"<span>Comentario no puede estar en blanco y debe ser mayor de 5 caracteres</span><br>";_valid=false;}
        if (_valid==false){
            showDialog(strErr);
        }
        if (_valid == true){
        $('#txtcomments').val(replaceAll($('#txtcomments').val())) ;
        $('#txtemail').val(replaceAll($('#txtemail').val())); 
        $('#txtname').val(replaceAll($('#txtname').val()));
        $('#divloader').html("<img src='scripts/css/imgs/loader.gif'>");
           ajaxJqueryPost("websvr.aspx/addcomment", "{'_id':'"+$('#news_id').val()+"','_email':'"+$('#txtemail').val()+"','_name':'"+$('#txtname').val()+"','_comments':'"+$('#txtcomments').val()+"','_rowno':'"+$('#comm_count').text()+"'}","#wrap_comments_all","addcomments");
                $('#txtcomments').val('') ;
                $('#txtemail').val(''); 
                $('#txtname').val('');
                $('#counter').text(500);
        }     
    });
});

function showDialog(_msg){
  var _newid = "";
  $("#wrap_comments_all").append("<div id='new1_wrap_00'>"+_msg+"</div>");
  $("#new1_wrap_00").dialog();
   }

function setDefaultImg(source){ 
    source.src = "http://cbkimages.s3.amazonaws.com/imgs/m_error.png";
    source.onerror = ""; 
    return true; 
    } 
 
function isemail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false) {
      return false;
   }
}

function addvote(_id,_type,_row){
    ajaxJqueryPost("websvr.aspx/addvote", "{'_id':'"+_id+"','_type':'"+_type+"'}","#"+_row,"addvote");
}

function addabuse(_id){

    ajaxJqueryPost("websvr.aspx/addabuse", "{'_id':'"+_id+"'}","#"+_id,"addabuse");
}

  function replaceAll(_str){
   var tmpStr = _str;
   var _index;
   var _strFind;
   var _strReplace;
   for (i=0;i<=3;i++)
   {
     if (_index ==1) {_strFind ="<";_strReplace="";}
     if (_index ==2) {_strFind =">";_strReplace="";}
     if (_index ==3) {_strFind ="'";_strReplace="`";}
        while(_index != -1){
             tmpStr = tmpStr.replace(_strFind,_strReplace);
            _index = tmpStr.indexOf(_strFind);
        }
     }
        return tmpStr;
    }

    function watermark(_id,_lbl){
     $(_id).addClass("watermark").val($(_lbl).val());
            $(_id).focus(function() {
                $(this).filter(function() {
                    return $(this).val() == "" || $(this).val() == $(_lbl).val()
                }).removeClass("watermark").val("");
            });
            $(_id).blur(function() {
                $(this).filter(function() {
                    return $(this).val() == ""
                }).addClass("watermark").val($(_lbl).val());

            });
    }
    
  function dosearch(_id){
      var _postText =$(_id).val();
          if (_postText!= "")
             {
                window.location.href ='search.aspx?search='+_postText;
              }
    }
    

function insertImage(_Id,text){
    if (text !=""){
    text = "<div class='wrap_img'"+$('input:radio[name=r]:checked').val()+"'>"+text+"</div>"
    $("#"+_Id).append(text);  
    }
    
}
  function ajaxJqueryPost(_url,_data,_id,_type) {
  
  var retVal ='';
            $.ajax({
                      type: "POST",
                      url: _url,
                      data: _data,
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function(content) {
                        if (_type =='getimglist'){
                          $(_id).html(content);
                          $("#divloader").hide();
                          if (content ='') {
                          $("#divloader").html("<div class='wrap_msg'>No se encontraron resultados para esta busqueda, Intente de nuevo!</div>")}
                       }
                       
                       if (_type =='addcomments'){
                          if (content !=''){
                          $(_id).append(content);
                           $('#comm_count').text(parseInt($('#comm_count').text())+1);   
                           showDialog("Tu Comentario ha sido Enviado");
                       }else{   
                          showDialog("Comentario no pudo ser guardado debido a un error del sistema, trate de nuevo");
                          }
                          $('#divloader').hide();
                       }
                       
                       if (_type =='addvote'){
                       if (content =='voted'){
                          $(_id).text(parseInt($(_id).text())+1);
                          $(_id+"c").attr("disabled","disabled");
                          $(_id+"c").attr("src",$(_id+"c").attr("src").replace(".png","2.png"));
                          $(_id.replace("x1","x2")+"c").attr("disabled","disabled");
                          $(_id.replace("x1","x2")+"c").attr("src",$(_id.replace("x1","x2")+"c").attr("src"));
                          /*$(_id+"c").attr("src",$(_id+"c").attr("onclick()").replace(".png","2.png"));*/
                          }
                          else {
                                showDialog("Error del sistema, trate de nuevo");
                                }
                          
                       }
                       
                       if (_type =='addabuse'){
                            if (content !=''){
                              showDialog("Comentario ha sido reportado para revisión de Consuelocity.com, cualquier sugerencia escribanos a dominicano_22@hotmail.com!!!");
                       }       
                          
                       }
              }
           });
           
      }

  /**
 * 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

