$j(document).ready(function(){

});
var deal_id;
var option = '';
var last_option = '';
var overStars = false;
function onrelateddeal(id, catid){
    option = opt = 'relateddeal';
    var params = 'catid=' + catid + '&id=' + id;
    showBox('<div padding="50px;">Loading....</div>', id, opt);
    $j.ajax({
        method: 'POST',
        dataType: 'text',
        data: params,
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=getrelateddeals',
        success: function(response){
            if (option != opt) 
                return;
            var dealFuncContent = $j('.dealFuncContent');
            dealFuncContent.html('<a href="javascript:void(0)" onclick="hiddenBox();" style="float:right">X</a>');
            dealFuncContent.append(response);
        },
        error: function(response){
        }
    });
}

function onaddtofav(id){
    option = opt = 'addtofav';
    var htmlContent = '<form id="addtofav_form" style="margin: 20px 0px;" onsubmit="return false;" name="addtofav" method="post" action="index.php"><table cellpadding="0" cellspacing="0">';
    htmlContent += '<tr><td width="100" valign="top"><label for="description">Memo: </label></td><td valign="top"><textarea id="description" name="prod_description" class="emailContent" style="width:280px" /></textarea></td></tr>';
    htmlContent += '<tr><td height="5" valign="top"></td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="tags">Tags: </label></td><td valign="top"><input id="tags" name="tags" class="input" style="width:280px"/></td></tr>';
    htmlContent += '<tr><td width="100" valign="middle" height="32"><label for="tags">Suggested Tags</label></td><td valign="middle"><div id="suggestedTags"><div class="loadingImg" style="display:block;"> </div></div></td></tr>';
    htmlContent += '<tr><td height="5" valign="top"></td></tr>';
    htmlContent += '<tr><td width="100" valign="middle"></td><td valign="top">You can write at most FIVE tags for each deal. <br/>Separate them with <span class="red">comma</span>.( , )</td></tr>';
    htmlContent += '</table>';
    htmlContent += '<div class="submitDIV"><input type="button" onclick="doaddtofav(' + id + ',\'' + opt + '\')" class="button submit" value="Submit" /></div><div class="loadingImg"></div></form>';
    showBox(htmlContent, id, opt);
    
    params = 'deal_id=' + id;
    $j.ajax({
        type: 'POST',
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=getTags',
        dataType: 'text',
        data: params,
        success: function(responseText){
            $j('#suggestedTags').html(responseText);
        }
    });
}

function onrate(id){
    option = opt = 'rate';
    var comment = getCookie('comment_' + id);
    if (comment == null || comment == 'undefined') {
        comment = '';
    }
    else {
        comment = comment.replace(/\+/g, ' ');
    }
    var htmlContent = '<form id="rate_form" onsubmit="return false;" name="rate" method="post" action="index.php"><table cellpadding="0" cellspacing="0">';
    //	htmlContent += '<tr><td width="100" valign="top" colspan="2">First: Rate the product. Please select a rating between 0 (poorest) and 5 stars (best).</td></tr>';
    htmlContent += '<tr><td width="100" valign="top" colspan="2"><ul class="voting-ul">';
    for (i = 0; i < 5; i++) {
        num = i + 1;
        htmlContent += '<li id="start_' + num + '" class="voting-li voting-cursor">' + num + '</li>';
    }
    htmlContent += '</ul><div id="voting-overlap"></div></td></tr>';
    htmlContent += '<tr><td height="30"> </td></tr>';
    htmlContent += '<tr><td width="100" valign="top" colspan="2">Please write a (short) review....(max. 2000 characters) </td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="comment">Review: &nbsp;(*)</label></td><td valign="top"><textarea id="comment" name="comment" class="emailContent required" onblur="checkEmpty(this.id);">' + comment + '</textarea></td></tr>';
    htmlContent += '</table>';
    htmlContent += '<input type="hidden" name="rating" id="rating" value="0" />';
    htmlContent += '<div class="submitDIV"><input type="button" onclick="dorate(' + id + ',\'' + opt + '\')" class="button submit" value="Submit" /></div><div class="loadingImg"></div></form>';
    showBox(htmlContent, id, opt);
    var rating_bar = $j('.voting-cursor');
    var rating_val = $j('#rating');
    var clicked = false;
    
    rating_bar.mouseover(function(){
        clicked = false;
        overStars = true;
        //		$j('#comment').html('mouseover:'+overStars);
        ratingStar = $j(this);
        setTimeout(function(){
            return scollStars(ratingStar)
        }, 0);
    });
    
    rating_bar.mouseout(function(){
        overStars = false;
        //		$j('#comment').html('mouseout:'+overStars);
        if (clicked) 
            return;
        for (i = 1; i <= 5; i++) {
            $j('#start_' + i).removeClass('voting-li-current');
        }
        rating_val.val(0);
    });
    
    rating_bar.click(function(){
        clicked = true;
        rating_val.val($j(this).text());
    });
}

function scollStars(thisStar){
    //	$j('#comment').html('In func:'+overStars);
    if (overStars == false) 
        return;
    var num = parseInt(thisStar.text());
    for (i = 1; i <= num; i++) {
        $j('#start_' + i).addClass('voting-li-current');
    }
    for (i = num + 1; i <= 5; i++) {
        $j('#start_' + i).removeClass('voting-li-current');
    }
}

function onreporterror(id){
    option = opt = 'reporterror';
    var htmlContent = '<form id="reporterror_form" onsubmit="return false;" name="reporterror" method="post" action="index.php"><table cellpadding="0" cellspacing="0">';
    htmlContent += '<tr><td width="100" valign="top"><label for="subject">Subject: &nbsp;(*)</label></td><td valign="top"><input id="subject" name="subject" class="input required" style="width:280px" onblur="checkEmpty(this.id);" /></td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="emailContent">Content: &nbsp;(*)</label></td><td valign="top"><textarea id="emailContent" name="emailContent" class="emailContent required" onblur="checkEmpty(this.id);" ></textarea></td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="username">Your name: &nbsp;(*)</label></td><td valign="top"><input id="username" name="username" class="input required" onblur="checkEmpty(this.id);" /></td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="username">Your email: &nbsp;(*)</label></td><td valign="top"><input id="email" name="email" class="input required" onblur="checkEmpty(this.id);" /></td></tr>';
    htmlContent += '</table>';
    htmlContent += '<div class="submitDIV"><input type="button" onclick="doreporterror(' + id + ',\'' + opt + '\')" class="button submit" value="Submit" /></div><div class="loadingImg"></div></form>';
    showBox(htmlContent, id, opt);
}

function onsharedeal(id){
    option = opt = 'sharedeal';
    //<legend>What would you like to say:</legend>
    var htmlContent = '<form id="sharedeal_form" onsubmit="return false;" name="sharedeal" method="post" action="index.php"><table cellpadding="0" cellspacing="0">';
    htmlContent += '<tr><td width="100" valign="top"><label for="emailContent">Your words: &nbsp;(*)</label></td><td valign="top"><textarea id="emailContent" name="emailContent" class="emailContent" onblur="checkEmpty(this.id)"></textarea></td></tr>';
    htmlContent += '<tr><td width="100" valign="top"><label for="username">Your name: &nbsp;(*)</label></td><td valign="top"><input id="username" name="username" class="input" onblur="checkEmpty(this.id)" /></td></tr>';
    htmlContent += '</table><legend>Who do want to share with:</legend><div id="dealContact">';
    for (var i = 0; i < 2; i++) {
        var hidden = (i == 0) ? 'style="display:none;" id="dealContactHidden"' : '';
        var addButton = (i == 1) ? '&nbsp;&nbsp;<a href="javascript:void(0)" class="addItem" onclick="addItem(\'dealContact\')">+</a>' : '';
        htmlContent += '<div class="dealContact" ' + hidden + ' ><div style="width:100px;float:left"><label>Name: </label></div><input type="text" name="contactName[]" class="inputbox" />';
        htmlContent += '&nbsp;&nbsp;<label>Email: </label><input type="text" name="email[]" class="inputbox" /></div>' + addButton;
    }
    htmlContent += '</div>';
    htmlContent += '<div class="submitDIV"><input type="button" onclick="dosharedeal(' + id + ',\'' + opt + '\')" class="button submit" value="Submit" /></div><div class="loadingImg"></div></form>';
    showBox(htmlContent, id, opt);
}

function showBox(htmlContent, id, opt){
    var dealFuncContent = $j('.dealFuncContent');
    if (id == deal_id && dealFuncContent.css('display') != 'none' && option == last_option) 
        return;
    dealFuncContent.css('display', 'none');
    dealFuncContent.html(htmlContent);
    dealFuncContent.prepend('<a href="javascript:void(0)" onclick="hiddenBox();" style="float:right">X</a>');
    dealFuncContent.insertAfter('#dealfunc_' + id);
    dealFuncContent.slideDown();
    deal_id = id;
    last_option = option;
}

function hiddenBox(){
    var dealFuncContent = $j('.dealFuncContent');
    dealFuncContent.slideUp();
}

function doaddtofav(id, opt){
    hiddensubmitDIV();
    var params = $j('#' + opt + '_form').serialize();
    params += '&deal_id=' + id;
    $j.ajax({
        type: 'POST',
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=addToFavorite',
        dataType: 'text',
        data: params,
        error: function(error){
            alert(error);
            showsubmitDIV();
        },
        success: function(responseText){
            switch (responseText) {
                case 'NOT_AUTH_USER':
                    responseText = "<b>Info</b>: Please login first.";
                    break;
                case 'FAV_EXSIT':
                    responseText = "<b>Info</b>: This deal is aleady in your favorite.";
                    break;
                case 'SUCCESS':
                    responseText = "<b>Info</b>: Add succeeded.";
            }
            showPopupMsg(responseText);
            hiddenBox();
        }
    });
}

function dosharedeal(id, opt){
    if (!checkAllFields()) 
        return false;
    hiddensubmitDIV();
    var params = $j('#sharedeal_form').serialize();
    params += '&deal_id=' + id;
    $j.ajax({
        type: 'POST',
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=share',
        dataType: 'text',
        data: params,
        error: function(error){
            alert(error);
            showsubmitDIV();
        },
        success: function(response){
            showPopupMsg(response);
            hiddenBox();
        }
    });
}

function doreporterror(id, opt){
    if (!checkAllFields()) 
        return false;
    hiddensubmitDIV();
    var params = $j('#reporterror_form').serialize();
    params += '&deal_id=' + id;
    $j.ajax({
        type: 'POST',
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=reporterror',
        dataType: 'text',
        data: params,
        error: function(error){
            alert(error);
            showsubmitDIV();
        },
        success: function(response){
            if (response == 'SUCCESS') {
                msg = 'Submit succeeded! Thank you for your attention and carefulness.';
                showPopupMsg(msg);
                hiddenBox();
            }
            else 
                if (response == 'EMAIL_DO_NOT_MATCH') {
                    msg = 'please check your email format.';
                    showPopupMsg(msg);
                    showsubmitDIV();
                }
                else {
                    showPopupMsg(response);
                    hiddenBox();
                }
        }
    });
}

function dorate(id, opt){
    if (!checkAllFields()) 
        return false;
    hiddensubmitDIV();
    var params = $j('#' + opt + '_form').serialize();
    params += '&deal_id=' + id;
    $j.ajax({
        type: 'POST',
        url: 'index2.php?option=com_dealsmanager&controller=assistcontroller&task=rate',
        dataType: 'text',
        data: params,
        error: function(error){
            alert(error);
            showsubmitDIV();
        },
        success: function(response){
            //            switch (response) {
            //                case 'USER_AUTH_FAILED':
            //                    msg = 'Please login first.';
            //                    break;
            //                case 'RATING_RANGE_ERROR':
            //                    msg = 'Rating Error!';
            //                    break;
            //                case 'DEAL_ID_ERROR':
            //                    msg = 'No this deal or the deal has been expired.';
            //                    break;
            //                case 'RATE_SUCCESS':
            //                    msg = 'Rate succeeded.<br/>It will be shown after beening reviewed by administrator.';
            //                    break;
            //                default:
            //            }
            showPopupMsg(response);
            //            showsubmitDIV();
            hiddenBox();
        }
    });
}


function hiddensubmitDIV(){
    $j('.submitDIV').hide();
    $j('.loadingImg').show();
}

function showsubmitDIV(){
    $j('.loadingImg').hide();
    $j('.submitDIV').show();
}

function addItem(item){
    var toBeAdded = $j('.' + item + ':first-child');
    $j('#' + item).append('<div class="item">' + toBeAdded.html() + '</div>');
}

function checkAllFields(){
    $j(".required").each(function(){
        $j(this).blur();
    });
    if ($j(".invalid").length > 0) 
        return false;
    return true;
}

function checkEmpty(id){
    currentObject = $j('#' + id);
    if (currentObject.val() == null || currentObject.val() == '') 
        currentObject.addClass('invalid');
    else 
        currentObject.removeClass('invalid');
}

/**
 * Add suggested tags to the inputbox of tag.
 */
function addToTags(element){
    tags = $j('#tags');
    tagsVal = tags.val();
    tag = element.innerHTML;
    if (tagsVal == '' || tagsVal == null) {
        tags.val(tag);
    }
    else {
        tags.val(tagsVal + ',' + tag);
    }
    
}

function showPopupMsg(msg){
    var msgheader = "<div id=\"vmLogResult\"><div><div class=\"shop_info\">";
    var msgfooter = "<br />\n</div></div></div>";
    msg = msgheader + msg + msgfooter;
    document.boxB = new MooPrompt(notice_lbl, msg, {
        buttons: 1,
        width: 400,
        height: 150,
        overlay: false,
        button1: ok_lbl
    });
    setTimeout('document.boxB.close()', 15000);
}

function setCookie(name, value, expires, path, domain, secure){
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires *= 86400000;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
    (expires ? ";expires=" + expires_date.toGMTString() : "") +
    (path ? ";path=" + path : "") +
    (domain ? ";domain=" + domain : "") +
    (secure ? ";secure" : "");
}

function getCookie(name){
    var cookies = document.cookie.split(';');
    var cookie = '';
    
    for (var i = 0; i < cookies.length; i++) {
        cookie = cookies[i].split('=');
        if (cookie[0].replace(/^\s+|\s+$/g, '') == name) {
            return (cookie.length <= 1) ? "" : unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
        }
    }
    return null;
}

function delCookie(name, path, domain){
    document.cookie = name + "=" +
    (path ? ";path=" + path : "") +
    (domain ? ";domain=" + domain : "") +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}